PowerShell Guidance

Slug: pwsh

3655686 characters 450558 words

./enhance_pwsh_verbosity.sh <path_to_script.ps1> <output_file.txt> <topic1_no_prefix> <topic2_no_prefix> ...

./enhance_pwsh_verbosity.sh ./my_script.ps1 diagnostics.txt functions_advanced redirection debuggers

#!/bin/bash # ============================================================================== # PowerShell Verbosity Enhancement and Diagnostics Script # # This script automates the configuration of a target PowerShell script to # maximize its verbosity and gathers key diagnostic help topics. # It is designed to be idempotent and creates a backup of the modified script. # # WARNING: This script modifies the target PowerShell file in place. # It is highly recommended to use this on a project under version control # so you can review and revert changes easily. # ============================================================================== # --- Script Setup --- # Exit immediately if a command exits with a non-zero status. # Treat unset variables as an error. # Pipelines return the exit status of the last command to exit with a non-zero status. set -euo pipefail # --- Argument Parsing and Validation --- if [[ "$#" -lt 3 ]]; then echo "Error: Insufficient arguments." >&2 echo "Usage: $0 <path_to_script.ps1> <output_file.txt> <topic1_no_prefix> [topic2_no_prefix]..." >&2 echo "Example: $0./my_script.ps1 diagnostics.txt functions_advanced redirection" >&2 exit 1 fi SCRIPT_PATH="$1" OUTPUT_FILE="<span class="math-inline">2" shift 2 ABOUT\_TOPICS\=\("</span>@") # Validate that the target PowerShell script exists and is readable. if] ||]; then echo "Error: PowerShell script not found or is not readable at '$SCRIPT_PATH'" >&2 exit 1 fi # Check if PowerShell (pwsh) is installed and available in the PATH. if! command -v pwsh &> /dev/null; then echo "Error: PowerShell 'pwsh' command not found. Please install PowerShell for Debian." >&2 exit 1 fi echo "--- PowerShell Verbosity Enhancement Script ---" echo "Target Script: $SCRIPT_PATH" echo "Output File: $OUTPUT_FILE" echo "About Topics: ${ABOUT_TOPICS[*]}" echo "---------------------------------------------" echo "NOTE: For full support of common parameters (-Verbose, -Debug) on your script," echo "ensure it is an 'advanced function' by including before its param() block." echo "---------------------------------------------" # --- Step 1: Maximize Verbosity via Script Modification --- echo -e "\n--- Step 1: Modifying PowerShell script for maximum verbosity ---" # Define a unique marker to check if the script has already been modified. readonly MARKER="# SCRIPT_MODIFIED_BY_VERBOSITY_TOOL" if grep -qF "$MARKER" "<span class="math-inline">SCRIPT\_PATH"; then echo "Script has already been modified\. Skipping file alteration\." else \# Create a backup of the original script\. BACKUP\_PATH\="</span>{SCRIPT_PATH}.bak" echo "Creating backup of original script at '$BACKUP_PATH'..." cp "$SCRIPT_PATH" "$BACKUP_PATH" # Define the PowerShell code block to be injected for maximum verbosity. # This is based on the principles outlined in the research report. read -r -d '' PWSH_INJECTION_BLOCK <<'EOF' # --- Start of Injected Verbosity Code --- # This block was added by a script to maximize diagnostic output. # Set preference variables to force display of all verbose and debug messages # without needing to specify -Verbose or -Debug flags at runtime. # See about_Preference_Variables for more details. $VerbosePreference = 'Continue' <span class="math-inline">DebugPreference \= 'Continue' \# Enable the most detailed execution tracing and strict mode\. \[4, 5, 6\] \# \-Trace 2\: Logs script lines, variable assignments, and function calls\. \# \-Strict\: Throws an error if an uninitialized variable is referenced\. Set\-PSDebug \-Trace 2 \-Strict \# \-\-\- End of Injected Verbosity Code \-\-\- EOF \# Create a temporary file to construct the new script content\. TEMP\_FILE\=</span>(mktemp) # Handle shebang if it exists by writing it to the temp file first. HAS_SHEBANG=false if read -r FIRST_LINE < "$SCRIPT_PATH" &&]; then HAS_SHEBANG=true echo "$FIRST_LINE" > "$TEMP_FILE" fi # Add the marker and the injection block. echo "$MARKER" >> "$TEMP_FILE" echo "$PWSH_INJECTION_BLOCK" >> "$TEMP_FILE" echo "" >> "$TEMP_FILE" # Append the original script content, skipping the shebang if it was already handled. if $HAS_SHEBANG; then tail -n +2 "$SCRIPT_PATH" >> "$TEMP_FILE" else cat "$SCRIPT_PATH" >> "$TEMP_FILE" fi # Replace the original script with the modified version. mv "$TEMP_FILE" "$SCRIPT_PATH" echo "Successfully injected verbosity settings into '$SCRIPT_PATH'." fi # --- Step 2: Gather Diagnostic Information --- echo -e "\n--- Step 2: Gathering PowerShell 'about_*' help topics ---" # Initialize the output file, clearing any previous content. > "<span class="math-inline">OUTPUT\_FILE" for topic in "</span>{ABOUT_TOPICS[@]}"; do echo "Fetching help for 'about_$topic'..." { echo "=================================================" echo " HELP TOPIC: about_$topic" echo "=================================================" echo "" # Execute pwsh to get the help content for the specified topic. [1, 2] # Redirect stderr (2) to stdout (1) to capture "not found" messages in the output file. pwsh -Command "Get-Help about_$topic" 2>&1 echo "" } >> "$OUTPUT_FILE" done echo "'about_*' help topics have been saved to '<span class="math-inline">OUTPUT\_FILE'\." \# \-\-\- Finalization \-\-\- echo \-e "\\n\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-" echo "✅ Script finished successfully\!" echo "A backup of the original PowerShell script is available at '</span>{SCRIPT_PATH}.bak'." echo "Diagnostic information has been saved to '$OUTPUT_FILE'." echo "You can now run '$SCRIPT_PATH' to see highly verbose output."

<purpose>You are an expert AI assistant specializing in the powershell programming language. Your goal is to accurately fulfill the user's powershell-related request (`[[user_task_description]]`) by leveraging your comprehensive training knowledge *and* using the provided `[[powershell_reference_excerpts]]` as an authoritative steering context. Integrate information from the excerpts to enhance accuracy, provide specific grounding, and ensure your response aligns with the details and best practices mentioned in the references.</purpose> <context> <domain>powershell programming language assistance</domain> <knowledge_integration>You possess broad knowledge of powershell. The provided [[powershell_reference_excerpts]] offer specific, authoritative context that MUST be consulted and integrated to guide your response.</knowledge_integration> <prioritization>Where the [[powershell_reference_excerpts]] provide specific details relevant to the [[user_task_description]], prioritize that information as potentially more accurate or specific than your general knowledge.</prioritization> </context> <constraints> <constraint>Base your response on your understanding of powershell, guided and verified by the [[powershell_reference_excerpts]].</constraint> <constraint>Directly address all parts of the [[user_task_description]].</constraint> <constraint>Ensure any code generated adheres to powershell best practices, informed by the excerpts where applicable.</constraint> <constraint>If the excerpts clarify a subtle point or correct a common misunderstanding relevant to the task, incorporate that clarification into your response.</constraint> <constraint>Generate output in the appropriate format for the task (e.g., markdown text, powershell code blocks).</constraint> </constraints> <instructions> <instruction>1. Analyze the `[[user_task_description]]` to fully understand the user's need regarding powershell.</instruction> <instruction>2. Access your internal knowledge base about the powershell programming language relevant to the task.</instruction> <instruction>3. Carefully review the provided `[[powershell_reference_excerpts]]` to identify any information, rules, examples, or clarifications that directly apply to the `[[user_task_description]]`.</instruction> <instruction>4. Synthesize a response (e.g., explanation, code, debugging suggestions) that fulfills the user's request.</instruction> <instruction>5. **Crucially:** Integrate the relevant findings from `[[powershell_reference_excerpts]]` into your response. Use the excerpts to verify accuracy, provide specific details, ensure alignment with best practices, and correct potential misconceptions.</instruction> <instruction>6. If the excerpts provide significant clarification or detail crucial to the answer, briefly mention how the reference informed the response.</instruction> <instruction>7. Format the final output appropriately for the task (e.g., markdown for explanations, code blocks for powershell code).</instruction> </instructions> <input_data> <user_task_description> ''' [[user_task_description]]={ """ """ } ''' </user_task_description> <powershell_reference_excerpts> ::: [[powershell_reference_excerpts]]={ """ This file is a merged representation of a subset of the codebase, containing specifically included files and files not matching ignore patterns, combined into a single document by Repomix. The content has been processed where comments have been removed, empty lines have been removed, content has been compressed (code blocks are separated by ⋮---- delimiter), security check has been disabled. # File Summary ## Purpose This file contains a packed representation of the entire repository's contents. It is designed to be easily consumable by AI systems for analysis, code review, or other automated processes. ## File Format The content is organized as follows: 1. This summary section 2. Repository information 3. Directory structure 4. Repository files (if enabled) 5. Multiple file entries, each consisting of: a. A header with the file path (## File: path/to/file) b. The full contents of the file in a code block ## Usage Guidelines - This file should be treated as read-only. Any changes should be made to the original repository files, not this packed version. - When processing this file, use the file path to distinguish between different files in the repository. - Be aware that this file may contain sensitive information. Handle it with the same level of security as you would the original repository. ## Notes - Some files may have been excluded based on .gitignore rules and Repomix's configuration - Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files - Only files matching these patterns are included: reference/7.6/ - Files matching these patterns are excluded: **/About/ - Files matching patterns in .gitignore are excluded - Files matching default ignore patterns are excluded - Code comments have been removed from supported file types - Empty lines have been removed from all files - Content has been compressed - code blocks are separated by ⋮---- delimiter - Security check has been disabled - content may contain sensitive information - Files are sorted by Git change count (files with more changes are at the bottom) # Directory Structure

reference/ 7.6/ CimCmdlets/ CimCmdlets.md Get-CimAssociatedInstance.md Get-CimClass.md Get-CimInstance.md Get-CimSession.md Invoke-CimMethod.md New-CimInstance.md New-CimSession.md New-CimSessionOption.md Register-CimIndicationEvent.md Remove-CimInstance.md Remove-CimSession.md Set-CimInstance.md Microsoft.PowerShell.Archive/ Compress-Archive.md Expand-Archive.md Microsoft.PowerShell.Archive.md Microsoft.PowerShell.Core/ Add-History.md Clear-History.md Clear-Host.md Connect-PSSession.md Debug-Job.md Disable-ExperimentalFeature.md Disable-PSRemoting.md Disable-PSSessionConfiguration.md Disconnect-PSSession.md Enable-ExperimentalFeature.md Enable-PSRemoting.md Enable-PSSessionConfiguration.md Enter-PSHostProcess.md Enter-PSSession.md Exit-PSHostProcess.md Exit-PSSession.md Export-ModuleMember.md ForEach-Object.md Get-Command.md Get-ExperimentalFeature.md Get-Help.md Get-History.md Get-Job.md Get-Module.md Get-PSHostProcessInfo.md Get-PSSession.md Get-PSSessionCapability.md Get-PSSessionConfiguration.md Get-PSSubsystem.md Import-Module.md Invoke-Command.md Invoke-History.md Microsoft.PowerShell.Core.md New-Module.md New-ModuleManifest.md New-PSRoleCapabilityFile.md New-PSSession.md New-PSSessionConfigurationFile.md New-PSSessionOption.md New-PSTransportOption.md Out-Default.md Out-Host.md Out-Null.md Receive-Job.md Receive-PSSession.md Register-ArgumentCompleter.md Register-PSSessionConfiguration.md Remove-Job.md Remove-Module.md Remove-PSSession.md Save-Help.md Set-PSDebug.md Set-PSSessionConfiguration.md Set-StrictMode.md Start-Job.md Stop-Job.md Switch-Process.md TabExpansion2.md Test-ModuleManifest.md Test-PSSessionConfigurationFile.md Unregister-PSSessionConfiguration.md Update-Help.md Wait-Job.md Where-Object.md Microsoft.PowerShell.Diagnostics/ Get-Counter.md Get-WinEvent.md Microsoft.PowerShell.Diagnostics.md New-WinEvent.md Microsoft.PowerShell.Host/ Microsoft.PowerShell.Host.md Start-Transcript.md Stop-Transcript.md Microsoft.PowerShell.Management/ Add-Content.md Clear-Content.md Clear-Item.md Clear-ItemProperty.md Clear-RecycleBin.md Convert-Path.md Copy-Item.md Copy-ItemProperty.md Debug-Process.md Get-ChildItem.md Get-Clipboard.md Get-ComputerInfo.md Get-Content.md Get-HotFix.md Get-Item.md Get-ItemProperty.md Get-ItemPropertyValue.md Get-Location.md Get-Process.md Get-PSDrive.md Get-PSProvider.md Get-Service.md Get-TimeZone.md Invoke-Item.md Join-Path.md Microsoft.PowerShell.Management.md Move-Item.md Move-ItemProperty.md New-Item.md New-ItemProperty.md New-PSDrive.md New-Service.md Pop-Location.md Push-Location.md Remove-Item.md Remove-ItemProperty.md Remove-PSDrive.md Remove-Service.md Rename-Computer.md Rename-Item.md Rename-ItemProperty.md Resolve-Path.md Restart-Computer.md Restart-Service.md Resume-Service.md Set-Clipboard.md Set-Content.md Set-Item.md Set-ItemProperty.md Set-Location.md Set-Service.md Set-TimeZone.md Split-Path.md Start-Process.md Start-Service.md Stop-Computer.md Stop-Process.md Stop-Service.md Suspend-Service.md Test-Connection.md Test-Path.md Wait-Process.md Microsoft.PowerShell.Security/ ConvertFrom-SecureString.md ConvertTo-SecureString.md Get-Acl.md Get-AuthenticodeSignature.md Get-CmsMessage.md Get-Credential.md Get-ExecutionPolicy.md Get-PfxCertificate.md Microsoft.PowerShell.Security.md New-FileCatalog.md Protect-CmsMessage.md Set-Acl.md Set-AuthenticodeSignature.md Set-ExecutionPolicy.md Test-FileCatalog.md Unprotect-CmsMessage.md Microsoft.PowerShell.Utility/ Add-Member.md Add-Type.md Clear-Variable.md Compare-Object.md ConvertFrom-CliXml.md ConvertFrom-Csv.md ConvertFrom-Json.md ConvertFrom-Markdown.md ConvertFrom-SddlString.md ConvertFrom-StringData.md ConvertTo-CliXml.md ConvertTo-Csv.md ConvertTo-Html.md ConvertTo-Json.md ConvertTo-Xml.md Debug-Runspace.md Disable-PSBreakpoint.md Disable-RunspaceDebug.md Enable-PSBreakpoint.md Enable-RunspaceDebug.md Export-Alias.md Export-Clixml.md Export-Csv.md Export-FormatData.md Export-PSSession.md Format-Custom.md Format-Hex.md Format-List.md Format-Table.md Format-Wide.md Get-Alias.md Get-Culture.md Get-Date.md Get-Error.md Get-Event.md Get-EventSubscriber.md Get-FileHash.md Get-FormatData.md Get-Host.md Get-MarkdownOption.md Get-Member.md Get-PSBreakpoint.md Get-PSCallStack.md Get-Random.md Get-Runspace.md Get-RunspaceDebug.md Get-SecureRandom.md Get-TraceSource.md Get-TypeData.md Get-UICulture.md Get-Unique.md Get-Uptime.md Get-Variable.md Get-Verb.md Group-Object.md Import-Alias.md Import-Clixml.md Import-Csv.md Import-LocalizedData.md Import-PowerShellDataFile.md Import-PSSession.md Invoke-Expression.md Invoke-RestMethod.md Invoke-WebRequest.md Join-String.md Measure-Command.md Measure-Object.md Microsoft.PowerShell.Utility.md New-Alias.md New-Event.md New-Guid.md New-Object.md New-TemporaryFile.md New-TimeSpan.md New-Variable.md Out-File.md Out-GridView.md Out-Printer.md Out-String.md Read-Host.md Register-EngineEvent.md Register-ObjectEvent.md Remove-Alias.md Remove-Event.md Remove-PSBreakpoint.md Remove-TypeData.md Remove-Variable.md Select-Object.md Select-String.md Select-Xml.md Send-MailMessage.md Set-Alias.md Set-Date.md Set-MarkdownOption.md Set-PSBreakpoint.md Set-TraceSource.md Set-Variable.md Show-Command.md Show-Markdown.md Sort-Object.md Start-Sleep.md Tee-Object.md Test-Json.md Trace-Command.md Unblock-File.md Unregister-Event.md Update-FormatData.md Update-List.md Update-TypeData.md Wait-Debugger.md Wait-Event.md Write-Debug.md Write-Error.md Write-Host.md Write-Information.md Write-Output.md Write-Progress.md Write-Verbose.md Write-Warning.md Microsoft.WSMan.Management/ Connect-WSMan.md Disable-WSManCredSSP.md Disconnect-WSMan.md Enable-WSManCredSSP.md Get-WSManCredSSP.md Get-WSManInstance.md Invoke-WSManAction.md Microsoft.WSMan.Management.md New-WSManInstance.md New-WSManSessionOption.md Remove-WSManInstance.md Set-WSManInstance.md Set-WSManQuickConfig.md Test-WSMan.md PSDiagnostics/ Disable-PSTrace.md Disable-PSWSManCombinedTrace.md Disable-WSManTrace.md Enable-PSTrace.md Enable-PSWSManCombinedTrace.md Enable-WSManTrace.md Get-LogProperties.md PSDiagnostics.md Set-LogProperties.md Start-Trace.md Stop-Trace.md PSReadLine/ Get-PSReadLineKeyHandler.md Get-PSReadLineOption.md PSConsoleHostReadLine.md PSReadLine.md Remove-PSReadLineKeyHandler.md Set-PSReadLineKeyHandler.md Set-PSReadLineOption.md ThreadJob/ Start-ThreadJob.md ThreadJob.md

# Files ## File: reference/7.6/CimCmdlets/CimCmdlets.md ````markdown --- Download Help Link: https://aka.ms/powershell75-help Help Version: 7.6.0.0 Locale: en-US Module Guid: fb6cc51d-c096-4b38-b78d-0fed6277096a Module Name: CimCmdlets ms.date: 02/20/2019 schema: 2.0.0 title: CimCmdlets Module --- # CimCmdlets Module ## Description Contains cmdlets that interact with Common Information Model (CIM) Servers like the Windows Management Instrumentation (WMI) service. This module is only available on the Windows platform. ## CimCmdlets Cmdlets ### [Get-CimAssociatedInstance](Get-CimAssociatedInstance.md) Retrieves the CIM instances that are connected to a specific CIM instance by an association. ### [Get-CimClass](Get-CimClass.md) Gets a list of CIM classes in a specific namespace. ### [Get-CimInstance](Get-CimInstance.md) Gets the CIM instances of a class from a CIM server. ### [Get-CimSession](Get-CimSession.md) Gets the CIM session objects from the current session. ### [Invoke-CimMethod](Invoke-CimMethod.md) Invokes a method of a CIM class. ### [New-CimInstance](New-CimInstance.md) Creates a CIM instance. ### [New-CimSession](New-CimSession.md) Creates a CIM session. ### [New-CimSessionOption](New-CimSessionOption.md) Specifies advanced options for the New-CimSession cmdlet. ### [Register-CimIndicationEvent](Register-CimIndicationEvent.md) Subscribes to indications using a filter expression or a query expression. ### [Remove-CimInstance](Remove-CimInstance.md) Removes a CIM instance from a computer. ### [Remove-CimSession](Remove-CimSession.md) Removes one or more CIM sessions. ### [Set-CimInstance](Set-CimInstance.md) Modifies a CIM instance on a CIM server by calling the ModifyInstance method of the CIM class.

#File: reference/7.6/CimCmdlets/Get-CimAssociatedInstance.md

--- external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml Locale: en-US Module Name: CimCmdlets ms.date: 05/31/2024 online version: https://learn.microsoft.com/powershell/module/cimcmdlets/get-cimassociatedinstance?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-CimAssociatedInstance --- # Get-CimAssociatedInstance ## SYNOPSIS Retrieves the CIM instances that are connected to a specific CIM instance by an association. ## SYNTAX ### ComputerSet (Default) ``` Get-CimAssociatedInstance [[-Association] <String>] [-ResultClassName <String>] [-InputObject] <CimInstance> [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-ResourceUri <Uri>] [-ComputerName <String[]>] [-KeyOnly] [<CommonParameters>] ``` ### SessionSet ``` Get-CimAssociatedInstance [[-Association] <String>] [-ResultClassName <String>] [-InputObject] <CimInstance> [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-ResourceUri <Uri>] -CimSession <CimSession[]> [-KeyOnly] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Get-CimAssociatedInstance` cmdlet retrieves the CIM instances connected to a specific CIM instance, called the source instance, by an association. In an association, each CIM instance has a named role and the same CIM instance can participate in an association in different roles. If the **InputObject** parameter isn't specified, the cmdlet works in one of the following ways: - If neither the **ComputerName** parameter nor the **CimSession** parameter is specified, then this cmdlet works on local Windows Management Instrumentation (WMI) using a Component Object Model (COM) session. - If either the **ComputerName** parameter or the **CimSession** parameter is specified, then this cmdlet works against the CIM server specified by either the **ComputerName** parameter or the **CimSession** parameter. ## EXAMPLES ### Example 1: Get all the associated instances of a specific instance ```powershell $disk = Get-CimInstance -ClassName Win32_LogicalDisk -KeyOnly Get-CimAssociatedInstance -InputObject $disk[1] ``` This set of commands retrieves the instances of the class named **Win32_LogicalDisk** and stores the information in a variable named `$disk` using the `Get-CimInstance` cmdlet. The first logical disk instance in the variable is then used as the input object for the `Get-CimAssociatedInstance` cmdlet to get all the associated CIM instances of the specified CIM instance. ### Example 2: Get all the associated instances of a specific type ```powershell $disk = Get-CimInstance -ClassName Win32_LogicalDisk -KeyOnly Get-CimAssociatedInstance -InputObject $disk[1] -ResultClass Win32_DiskPartition ``` This set of commands retrieves all the instances of the **Win32_LogicalDisk** class and stores them in a variable named `$disk`. The first logical disk instance in the variable is then used as the input object for the `Get-CimAssociatedInstance` cmdlet to get all the associated instances that are associated through the specified association class **Win32_DiskPartition**. ### Example 3: Get all the associated instances through qualifier of a specific class This set of commands retrieves the services that depend on the **Winmgmt** service and stores them in a variable named `$s`. `Get-CimAssociatedInstance` gets the associated instances of the retrieved association class. ```powershell $s = Get-CimInstance -Query "Select * from Win32_Service where name like 'Winmgmt'" Get-CimAssociatedInstance -InputObject $s -Association Win32_DependentService ``` ```Output ProcessId Name StartMode State Status ExitCode --------- ---- --------- ----- ------ -------- 1716 RpcSs Auto Running OK 0 9964 CcmExec Auto Running OK 0 0 HgClientService Manual Stopped OK 1077 0 smstsmgr Manual Stopped OK 1077 3396 vmms Auto Running OK 0 ``` ## PARAMETERS ### -Association Specifies the name of the association class. If you don't specify this parameter, the cmdlet returns all existing association objects of any type. For example, if class A is associated with class B through two associations, AB1 and AB2, then this parameter can be used to specify the type of association, either AB1 or AB2. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -CimSession Runs the command using the specified CIM session. Enter a variable that contains the CIM session, or a command that creates or gets the CIM session, such as `New-CimSession` or `Get-CimSession`. For more information, see [about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md). ```yaml Type: Microsoft.Management.Infrastructure.CimSession[] Parameter Sets: SessionSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -ComputerName Specifies the name of the computer on which you want to run the CIM operation. You can specify a fully qualified domain name (FQDN) or a NetBIOS name. If you specify this parameter, the cmdlet creates a temporary session to the specified computer using the WsMan protocol. If you don't specify this parameter, the cmdlet performs the operation on the local computer using Component Object Model (COM). If multiple operations are being performed on the same computer, connecting using a CIM session gives better performance. ```yaml Type: System.String[] Parameter Sets: ComputerSet Aliases: CN, ServerName Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the input to this cmdlet. You can use this parameter, or you can pipe the input to this cmdlet. The **InputObject** parameter doesn't enumerate over collections. If a collection is passed, an error is thrown. When working with collections, pipe the input to enumerate the values. ```yaml Type: Microsoft.Management.Infrastructure.CimInstance Parameter Sets: (All) Aliases: CimInstance Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -KeyOnly Returns objects with only key properties populated. This reduces the amount of data that's transferred over the network. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Namespace Specifies the namespace for the CIM operation. The default namespace is **root/CIMV2**. > [!NOTE] > You can use tab completion to browse the list of namespaces, because PowerShell gets a list of > namespaces from the local WMI server to provide the list of namespaces. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -OperationTimeoutSec Specifies the amount of time that the cmdlet waits for a response from the computer. By default, the value of this parameter is 0, which means that the cmdlet uses the default timeout value for the server. If the **OperationTimeoutSec** parameter is set to a value less than the robust connection retry timeout of 3 minutes, network failures that last more than the value of the **OperationTimeoutSec** parameter aren't recoverable, because the operation on the server times out before the client can reconnect. ```yaml Type: System.UInt32 Parameter Sets: (All) Aliases: OT Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ResourceUri Specifies the resource uniform resource identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer. A URI consists of a prefix and a path to a resource. For example: - `http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk` - `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings` By default, if you don't specify this parameter, the DMTF standard resource URI `http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/` is used and the class name is appended to it. **ResourceUri** can only be used with CIM sessions created using the WSMan protocol, or when specifying the **ComputerName** parameter, which creates a CIM session using WSMan. If you specify this parameter without specifying the **ComputerName** parameter, or if you specify a CIM session created using DCOM protocol, you get an error, because the DCOM protocol doesn't support the **ResourceUri** parameter. If both the **ResourceUri** parameter and the **Filter** parameter are specified, the **Filter** parameter is ignored. ```yaml Type: System.Uri Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ResultClassName Specifies the class name of the associated instances. A CIM instance can be associated with one or more CIM instances. All associated CIM instances are returned if you don't specify the result class name. By default, the value of this parameter is null, and all associated CIM instances are returned. You can filter the association results to match a specific class name. Filtering happens on the server. If this parameter isn't specified, `Get-CimAssociatedInstance` returns all existing associations. For example, if class A is associated with classes B, C and D, then this parameter can be used to restrict the output to a specific type (B, C or D). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.Management.Infrastructure.CimInstance This cmdlet returns a CIM instance object. ## NOTES PowerShell includes the following aliases for `Get-CimAssociatedInstance`: - Windows: - `gcai` This cmdlet is only available on Windows platforms. ## RELATED LINKS [Get-CimClass](Get-CimClass.md) [Get-CimInstance](Get-CimInstance.md)

#File: reference/7.6/CimCmdlets/Get-CimClass.md

--- external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml Locale: en-US Module Name: CimCmdlets ms.date: 09/11/2023 online version: https://learn.microsoft.com/powershell/module/cimcmdlets/get-cimclass?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-CimClass --- # Get-CimClass ## SYNOPSIS Gets a list of CIM classes in a specific namespace. ## SYNTAX ### ComputerSet (Default) ``` Get-CimClass [[-ClassName] <string>] [[-Namespace] <string>] [-Amended] [-OperationTimeoutSec <uint>] [-ComputerName <string[]>] [-MethodName <string>] [-PropertyName <string>] [-QualifierName <string>] [<CommonParameters>] ``` ### SessionSet ``` Get-CimClass [[-ClassName] <string>] [[-Namespace] <string>] -CimSession <CimSession[]> [-Amended] [-OperationTimeoutSec <uint>] [-MethodName <string>] [-PropertyName <string>] [-QualifierName <string>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Get-CimClass` cmdlet retrieves a list of CIM classes in a specific namespace. If there is no class name supplied, then the cmdlet returns all the classes in the namespace. Unlike a CIM instance, CIM classes do not contain the CIM session or computer name from which they are retrieved. ## EXAMPLES ### Example 1: Get all the class definitions This example gets all the class definitions under the namespace **root/CIMV2**. ```powershell Get-CimClass ``` ### Example 2: Get the classes with a specific name This example gets the classes that contain the word **Disk** in their names. ```powershell Get-CimClass -ClassName *Disk* ``` ### Example 3: Get the classes with a specific method name This example gets the classes that start with the name **Win32** and have a method name that starts with **Term**. ```powershell Get-CimClass -ClassName Win32* -MethodName Term* ``` ### Example 4: Get the classes with a specific property name This example gets the classes that start with the name **Win32** and have a property named **Handle**. ```powershell Get-CimClass -ClassName Win32* -PropertyName Handle ``` ### Example 5: Get the classes with a specific qualifier name This example gets the classes that start with the name **Win32**, contain the word **Disk** in their names and have the specified qualifier **Association**. ```powershell Get-CimClass -ClassName Win32*Disk* -QualifierName Association ``` ### Example 6: Get the class definitions from a specific namespace This example gets the class definitions that contain the word **Net** in their names from the specified namespace **root/StandardCimv2**. ```powershell Get-CimClass -Namespace root/StandardCimv2 -ClassName *Net* ``` ### Example 7: Get the class definitions from a remote server This example gets the class definitions that contain the word **Disk** in their names from the specified remote servers **Server01** and **Server02**. ```powershell Get-CimClass -ClassName *Disk* -ComputerName Server01, Server02 ``` ### Example 8: Get the classes by using a CIM session ```powershell $s = New-CimSession -ComputerName Server01, Server02 Get-CimClass -ClassName *Disk* -CimSession $s ``` This set of commands creates a session with multiple computers and stores it into a variable `$s` using the `New-CimSession` cmdlet, and then gets the classes using the `Get-CimClass` cmdlet. ## PARAMETERS ### -Amended Indicates that objects returned from the CIM query should contain amended information. Typically, amended information is localizable information, such as object and property descriptions that are attached to the CIM object. This is useful for translating numeric values to human-readable values. This parameter was added in PowerShell 7.3. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CimSession Runs the cmdlet in a remote session or on a remote computer. Enter a computer name or a session object, such as the output of a `New-CimSession` or `Get-CimSession` cmdlet. The default is the current session on the local computer. ```yaml Type: Microsoft.Management.Infrastructure.CimSession[] Parameter Sets: SessionSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -ClassName Specifies the name of the CIM class for which to perform the operation. You can use tab completion to browse the list of classes, because PowerShell gets a list of classes from the local WMI server to provide a list of class names. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -ComputerName Specifies the computer on which you want to run the CIM operation. You can specify a fully qualified domain name (FQDN) a NetBIOS name, or an IP address. If you specify this parameter, the cmdlet creates a temporary session to the specified computer using the WsMan protocol. If you do not specify this parameter, the cmdlet performs the operation on the local computer using Component Object Model (COM). If multiple operations are being performed on the same computer, using a CIM session gives better performance. ```yaml Type: System.String[] Parameter Sets: ComputerSet Aliases: CN, ServerName Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -MethodName Finds the classes that have a method matching this name. You can use wildcard characters with this parameter. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Namespace Specifies the namespace for CIM operation. The default namespace is **root/CIMV2**. You can use tab completion to browse the list of namespaces, because PowerShell gets a list of namespaces from the local WMI server to provide the list of namespaces. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -OperationTimeoutSec Specifies the amount of time that the cmdlet waits for a response from the computer. By default, the value of this parameter is 0, which means that the cmdlet uses the default timeout value for the server. If the **OperationTimeoutSec** parameter is set to a value less than the robust connection retry timeout of 3 minutes, network failures that last more than the value of the **OperationTimeoutSec** parameter are not recoverable, because the operation on the server times out before the client can reconnect. ```yaml Type: System.UInt32 Parameter Sets: (All) Aliases: OT Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PropertyName Finds the classes which have a property matching this name. You can use wildcard characters with this parameter. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -QualifierName Filters the classes by class level qualifier name. You can use wildcard characters with this parameter. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.Management.Infrastructure.CimClass This cmdlet returns a CIM class object. ## NOTES PowerShell includes the following aliases for `Get-CimClass`: - Windows: - `gcls` This cmdlet is only available on Windows platforms. ## RELATED LINKS [New-CimSession](New-CimSession.md)

#File: reference/7.6/CimCmdlets/Get-CimInstance.md

--- external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml Locale: en-US Module Name: CimCmdlets ms.date: 06/28/2023 online version: https://learn.microsoft.com/powershell/module/cimcmdlets/get-ciminstance?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-CimInstance --- # Get-CimInstance ## SYNOPSIS Gets the CIM instances of a class from a CIM server. ## SYNTAX ### ClassNameComputerSet (Default) ``` Get-CimInstance [-ClassName] <String> [-ComputerName <String[]>] [-KeyOnly] [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-QueryDialect <String>] [-Shallow] [-Filter <String>] [-Property <String[]>] [<CommonParameters>] ``` ### ResourceUriSessionSet ``` Get-CimInstance -CimSession <CimSession[]> -ResourceUri <Uri> [-KeyOnly] [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-Shallow] [-Filter <String>] [-Property <String[]>] [<CommonParameters>] ``` ### QuerySessionSet ``` Get-CimInstance -CimSession <CimSession[]> [-ResourceUri <Uri>] [-Namespace <String>] [-OperationTimeoutSec <UInt32>] -Query <String> [-QueryDialect <String>] [-Shallow] [<CommonParameters>] ``` ### ClassNameSessionSet ``` Get-CimInstance -CimSession <CimSession[]> [-ClassName] <String> [-KeyOnly] [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-QueryDialect <String>] [-Shallow] [-Filter <String>] [-Property <String[]>] [<CommonParameters>] ``` ### CimInstanceSessionSet ``` Get-CimInstance -CimSession <CimSession[]> [-ResourceUri <Uri>] [-OperationTimeoutSec <UInt32>] [-InputObject] <CimInstance> [<CommonParameters>] ``` ### CimInstanceComputerSet ``` Get-CimInstance [-ResourceUri <Uri>] [-ComputerName <String[]>] [-OperationTimeoutSec <UInt32>] [-InputObject] <CimInstance> [<CommonParameters>] ``` ### ResourceUriComputerSet ``` Get-CimInstance -ResourceUri <Uri> [-ComputerName <String[]>] [-KeyOnly] [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-Shallow] [-Filter <String>] [-Property <String[]>] [<CommonParameters>] ``` ### QueryComputerSet ``` Get-CimInstance [-ResourceUri <Uri>] [-ComputerName <String[]>] [-Namespace <String>] [-OperationTimeoutSec <UInt32>] -Query <String> [-QueryDialect <String>] [-Shallow] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Get-CimInstance` cmdlet gets the CIM instances of a class from a CIM server. You can specify either the class name or a query for this cmdlet. This cmdlet returns one or more CIM instance objects representing a snapshot of the CIM instances present on the CIM server. If the **InputObject** parameter is not specified, the cmdlet works in one of the following ways: - If neither the **ComputerName** parameter nor the **CimSession** parameter is specified, then this cmdlet works on local Windows Management Instrumentation (WMI) using a Component Object Model (COM) session. - If either the **ComputerName** parameter or the **CimSession** parameter is specified, then this cmdlet works against the CIM server specified by either the **ComputerName** parameter or the **CimSession** parameter. If the **InputObject** parameter is specified, the cmdlet works in one of the following ways: - If neither the **ComputerName** parameter nor the **CimSession** parameter is specified, then this cmdlet uses the CIM session or computer name from the input object. - If the either the **ComputerName** parameter or the **CimSession** parameter is specified, then this cmdlet uses the either the CimSession parameter value or **ComputerName** parameter value. ## EXAMPLES ### Example 1: Get the CIM instances of a specified class This example retrieves the CIM instances of a class named **Win32_Process**. ```powershell Get-CimInstance -ClassName Win32_Process ``` ### Example 2: Get a list of namespaces from a WMI server This example retrieves a list of namespaces under the **root** namespace on a WMI server. ```powershell Get-CimInstance -Namespace root -ClassName __Namespace ``` ### Example 3: Get instances of a class filtered by using a query This example retrieves all the CIM instances that start with the letter **P** of a class named **Win32_Process** using the query specified by a **Query** parameter. ```powershell Get-CimInstance -Query "SELECT * from Win32_Process WHERE name LIKE 'P%'" ``` ### Example 4: Get instances of a class filtered by using a class name and a filter expression This example retrieves all the CIM instances that start with the letter **P** of a class named **Win32_Process** using the Filter parameter. ```powershell Get-CimInstance -ClassName Win32_Process -Filter "Name like 'P%'" ``` ### Example 5: Get the CIM instances with only key properties filled in This example creates a new CIM instance in memory for a class named **Win32_Process** with the key property `@{ "Handle"=0 }` and stores it in a variable named `$x`. The variable is passed as a CIM instance to the `Get-CimInstance` cmdlet to get a particular instance. ```powershell $instance = @{ ClassName = 'Win32_Process' Namespace = 'root/cimv2' Properties = @{ Handle = 0 } Key = 'Handle' ClientOnly = $true } $x = New-CimInstance @instance Get-CimInstance -CimInstance $x ``` ### Example 6: Retrieve CIM instances and reuse them This example gets the CIM instances of a class named **Win32_Process** and stores them in the variables `$x` and `$y`. The variable `$x` is then formatted in a table containing only the **Name** and **KernelModeTime** properties, the table set to **AutoSize**. ```powershell $x, $y = Get-CimInstance -ClassName Win32_Process $x | Format-Table -Property Name, KernelModeTime -AutoSize ``` ```Output Name KernelModeTime ---- -------------- System Idle Process 157238797968750 ``` ### Example 7: Get CIM instances from remote computer This example retrieves the CIM instances of a class named **Win32_ComputerSystem** from the remote computers named **Server01** and **Server02**. ```powershell Get-CimInstance -ClassName Win32_ComputerSystem -ComputerName Server01, Server02 ``` ### Example 8: Getting only the key properties, instead of all properties This example retrieves only the key properties, which reduces the size of the object and network traffic. ```powershell $x = Get-CimInstance -Class Win32_Process -KeyOnly $x | Invoke-CimMethod -MethodName GetOwner ``` ### Example 9: Getting only a subset of properties, instead of all properties This example retrieves only a subset of properties, which reduces the size of the object and network traffic. ```powershell Get-CimInstance -Class Win32_Process -Property Name, KernelModeTime $x = Get-CimInstance -Class Win32_Process -Property Name, KernelModeTime $x | Invoke-CimMethod -MethodName GetOwner ``` The instance retrieved with the **Property** parameter can be used to perform other CIM operations, for example `Set-CimInstance` or `Invoke-CimMethod`. ### Example 10: Get the CIM instance using CIM session This example creates a CIM session on the computers named **Server01** and **Server02** using the `New-CimSession` cmdlet and stores the session information in a variable named `$s`. The contents of the variable are then passed to `Get-CimInstance` by using the **CimSession** parameter, to get the CIM instances of the class named **Win32_ComputerSystem**. ```powershell $s = New-CimSession -ComputerName Server01, Server02 Get-CimInstance -ClassName Win32_ComputerSystem -CimSession $s ``` ## PARAMETERS ### -CimSession Specifies the CIM session to use for this cmdlet. Enter a variable that contains the CIM session or a command that creates or gets the CIM session, such as the `New-CimSession` or `Get-CimSession` cmdlets. For more information, see [about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md). ```yaml Type: Microsoft.Management.Infrastructure.CimSession[] Parameter Sets: ResourceUriSessionSet, QuerySessionSet, ClassNameSessionSet, CimInstanceSessionSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -ClassName Specifies the name of the CIM class for which to retrieve the CIM instances. You can use tab completion to browse the list of classes, because PowerShell gets a list of classes from the local WMI server to provide a list of class names. ```yaml Type: System.String Parameter Sets: ClassNameComputerSet, ClassNameSessionSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ComputerName Specifies computer on which you want to run the CIM operation. You can specify a fully qualified domain name (FQDN), a NetBIOS name, or an IP address. If you do not specify this parameter, the cmdlet performs the operation on the local computer using Component Object Model (COM). If you specify this parameter, the cmdlet creates a temporary session to the specified computer using the WsMan protocol. If multiple operations are being performed on the same computer, connect using a CIM session for better performance. ```yaml Type: System.String[] Parameter Sets: ClassNameComputerSet, CimInstanceComputerSet, ResourceUriComputerSet, QueryComputerSet Aliases: CN, ServerName Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Filter Specifies a where clause to use as a filter. Specify the clause in either the **WQL** or the **CQL** query language. Do not include the `WHERE` keyword in the value of the parameter. ```yaml Type: System.String Parameter Sets: ClassNameComputerSet, ResourceUriSessionSet, ClassNameSessionSet, ResourceUriComputerSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InputObject Specifies a CIM instance object to use as input. If you are already working with a CIM instance object, you can use this parameter to pass the CIM instance object in order to get the latest snapshot from the CIM server. When you pass a CIM instance object as an input, `Get-CimInstance` returns the object from server using a get CIM operation, instead of an enumerate or query operation. Using a get CIM operation is more efficient than retrieving all instances and then filtering them. The **InputObject** parameter doesn't enumerate over collections. If a collection is passed, an error is thrown. When working with collections, pipe the input to enumerate the values. If the CIM class does not implement the get operation, then specifying the **InputObject** parameter returns an error. ```yaml Type: Microsoft.Management.Infrastructure.CimInstance Parameter Sets: CimInstanceSessionSet, CimInstanceComputerSet Aliases: CimInstance Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -KeyOnly Indicates that only objects with key properties populated are returned. Specifying the **KeyOnly** parameter reduces the amount of data transferred over the network. Use the **KeyOnly** parameter to return only a small portion of the object, which can be used for other operations, such as the `Set-CimInstance` or `Get-CimAssociatedInstance` cmdlets. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ClassNameComputerSet, ResourceUriSessionSet, ClassNameSessionSet, ResourceUriComputerSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Namespace Specifies the namespace of CIM class. The default namespace is **root/CIMV2**. You can use tab completion to browse the list of namespaces, because PowerShell gets a list of namespaces from the local WMI server to provide the list of namespaces. ```yaml Type: System.String Parameter Sets: ClassNameComputerSet, ResourceUriSessionSet, QuerySessionSet, ClassNameSessionSet, ResourceUriComputerSet, QueryComputerSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -OperationTimeoutSec Specifies the amount of time that the cmdlet waits for a response from the computer. By default, the value of this parameter is 0, which means that the cmdlet uses the default timeout value for the server. If the **OperationTimeoutSec** parameter is set to a value less than the robust connection retry timeout of 3 minutes, network failures that last more than the value of the **OperationTimeoutSec** parameter are not recoverable, because the operation on the server times out before the client can reconnect. ```yaml Type: System.UInt32 Parameter Sets: (All) Aliases: OT Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Property Specifies a set of instance properties to retrieve. Use this parameter when you need to reduce the size of the object returned, either in memory or over the network. The object returned also contains the key properties even if you have not listed them using the **Property** parameter. Other properties of the class are present but they are not populated. ```yaml Type: System.String[] Parameter Sets: ClassNameComputerSet, ResourceUriSessionSet, ClassNameSessionSet, ResourceUriComputerSet Aliases: SelectProperties Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Query Specifies a query to run on the CIM server. If the value specified contains double quotes `"`, single quotes `'`, or a backslash `\`, you must escape those characters by prefixing them with the backslash character. If the value specified uses the WQL **LIKE** operator, then you must escape the following characters by enclosing them in square brackets `[]`: percent `%`, underscore `_`, or opening square bracket `[`. You cannot use a metadata query to retrieve a list of classes or an event query. To retrieve a list of classes, use the `Get-CimClass` cmdlet. To retrieve an event query, use the `Register-CimIndicationEvent` cmdlet. You can specify the query dialect using the **QueryDialect** parameter. ```yaml Type: System.String Parameter Sets: QuerySessionSet, QueryComputerSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -QueryDialect Specifies the query language used for the Query parameter. The acceptable values for this parameter are: **WQL** or **CQL**. The default value is **WQL**. ```yaml Type: System.String Parameter Sets: ClassNameComputerSet, QuerySessionSet, ClassNameSessionSet, QueryComputerSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ResourceUri Specifies the resource uniform resource identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer. A URI consists of a prefix and a path to a resource. For example: - `http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk` - `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings` By default, if you do not specify this parameter, the DMTF standard resource URI `http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/` is used and the class name is appended to it. **ResourceUri** can only be used with CIM sessions created using the WSMan protocol, or when specifying the **ComputerName** parameter, which creates a CIM session using WSMan. If you specify this parameter without specifying the **ComputerName** parameter, or if you specify a CIM session created using DCOM protocol, you will get an error, because the DCOM protocol does not support the **ResourceUri** parameter. If both the **ResourceUri** parameter and the **Filter** parameter are specified, the **Filter** parameter is ignored. ```yaml Type: System.Uri Parameter Sets: ResourceUriSessionSet, ResourceUriComputerSet, QuerySessionSet, QueryComputerSet, CimInstanceSessionSet, CimInstanceComputerSet Aliases: Required: True (ResourceUriSessionSet, ResourceUriComputerSet), False (QuerySessionSet, QueryComputerSet, CimInstanceSessionSet, CimInstanceComputerSet) Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Shallow Indicates that the instances of a class are returned without including the instances of any child classes. By default, the cmdlet returns the instances of a class and its child classes. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ClassNameComputerSet, ResourceUriSessionSet, QuerySessionSet, ClassNameSessionSet, ResourceUriComputerSet, QueryComputerSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### Microsoft.Management.Infrastructure.CimInstance You can pipe a CIM instance object to this cmdlet. ## OUTPUTS ### Microsoft.Management.Infrastructure.CimInstance This cmdlet returns one or more CIM instance objects representing a snapshot of the CIM instances on the CIM server. ## NOTES PowerShell includes the following aliases for `Get-CimInstance`: - Windows: - `gcim` This cmdlet is only available on Windows platforms. ## RELATED LINKS [Format-Table](../Microsoft.Powershell.Utility/Format-Table.md) [Get-CimAssociatedInstance](Get-CimAssociatedInstance.md) [Get-CimClass](Get-CimClass.md) [Invoke-CimMethod](Invoke-CimMethod.md) [New-CimInstance](New-CimInstance.md) [Register-CimIndicationEvent](Register-CimIndicationEvent.md) [Remove-CimInstance](Remove-CimInstance.md) [Set-CimInstance](Set-CimInstance.md)

#File: reference/7.6/CimCmdlets/Get-CimSession.md

--- external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml Locale: en-US Module Name: CimCmdlets ms.date: 06/28/2023 online version: https://learn.microsoft.com/powershell/module/cimcmdlets/get-cimsession?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-CimSession --- # Get-CimSession ## SYNOPSIS Gets the CIM session objects from the current session. ## SYNTAX ### ComputerNameSet (Default) ``` Get-CimSession [[-ComputerName] <String[]>] [<CommonParameters>] ``` ### SessionIdSet ``` Get-CimSession [-Id] <UInt32[]> [<CommonParameters>] ``` ### InstanceIdSet ``` Get-CimSession -InstanceId <Guid[]> [<CommonParameters>] ``` ### NameSet ``` Get-CimSession -Name <String[]> [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** By default, the cmdlet gets all of the CIM sessions created in the current PowerShell session. You can use the parameters of `Get-CimSession` to get the sessions that are for particular computers, or you can identify sessions by their names or other identifiers. `Get-CimSession` does not get CIM sessions that were created in other PowerShell sessions or that were created on other computers. For more information about CIM sessions, see [about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md). ## EXAMPLES ### Example 1: Get CIM sessions from the current PowerShell session This example creates CIM sessions using [New-CimSession](New-CimSession.md), and then gets the CIM sessions using `Get-CimSession`. ```powershell New-CimSession -ComputerName Server01, Server02 Get-CimSession ``` ```Output Id : 1 Name : CimSession1 InstanceId : d1413bc3-162a-4cb8-9aec-4d2c61253d59 ComputerName : Server01 Protocol : WSMAN Id : 2 Name : CimSession2 InstanceId : c0095981-52c5-4e7f-a5bb-c4c680541710 ComputerName : Server02 Protocol : WSMAN ``` ### Example 2: Get the CIM sessions to a specific computer This example gets the CIM sessions that are connected to the computer named **Server02**. ```powershell Get-CimSession -ComputerName Server02 ``` ```Output Id : 2 Name : CimSession2 InstanceId : c0095981-52c5-4e7f-a5bb-c4c680541710 ComputerName : Server02 Protocol : WSMAN ``` ### Example 3: Get a list of CIM sessions and then format the list This example gets all CIM sessions in the current PowerShell session and displays a table containing only the **ComputerName** and **InstanceId** properties. ```powershell Get-CimSession | Format-Table -Property ComputerName, InstanceId ``` ```Output ComputerName InstanceId ------------ ---------- Server01 d1413bc3-162a-4cb8-9aec-4d2c61253d59 Server02 c0095981-52c5-4e7f-a5bb-c4c680541710 ``` ### Example 4: Get all the CIM sessions that have specific names This example gets all CIM sessions that have names that begin with **Serv**. ```powershell Get-CimSession -ComputerName Serv* ``` ```Output Id : 1 Name : CimSession1 InstanceId : d1413bc-162a-4cb8-9aec-4d2c61253d59 ComputerName : Server01 Protocol : WSMAN Id : 2 Name : CimSession2 InstanceId : c0095981-52c5-4e7f-a5bb-c4c680541710 ComputerName : Server02 Protocol : WSMAN ``` ### Example 5: Get a specific CIM session This example gets the CIM session that has an **Id** of 2. ```powershell Get-CimSession -Id 2 ``` ```Output Id : 2 Name : CimSession2 InstanceId : c0095981-52c5-4e7f-a5bb-c4c680541710 ComputerName : Server02 Protocol : WSMAN ``` ## PARAMETERS ### -ComputerName Specifies the name of the computer to get CIM sessions connected to. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: ComputerNameSet Aliases: CN, ServerName Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Id Specifies the identifier of the CIM session to get. For multiple IDs, use commas to separate the IDs or use the range operator (`..`) to specify a range of IDs. An **Id** is an integer that uniquely identifies the CIM session within the current PowerShell session. For more information about the range operator, see [about_Operators](../Microsoft.PowerShell.Core/About/about_Operators.md). ```yaml Type: System.UInt32[] Parameter Sets: SessionIdSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InstanceId Specifies the instance IDs of the CIM session to get. **InstanceId** is a globally-unique identifier (GUID) that uniquely identifies a CIM session. The **InstanceId** is unique, even when you have multiple sessions running in PowerShell. The **InstanceId** is stored in the **InstanceId** property of the object that represents a CIM session. ```yaml Type: System.Guid[] Parameter Sets: InstanceIdSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Gets one or more CIM sessions which contain the specified friendly names. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: NameSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.Management.Infrastructure.CimSession This cmdlet returns a CIM session object. ## NOTES PowerShell includes the following aliases for `Get-CimSession`: - Windows: - `gcms` This cmdlet is only available on Windows platforms. ## RELATED LINKS [Format-Table](../Microsoft.Powershell.Utility/Format-Table.md) [New-CimSession](New-CimSession.md) [Remove-CimSession](Remove-CimSession.md) [about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md)

#File: reference/7.6/CimCmdlets/Invoke-CimMethod.md

--- external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml Locale: en-US Module Name: CimCmdlets ms.date: 06/28/2023 online version: https://learn.microsoft.com/powershell/module/cimcmdlets/invoke-cimmethod?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Invoke-CimMethod --- # Invoke-CimMethod ## SYNOPSIS Invokes a method of a CIM class. ## SYNTAX ### ClassNameComputerSet (Default) ``` Invoke-CimMethod [-ClassName] <String> [-ComputerName <String[]>] [[-Arguments] <IDictionary>] [-MethodName] <String> [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ClassNameSessionSet ``` Invoke-CimMethod [-ClassName] <String> -CimSession <CimSession[]> [[-Arguments] <IDictionary>] [-MethodName] <String> [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ResourceUriComputerSet ``` Invoke-CimMethod -ResourceUri <Uri> [-ComputerName <String[]>] [[-Arguments] <IDictionary>] [-MethodName] <String> [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### CimInstanceSessionSet ``` Invoke-CimMethod [-ResourceUri <Uri>] [-InputObject] <CimInstance> -CimSession <CimSession[]> [[-Arguments] <IDictionary>] [-MethodName] <String> [-OperationTimeoutSec <UInt32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### CimInstanceComputerSet ``` Invoke-CimMethod [-ResourceUri <Uri>] [-InputObject] <CimInstance> [-ComputerName <String[]>] [[-Arguments] <IDictionary>] [-MethodName] <String> [-OperationTimeoutSec <UInt32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ResourceUriSessionSet ``` Invoke-CimMethod -ResourceUri <Uri> -CimSession <CimSession[]> [[-Arguments] <IDictionary>] [-MethodName] <String> [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### CimClassComputerSet ``` Invoke-CimMethod [-CimClass] <CimClass> [-ComputerName <String[]>] [[-Arguments] <IDictionary>] [-MethodName] <String> [-OperationTimeoutSec <UInt32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### CimClassSessionSet ``` Invoke-CimMethod [-CimClass] <CimClass> -CimSession <CimSession[]> [[-Arguments] <IDictionary>] [-MethodName] <String> [-OperationTimeoutSec <UInt32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### QueryComputerSet ``` Invoke-CimMethod -Query <String> [-QueryDialect <String>] [-ComputerName <String[]>] [[-Arguments] <IDictionary>] [-MethodName] <String> [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### QuerySessionSet ``` Invoke-CimMethod -Query <String> [-QueryDialect <String>] -CimSession <CimSession[]> [[-Arguments] <IDictionary>] [-MethodName] <String> [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Invoke-CimMethod` cmdlet invokes a method of a CIM class or CIM instance using the name-value pairs specified by the **Arguments** parameter. If the **InputObject** parameter is not specified, the cmdlet works in one of the following ways: - If neither the **ComputerName** parameter nor the **CimSession** parameter is specified, then this cmdlet works on local Windows Management Instrumentation (WMI) using a Component Object Model (COM) session. - If either the **ComputerName** parameter or the **CimSession** parameter is specified, then this cmdlet works against the CIM server specified by either the **ComputerName** parameter or the **CimSession** parameter. If the **InputObject** parameter is specified, the cmdlet works in one of the following ways: - If neither the **ComputerName** parameter nor the **CimSession** parameter is specified, then this cmdlet uses the CIM session or computer name from the input object. - If the either the **ComputerName** parameter or the **CimSession** parameter is specified, then this cmdlet uses the either the **CimSession** parameter value or **ComputerName** parameter value. This is not a common scenario. ## EXAMPLES ### Example 1: Invoke a method This example invokes the **Terminate** method of the **Win32_Process** class. ```powershell $method = @{ Query = 'select * from Win32_Process where name like "notepad%"' MethodName = "Terminate" } Invoke-CimMethod @method ``` ### Example 2: Invoke a method using CIM instance object This example retrieves the CIM instance object and stores it in a variable named `$x` using the `Get-CimInstance` cmdlet. The contents of the variable are then used as the **InputObject** for the `Invoke-CimMethod` cmdlet. The **GetOwner** method is invoked for the **CimInstance**. ```powershell $x = Get-CimInstance -Query 'Select * from Win32_Process where name like "notepad%"' Invoke-CimMethod -InputObject $x -MethodName GetOwner ``` ### Example 3: Invoke a static method using arguments This example invokes the **Create** method named using the **Arguments** parameter. ```powershell Invoke-CimMethod -ClassName Win32_Process -MethodName "Create" -Arguments @{ CommandLine = 'notepad.exe'; CurrentDirectory = "C:\windows\system32" } ``` ### Example 4: Client-side validation This example performs client-side validation for the **Foo** method by passing a **CimClass** object to `Invoke-CimMethod`. ```powershell $c = Get-CimClass -ClassName Win32_Process Invoke-CimMethod -CimClass $c -MethodName "Foo" -Arguments @{CommandLine='notepad.exe'} ``` ## PARAMETERS ### -Arguments Specifies the parameters to pass to the called method. Specify the values for this parameter as name-value pairs, stored in a hash table. The order of the values entered isn't important. ```yaml Type: System.Collections.IDictionary Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -CimClass Specifies a CIM class object that represents a CIM class definition on the server. Use this parameter when invoking a static method of a class. You can use the `Get-CimClass` cmdlet to retrieve a class definition from the server. Using this parameter results in better client side schema validations. ```yaml Type: Microsoft.Management.Infrastructure.CimClass Parameter Sets: CimClassComputerSet, CimClassSessionSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -CimSession Runs the command using the specified CIM session. Enter a variable that contains the CIM session, or a command that creates or gets the CIM session, such as the `New-CimSession` or `Get-CimSession` cmdlets. For more information, see [about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md). ```yaml Type: Microsoft.Management.Infrastructure.CimSession[] Parameter Sets: ClassNameSessionSet, CimInstanceSessionSet, CimClassSessionSet, QuerySessionSet, ResourceUriSessionSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -ClassName Specifies the name of the CIM class for which to perform the operation. This parameter is only used for static methods. You can use tab completion to browse the list of classes, because PowerShell gets a list of classes from the local WMI server to provide a list of class names. ```yaml Type: System.String Parameter Sets: ClassNameComputerSet, ClassNameSessionSet Aliases: Class Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ComputerName Specifies the name of the computer on which you want to run the CIM operation. You can specify a fully qualified domain name (FQDN), a NetBIOS name, or an IP address. When using this parameter, the cmdlet creates a temporary session to the specified computer using the WsMan protocol. Otherwise, the cmdlet performs the operation on the local computer using Component Object Model (COM). Connect using a CIM session for better performance when multiple operations are being performed on the same computer. ```yaml Type: System.String[] Parameter Sets: ClassNameComputerSet, ResourceUriComputerSet, CimClassComputerSet, CimInstanceComputerSet, QueryComputerSet Aliases: CN, ServerName Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InputObject Specifies a CIM instance object to use as input to invoke a method. This parameter can only be used to invoke instance methods. To invoke class static methods, use the **Class** parameter or the **CimClass** parameter. ```yaml Type: Microsoft.Management.Infrastructure.CimInstance Parameter Sets: CimInstanceComputerSet, CimInstanceSessionSet Aliases: CimInstance Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -MethodName Specifies the name of the CIM method to invoke. This parameter is mandatory and cannot be null or empty. To invoke static method of a CIM class use the **ClassName** or the **CimClass** parameter. ```yaml Type: System.String Parameter Sets: (All) Aliases: Name Required: True Position: 2 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Namespace Specifies the namespace for the CIM operation. The default namespace is **root/CIMV2**. You can use tab completion to browse the list of namespaces, because PowerShell gets a list of namespaces from the local WMI server to provide the list of namespaces. ```yaml Type: System.String Parameter Sets: ClassNameComputerSet, ClassNameSessionSet, ResourceUriComputerSet, ResourceUriSessionSet, QuerySessionSet, QueryComputerSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -OperationTimeoutSec Specifies the amount of time that the cmdlet waits for a response from the computer. By default, the value is 0, which means that the cmdlet uses the default timeout value for the server. If the **OperationTimeoutSec** parameter is set to a value less than the default connection retry timeout of 3 minutes, network failures that last more than the value of the **OperationTimeoutSec** parameter are not recoverable. ```yaml Type: System.UInt32 Parameter Sets: (All) Aliases: OT Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Query Specifies a query to run on the CIM server. A method is invoked on the instances received as a result of the query. You can specify the query dialect using the **QueryDialect** parameter. If the value specified contains double quotes (`"`), single quotes (`'`), or a backslash (`\`), you must escape those characters by prefixing them with the backslash (`\`) character. If the value specified uses the WQL LIKE operator, then you must escape the following characters by enclosing them in square brackets (`[]`): percent (`%`), underscore (`_`), or opening square bracket (`[`). ```yaml Type: System.String Parameter Sets: QuerySessionSet, QueryComputerSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -QueryDialect Specifies the query language used for the Query parameter. The acceptable values for this parameter are: **WQL** or **CQL**. The default value is **WQL**. ```yaml Type: System.String Parameter Sets: QuerySessionSet, QueryComputerSet Aliases: Required: False Position: Named Default value: WQL Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ResourceUri Specifies the resource uniform resource identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer. A URI consists of a prefix and a path to a resource. For example: `http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk` `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings` By default, if you do not specify this parameter, the DMTF standard resource URI `http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/` is used and the class name is appended to it. **ResourceUri** can only be used with CIM sessions created using the WSMan protocol, or when specifying the **ComputerName** parameter, which creates a CIM session using WSMan. When you specify this parameter without specifying the **ComputerName** parameter, or when you specify a CIM session created using DCOM protocol, you get an error. The DCOM protocol does not support the **ResourceUri** parameter. If both the **ResourceUri** parameter and the **Filter** parameter are specified, the **Filter** parameter is ignored. ```yaml Type: System.Uri Parameter Sets: CimInstanceComputerSet, CimInstanceSessionSet Aliases: Required: True (ResourceUriSessionSet, ResourceUriComputerSet), False (CimInstanceSessionSet, CimInstanceComputerSet) Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### Microsoft.Management.Infrastructure.CimClass You can pipe a CIM class to this cmdlet. ### Microsoft.Management.Infrastructure.CimInstance You can pipe a CIM instance to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSCustomObject This cmdlet returns an object. ## NOTES PowerShell includes the following aliases for `Invoke-CimMethod`: - Windows: - `icim` This cmdlet is only available on Windows platforms. ## RELATED LINKS [Get-CimClass](Get-CimClass.md) [Get-CimInstance](Get-CimInstance.md) [Get-CimSession](Get-CimSession.md) [New-CimSession](New-CimSession.md)

#File: reference/7.6/CimCmdlets/New-CimInstance.md

--- external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml Locale: en-US Module Name: CimCmdlets ms.date: 06/28/2023 online version: https://learn.microsoft.com/powershell/module/cimcmdlets/new-ciminstance?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-CimInstance --- # New-CimInstance ## SYNOPSIS Creates a CIM instance. ## SYNTAX ### ClassNameComputerSet (Default) ``` New-CimInstance [-ClassName] <String> [-Key <String[]>] [[-Property] <IDictionary>] [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-ComputerName <String[]>] [-ClientOnly] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ClassNameSessionSet ``` New-CimInstance [-ClassName] <String> [-Key <String[]>] [[-Property] <IDictionary>] [-Namespace <String>] [-OperationTimeoutSec <UInt32>] -CimSession <CimSession[]> [-ClientOnly] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ResourceUriSessionSet ``` New-CimInstance -ResourceUri <Uri> [-Key <String[]>] [[-Property] <IDictionary>] [-Namespace <String>] [-OperationTimeoutSec <UInt32>] -CimSession <CimSession[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ResourceUriComputerSet ``` New-CimInstance -ResourceUri <Uri> [-Key <String[]>] [[-Property] <IDictionary>] [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-ComputerName <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### CimClassSessionSet ``` New-CimInstance [-CimClass] <CimClass> [[-Property] <IDictionary>] [-OperationTimeoutSec <UInt32>] -CimSession <CimSession[]> [-ClientOnly] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### CimClassComputerSet ``` New-CimInstance [-CimClass] <CimClass> [[-Property] <IDictionary>] [-OperationTimeoutSec <UInt32>] [-ComputerName <String[]>] [-ClientOnly] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `New-CimInstance` cmdlet creates an instance of a CIM class based on the class definition on either the local computer or a remote computer. By default, the `New-CimInstance` cmdlet creates an instance on the local computer. ## EXAMPLES ### Example 1: Create an instance of a CIM class This example creates an instance of a CIM Class named **Win32_Environment** in the **root/CIMV2** namespace on the computer. ```powershell $prop = @{ Name = "testvar" VariableValue = "testvalue" UserName = "domain\user" } New-CimInstance -ClassName Win32_Environment -Property $prop ``` No client side validation is performed if the class does not exist, the properties are wrong, or if the server rejects the call. If the instance is created successfully, the cmdlet outputs the newly created instance. ### Example 2: Create an instance of a CIM class using a class schema This example retrieves a CIM class object and stores it in a variable named `$class`. The contents of the variable are then passed to the `New-CimInstance` cmdlet. ```powershell $class = Get-CimClass -ClassName Win32_Environment $prop = @{ Name = "testvar" VariableValue = "testvalue" UserName = "Contoso\User1" } New-CimInstance -CimClass $class -Property $prop ``` ### Example 3: Create a dynamic instance on the client This example creates a dynamic instance of a CIM class named **Win32_Process** on the client computer without getting the instance from the server. The new instance is stored in the variable `$a`. This dynamic instance can be used to perform operations if the instance with this key exists on the server. ```powershell $instance = @{ ClassName = 'Win32_Process' Property = @{ Handle = 0 } Key = 'Handle' ClientOnly = $true } $a = New-CimInstance @instance Get-CimInstance -CimInstance $a Invoke-CimMethod -CimInstance $a -MethodName GetOwner ``` ```Output ProcessId Name HandleCount WorkingSetSize VirtualSize --------- ---- ----------- -------------- ----------- 0 System Idle Process 0 8192 8192 Domain : ReturnValue : 2 User : PSComputerName : ``` The `Get-CimInstance` cmdlet then retrieves a particular single instance. The `Invoke-CimMethod` cmdlet calls the **GetOwner** method on the retrieved instance. ### Example 4: Create an instance for a CIM class of a specific namespace This example gets an instance of a CIM class named **MSFT_Something** in the namespace **root/somewhere** and stores it in a variable named `$class`. The variable is passed to the `New-CimInstance` cmdlet to create a new CIM instance and perform client side validations on the new instance. ```powershell $class = Get-CimClass -ClassName MSFT_Something -Namespace root/somewhere New-CimInstance -CimClass $class -Property @{"Prop1"=1;"Prop2"="value"} -ClientOnly ``` In this example, using the **CimClass** parameter instead of the **ClassName** parameter validates that **Prop1** and **Prop2** actually exist and that the keys are marked correctly. You cannot use the **ComputerName** or **CimSession** parameter with the **ClientOnly** parameter. ## PARAMETERS ### -CimClass Specifies a CIM class object that represents the type of the instance. Use the `Get-CimClass` cmdlet to retrieve the class declaration from a computer. Using this parameter results in better client side schema validations. ```yaml Type: Microsoft.Management.Infrastructure.CimClass Parameter Sets: CimClassSessionSet, CimClassComputerSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -CimSession Runs the command using the specified CIM session. Enter a variable that contains the CIM session, or a command that creates or gets the CIM session, such as the `New-CimSession` or `Get-CimSession` cmdlets. For more information, see [about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md). ```yaml Type: Microsoft.Management.Infrastructure.CimSession[] Parameter Sets: ClassNameSessionSet, ResourceUriSessionSet, CimClassSessionSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -ClassName Specifies the name of the CIM class of which the operation creates an instance. NOTE: You can use tab completion to browse the list of classes, because PowerShell gets a list of classes from the local WMI server to provide a list of class names. ```yaml Type: System.String Parameter Sets: ClassNameComputerSet, ClassNameSessionSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ClientOnly Indicates that the instance is only created in PowerShell without going to the CIM server. You can use this parameter to create an in-memory CIM instance for use in subsequent PowerShell operations. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ClassNameComputerSet, ClassNameSessionSet, CimClassSessionSet, CimClassComputerSet Aliases: Local Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies the name of the computer on which you want to run the CIM operation. You can specify a fully qualified domain name (FQDN), a NetBIOS name, or an IP address. If you specify this parameter, the cmdlet creates a temporary session to the specified computer using the WSMan protocol. If you do not specify this parameter, the cmdlet performs the operation on the local computer using Component Object Model (COM). If multiple operations are being performed on the same computer, connecting using a CIM session gives better performance. ```yaml Type: System.String[] Parameter Sets: ClassNameComputerSet, ResourceUriComputerSet, CimClassComputerSet Aliases: CN, ServerName Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Key Specifies the properties that are used as keys. **CimSession** and **ComputerName** cannot be used when **Key** is specified. ```yaml Type: System.String[] Parameter Sets: ClassNameComputerSet, ClassNameSessionSet, ResourceUriSessionSet, ResourceUriComputerSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Namespace Specifies the namespace of the class for the new instance. The default namespace is **root/CIMV2**. You can use tab completion to browse the list of namespaces, because PowerShell gets a list of namespaces from the local WMI server to provide the list of namespaces. ```yaml Type: System.String Parameter Sets: ClassNameComputerSet, ClassNameSessionSet, ResourceUriSessionSet, ResourceUriComputerSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -OperationTimeoutSec Specifies the amount of time that the cmdlet waits for a response from the CIM server. By default, the value of this parameter is 0, which means that the cmdlet uses the default timeout value for the server. If the **OperationTimeoutSec** parameter is set to a value less than the robust connection retry timeout of 3 minutes, network failures that last more than the value of the **OperationTimeoutSec** parameter are not recoverable, because the operation on the server times out before the client can reconnect. ```yaml Type: System.UInt32 Parameter Sets: (All) Aliases: OT Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Property Specifies the properties of the CIM instance using a hash table (name-value pairs). If you specify the **CimClass** parameter, then the `New-CimInstance` cmdlet performs a property validation on the client to make sure that the properties specified are consistent with the class declaration on the server. If the **CimClass** parameter is not specified, then the property validation is done on the server. ```yaml Type: System.Collections.IDictionary Parameter Sets: (All) Aliases: Arguments Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ResourceUri Specifies the resource uniform resource identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer. A URI consists of a prefix and a path to a resource. For example: `http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk` `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings` By default, if you do not specify this parameter, the DMTF standard resource URI `http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/` is used and the class name is appended to it. **ResourceUri** can only be used with CIM sessions created using the WSMan protocol, or when specifying the **ComputerName** parameter, which creates a CIM session using WSMan. If you specify this parameter without specifying the **ComputerName** parameter, or if you specify a CIM session created using DCOM protocol, you will get an error, because the DCOM protocol does not support the **ResourceUri** parameter. If both the **ResourceUri** parameter and the **Filter** parameter are specified, the **Filter** parameter is ignored. ```yaml Type: System.Uri Parameter Sets: ResourceUriSessionSet, ResourceUriComputerSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.Management.Infrastructure.CimInstance This cmdlet returns an object that contains the CIM instance information. ## NOTES PowerShell includes the following aliases for `New-CimInstance`: - Windows: - `ncim` This cmdlet is only available on Windows platforms. ## RELATED LINKS [Get-CimClass](Get-CimClass.md) [Get-CimInstance](Get-CimInstance.md) [Remove-CimInstance](Remove-CimInstance.md) [Set-CimInstance](Set-CimInstance.md)

#File: reference/7.6/CimCmdlets/New-CimSession.md

--- external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml Locale: en-US Module Name: CimCmdlets ms.date: 06/28/2023 online version: https://learn.microsoft.com/powershell/module/cimcmdlets/new-cimsession?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-CimSession --- # New-CimSession ## SYNOPSIS Creates a CIM session. ## SYNTAX ### CredentialParameterSet (Default) ``` New-CimSession [-Authentication <PasswordAuthenticationMechanism>] [[-Credential] <PSCredential>] [[-ComputerName] <String[]>] [-Name <String>] [-OperationTimeoutSec <UInt32>] [-SkipTestConnection] [-Port <UInt32>] [-SessionOption <CimSessionOptions>] [<CommonParameters>] ``` ### CertificateParameterSet ``` New-CimSession [-CertificateThumbprint <String>] [[-ComputerName] <String[]>] [-Name <String>] [-OperationTimeoutSec <UInt32>] [-SkipTestConnection] [-Port <UInt32>] [-SessionOption <CimSessionOptions>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `New-CimSession` cmdlet creates a CIM session. A CIM session is a client-side object representing a connection to a local computer or a remote computer. The CIM session contains information about the connection, such as **ComputerName**, the protocol used, or various identifiers. This cmdlet returns a CIM session object that can be used by all other CIM cmdlets. ## EXAMPLES ### Example 1: Create a CIM session with default options This example creates a local CIM session with default options. If **ComputerName** is not specified, `New-CimSession` creates a DCOM session to the local computer. ```powershell New-CimSession ``` ### Example 2: Create a CIM session to a specific computer This example creates a CIM session to the computer specified by **ComputerName**. By default, `New-CimSession` creates a WSMan session when **ComputerName** is specified. ```powershell New-CimSession -ComputerName Server01 ``` ### Example 3: Create a CIM session to multiple computers This example creates a CIM session to each of the computers specified by **ComputerName**, in the comma separated list. ```powershell New-CimSession -ComputerName Server01, Server02, Server03 ``` ### Example 4: Create a CIM session with a friendly name This example creates a remote CIM session to each of the computers specified by **ComputerName**, in the comma separated list, and assigns a friendly name to the new sessions, by specifying **Name**. ```powershell New-CimSession -ComputerName Server01, Server02 -Name FileServers Get-CimSession -Name File* ``` You can use the friendly name of a CIM session to refer to the session in other CIM cmdlets, for example, [Get-CimSession](Get-CimSession.md). ### Example 5: Create a CIM session to a computer using a PSCredential object This example creates a CIM session to the computer specified by **ComputerName**, using the **PSCredential** object specified by **Credential**, and the authentication type specified by **Authentication**. ```powershell New-CimSession -ComputerName Server01 -Credential $cred -Authentication Negotiate ``` You can create a **PSCredential** object using the [`Get-Credential`](../Microsoft.PowerShell.Security/Get-Credential.md) cmdlet. ### Example 6: Create a CIM session to a computer using a specific port This example creates a CIM session to the computer specified by **ComputerName** using the TCP port specified by **Port**. ```powershell New-CimSession -ComputerName Server01 -Port 1234 ``` ### Example 7: Create a CIM session using DCOM This example creates a CIM session using the Distributed COM (DCOM) protocol instead of WSMan. ```powershell $SessionOption = New-CimSessionOption -Protocol Dcom New-CimSession -ComputerName Server1 -SessionOption $SessionOption ``` ## PARAMETERS ### -Authentication Specifies the authentication type used for the user's credentials. The acceptable values for this parameter are: - Default - Digest - Negotiate - Basic - Kerberos - NtlmDomain - CredSsp You cannot use the **NtlmDomain** authentication type for connection to the local computer. **CredSSP** authentication is available only in Windows Vista, Windows Server 2008, and later versions of Windows. > [!CAUTION] > Credential Security Service Provider (CredSSP) authentication is designed for commands that > require authentication on more than one resource, such as accessing a remote network share. This > mechanism increases the security risk of the remote operation. If the remote computer is > compromised, the credentials that are passed to it can be used to control the network session. ```yaml Type: Microsoft.Management.Infrastructure.Options.PasswordAuthenticationMechanism Parameter Sets: CredentialParameterSet Aliases: Accepted values: Default, Digest, Negotiate, Basic, Kerberos, NtlmDomain, CredSsp Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X.509) of a user account that has permission to perform this action. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they do not work with domain accounts. To get a certificate thumbprint, use the [`Get-Item`](../Microsoft.Powershell.Management/Get-Item.md) or [`Get-ChildItem`](../Microsoft.Powershell.Management/Get-ChildItem.md) cmdlets in the PowerShell Certificate Provider. For more information, see [about_Certificate_Provider](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md). ```yaml Type: System.String Parameter Sets: CertificateParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ComputerName Specifies the name of the computer to which to create the CIM session. Specify either a single computer name, or multiple computer names separated by a comma. If **ComputerName** is not specified, a CIM session to the local computer is created. You can specify the value for computer name in one of the following formats: - One or more NetBIOS names - One or more IP addresses - One or more fully qualified domain names. If the computer is in a different domain than the user, you must specify the fully qualified domain name. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: CN, ServerName Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to perform this action. If **Credential** is not specified, the current user account is used. Specify the value for **Credential** using one of the following formats: - A user name: "User01" - A domain name and a user name: "Domain01\User01" - A user principal name: "User@Domain.com" - A PSCredential object, such as one returned by the [`Get-Credential`](../Microsoft.PowerShell.Security/Get-Credential.md) cmdlet. When you type a user name, you are prompted for a password. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: CredentialParameterSet Aliases: Required: False Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies a friendly name for the CIM session. You can use the name to refer to the CIM session when using other cmdlets, such as the [Get-CimSession](Get-CimSession.md) cmdlet. The name is not required to be unique to the computer or the current session. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -OperationTimeoutSec Duration for which the cmdlet waits for a response from the server. By default, the value of this parameter is 0, which means that the cmdlet uses the default timeout value for the server. If the **OperationTimeoutSec** parameter is set to a value less than the robust connection retry timeout of 3 minutes, network failures that last more than the value of the **OperationTimeoutSec** parameter are not recoverable, because the operation on the server times out before the client can reconnect. ```yaml Type: System.UInt32 Parameter Sets: (All) Aliases: OT Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Port Specifies the network port on the remote computer that is used for this connection. To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are 5985 (the WinRM port for HTTP) and 5986 (the WinRM port for HTTPS). Before using an alternate port, you must configure the WinRM listener on the remote computer to listen at that port. Use the following commands to configure the listener: `winrm delete winrm/config/listener?Address=*+Transport=HTTP` `winrm create winrm/config/listener?Address=*+Transport=HTTP @{Port="\<port-number>"}` Do not use the **Port** parameter unless you must. The port setting in the command applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on all computers. ```yaml Type: System.UInt32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -SessionOption Sets advanced options for the new CIM session. Enter the name of a **CimSessionOption** object created using the [`New-CimSessionOption`](New-CimSessionOption.md) cmdlet. ```yaml Type: Microsoft.Management.Infrastructure.Options.CimSessionOptions Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -SkipTestConnection By default, the `New-CimSession` cmdlet establishes a connection with a remote WS-Management endpoint for two reasons: to verify that the remote server is listening on the port number that is specified using the **Port** parameter, and to verify the specified account credentials. The verification is accomplished using a standard WS-Identity operation. You can add the **SkipTestConnection** switch parameter if the remote WS-Management endpoint cannot use WS-Identify, or to reduce some data transmission time. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.Management.Infrastructure.CimSession This cmdlet returns a CIM session object. ## NOTES PowerShell includes the following aliases for `New-CimSession`: - Windows: - `ncms` This cmdlet is only available on Windows platforms. ## RELATED LINKS [Get-ChildItem](../Microsoft.Powershell.Management/Get-ChildItem.md) [Get-Credential](../Microsoft.PowerShell.Security/Get-Credential.md) [Get-Item](../Microsoft.Powershell.Management/Get-Item.md) [Get-CimSession](Get-CimSession.md) [Remove-CimSession](Remove-CimSession.md) [New-CimSessionOption](New-CimSessionOption.md) [about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md)

#File: reference/7.6/CimCmdlets/New-CimSessionOption.md

--- external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml Locale: en-US Module Name: CimCmdlets ms.date: 06/28/2023 online version: https://learn.microsoft.com/powershell/module/cimcmdlets/new-cimsessionoption?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-CimSessionOption --- # New-CimSessionOption ## SYNOPSIS Specifies advanced options for the New-CimSession cmdlet. ## SYNTAX ### ProtocolTypeSet (Default) ``` New-CimSessionOption [-Protocol] <ProtocolType> [-UICulture <CultureInfo>] [-Culture <CultureInfo>] [<CommonParameters>] ``` ### WSManParameterSet ``` New-CimSessionOption [-NoEncryption] [-SkipCACheck] [-SkipCNCheck] [-SkipRevocationCheck] [-EncodePortInServicePrincipalName] [-Encoding <PacketEncoding>] [-HttpPrefix <Uri>] [-MaxEnvelopeSizeKB <UInt32>] [-ProxyAuthentication <PasswordAuthenticationMechanism>] [-ProxyCertificateThumbprint <String>] [-ProxyCredential <PSCredential>] [-ProxyType <ProxyType>] [-UseSsl] [-UICulture <CultureInfo>] [-Culture <CultureInfo>] [<CommonParameters>] ``` ### DcomParameterSet ``` New-CimSessionOption [-Impersonation <ImpersonationType>] [-PacketIntegrity] [-PacketPrivacy] [-UICulture <CultureInfo>] [-Culture <CultureInfo>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `New-CimSessionOption` cmdlet creates an instance of a CIM session options object. You use a CIM session options object as input to the `New-CimSession` cmdlet to specify the options for a CIM session. This cmdlet has two parameter sets, one for WsMan options and one for Distributed Component Object Model (DCOM) options. Depending on which parameters you use, the cmdlet returns either an instance of DCOM session options or returns WsMan session options. ## EXAMPLES ### Example 1: Create a CIM session options object for DCOM This example creates a CIM session options object for the DCOM protocol and stores it in a variable named `$so`. The contents of the variable are then passed to the `New-CimSession` cmdlet. `New-CimSession` then creates a new CIM session with the remote server named Server01, using the options defined in the variable. ```powershell $so = New-CimSessionOption -Protocol Dcom New-CimSession -ComputerName Server01 -SessionOption $so ``` ### Example 2: Create a CIM session options object for WsMan This example creates a CIM session options object for the WsMan protocol. The object contains configuration for the authentication mode of **Kerberos** specified by the **ProxyAuthentication** parameter, the credentials specified by the **ProxyCredential** parameter, and specifies that the command is to skip the CA check, skip the CN check, and use SSL. ```powershell $option = @{ ProxyAuthentication = 'Kerberos' ProxyCredential = $cred SkipCACheck = $true SkipCNCheck = $true UseSsl = $true } New-CimSessionOption @option ``` ### Example 3: Create a CIM session options object with the culture specified ```powershell New-CimSessionOption -Culture fr-FR -Protocol Wsman ``` This example specifies the culture that is used for the CIM session. By default, the culture of the client is used when performing operations. However, the default culture can be overridden using the **Culture** parameter. ## PARAMETERS ### -Culture Specifies the user interface culture to use for the CIM session. Specify the value for this parameter using one of the following formats: - A culture name in `<languagecode2>-<country/regioncode2>` format such as "en-US". - A variable that contains a **CultureInfo** object. - A command that gets a **CultureInfo** object, such as [Get-Culture](../Microsoft.PowerShell.Utility/Get-Culture.md) ```yaml Type: System.Globalization.CultureInfo Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -EncodePortInServicePrincipalName Indicates that the Kerberos connection is connecting to a service whose service principal name (SPN) includes the service port number. This type of connection is not common. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: WSManParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Encoding Specifies the encoding used for the WsMan protocol. The acceptable values for this parameter are: **Default**, **Utf8**, or **Utf16**. ```yaml Type: Microsoft.Management.Infrastructure.Options.PacketEncoding Parameter Sets: WSManParameterSet Aliases: Accepted values: Default, Utf8, Utf16 Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -HttpPrefix Specifies the part of the HTTP URL after the computer name and port number. Changing this is not common. By default, the value of this parameter is **/wsman**. ```yaml Type: System.Uri Parameter Sets: WSManParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Impersonation Creates a DCOM session to Windows Management Instrumentation (WMI) using impersonation. Valid values for this parameter are: - Default: DCOM can choose the impersonation level using its normal security negotiation algorithm. - None: The client is anonymous to the server. The server process can impersonate the client, but the impersonation token does not contain any information and cannot be used. - Identify: Allows objects to query the credentials of the caller. - Impersonate: Allows objects to use the credentials of the caller. - Delegate: Allows objects to permit other objects to use the credentials of the caller. If **Impersonation** is not specified, the `New-CimSession` cmdlet uses the value of **Impersonate**. ```yaml Type: Microsoft.Management.Infrastructure.Options.ImpersonationType Parameter Sets: DcomParameterSet Aliases: Accepted values: Default, None, Identify, Impersonate, Delegate Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaxEnvelopeSizeKB Specifies the size limit of WsMan XML messages for either direction. ```yaml Type: System.UInt32 Parameter Sets: WSManParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -NoEncryption Specifies that data encryption is turned off. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: WSManParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PacketIntegrity Specifies that the DCOM session created to WMI uses the Component Object Model (COM) _PacketIntegrity_ functionality. By default, all CIM sessions created using DCOM have the **PacketIntegrity** parameter set to **True**. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: DcomParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PacketPrivacy Creates a DCOM session to WMI using the COM _PacketPrivacy_. By default, all CIM sessions created using DCOM have the **PacketPrivacy** parameter set to **true**. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: DcomParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Protocol Specifies the protocol to use. The acceptable values for this parameter are: **Dcom**, **Default**, or **Wsman**. ```yaml Type: Microsoft.Management.Infrastructure.CimCmdlets.ProtocolType Parameter Sets: ProtocolTypeSet Aliases: Accepted values: Dcom, Default, Wsman Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ProxyAuthentication Specifies the authentication method to use for proxy resolution. The acceptable values for this parameter are: **Default**, **Digest**, **Negotiate**, **Basic**, **Kerberos**, **NtlmDomain**, or **CredSsp**. ```yaml Type: Microsoft.Management.Infrastructure.Options.PasswordAuthenticationMechanism Parameter Sets: WSManParameterSet Aliases: Accepted values: Default, Digest, Negotiate, Basic, Kerberos, NtlmDomain, CredSsp Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ProxyCertificateThumbprint Specifies the (x.509) digital public key certificate of a user account for proxy authentication. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. They can only be mapped to local user accounts and they do not work with domain accounts. To get a certificate thumbprint, use the `Get-Item` or `Get-ChildItem` cmdlets in the PowerShell Cert: drive. ```yaml Type: System.String Parameter Sets: WSManParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ProxyCredential Specifies the credentials to use for proxy authentication. Enter one of the following: - A variable that contains a PSCredential object. - A command that gets a PSCredential object, such as `Get-Credential` If this option is not set, then you cannot specify any credentials. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: WSManParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProxyType Specifies the host name resolution mechanism to use. The acceptable values for this parameter are: **None**, **WinHttp**, **Auto**, or **InternetExplorer**. The default value of this parameter is **InternetExplorer**. ```yaml Type: Microsoft.Management.Infrastructure.Options.ProxyType Parameter Sets: WSManParameterSet Aliases: Accepted values: None, WinHttp, Auto, InternetExplorer Required: False Position: Named Default value: InternetExplorer Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -SkipCACheck Indicates that when connecting over HTTPS, the client does not validate that the server certificate is signed by a trusted certification authority (CA). Use this parameter only when the remote computer is trusted using another mechanism, such as when the remote computer is part of a network that is physically secure and isolated, or when the remote computer is listed as a trusted host in a WinRM configuration. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: WSManParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -SkipCNCheck Indicates that the certificate common name (CN) of the server does not need to match the hostname of the server. Use this parameter for remote operations only with trusted computers that use the HTTPS protocol. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: WSManParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -SkipRevocationCheck Indicates that the revocation check for server certificates is skipped. Use this parameter only for trusted computers. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: WSManParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -UICulture Specifies the user interface culture to use for the CIM session. Specify the value for this parameter using one of the following formats: - A culture name in `<languagecode2>-<country/regioncode2>` format such as "en-US". - A variable that contains a CultureInfo object. - A command that gets a CultureInfo object, such as `Get-Culture`. ```yaml Type: System.Globalization.CultureInfo Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -UseSsl Indicates that SSL should be used to establish a connection to the remote computer. By default, SSL is not used. WsMan encrypts all content that is transmitted over the network, even when using HTTP. This parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port used for the connection and you specify this parameter, then the command fails. It is recommended that you use this parameter only when the **PacketPrivacy** parameter is not specified. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: WSManParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.Management.Infrastructure.Options.CimSessionOptions This cmdlet returns an object that contains CIM session options information. ## NOTES PowerShell includes the following aliases for `New-CimSessionOption`: - Windows: - `ncso` This cmdlet is only available on Windows platforms. ## RELATED LINKS [Get-ChildItem](../Microsoft.Powershell.Management/Get-ChildItem.md) [Get-Credential](../Microsoft.Powershell.Security/Get-Credential.md) [Get-Culture](../Microsoft.Powershell.Utility/Get-Culture.md) [Get-Item](../Microsoft.Powershell.Management/Get-Item.md) [New-CimSession](New-CimSession.md)

#File: reference/7.6/CimCmdlets/Register-CimIndicationEvent.md

--- external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml Locale: en-US Module Name: CimCmdlets ms.date: 06/28/2023 no-loc: [-Forward] online version: https://learn.microsoft.com/powershell/module/cimcmdlets/register-cimindicationevent?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Register-CimIndicationEvent --- # Register-CimIndicationEvent ## SYNOPSIS Subscribes to indications using a filter expression or a query expression. ## SYNTAX ### ClassNameComputerSet (Default) ``` Register-CimIndicationEvent [-Namespace <String>] [-ClassName] <String> [-OperationTimeoutSec <UInt32>] [-ComputerName <String>] [[-SourceIdentifier] <String>] [[-Action] <ScriptBlock>] [-MessageData <PSObject>] [-SupportEvent] [-Forward] [-MaxTriggerCount <Int32>] [<CommonParameters>] ``` ### ClassNameSessionSet ``` Register-CimIndicationEvent [-Namespace <String>] [-ClassName] <String> [-OperationTimeoutSec <UInt32>] -CimSession <CimSession> [[-SourceIdentifier] <String>] [[-Action] <ScriptBlock>] [-MessageData <PSObject>] [-SupportEvent] [-Forward] [-MaxTriggerCount <Int32>] [<CommonParameters>] ``` ### QueryExpressionSessionSet ``` Register-CimIndicationEvent [-Namespace <String>] [-Query] <String> [-QueryDialect <String>] [-OperationTimeoutSec <UInt32>] -CimSession <CimSession> [[-SourceIdentifier] <String>] [[-Action] <ScriptBlock>] [-MessageData <PSObject>] [-SupportEvent] [-Forward] [-MaxTriggerCount <Int32>] [<CommonParameters>] ``` ### QueryExpressionComputerSet ``` Register-CimIndicationEvent [-Namespace <String>] [-Query] <String> [-QueryDialect <String>] [-OperationTimeoutSec <UInt32>] [-ComputerName <String>] [[-SourceIdentifier] <String>] [[-Action] <ScriptBlock>] [-MessageData <PSObject>] [-SupportEvent] [-Forward] [-MaxTriggerCount <Int32>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Register-CimIndicationEvent` cmdlet subscribes to indications using an indication class name or a query expression. Use the **SourceIdentifier** parameter give a name to the subscription. This cmdlet returns an **EventSubscription** object. You can use this object to cancel the subscription. ## EXAMPLES ### Example 1: Register the events generated by a class This example subscribes to the events generated by the class named **Win32_ProcessStartTrace**. This class raises an event whenever a process starts. ```powershell $event = @{ ClassName = 'Win32_ProcessStartTrace' SourceIdentifier = 'ProcessStarted' } Register-CimIndicationEvent @event Get-Event -SourceIdentifier "ProcessStarted" ``` The `Get-Event` cmdlet gets the events with **ProcessStarted** subscription. For more information, see [Get-Event](../Microsoft.PowerShell.Utility/Get-Event.md). > [!NOTE] > For this example, you must run PowerShell as an Administrator. ### Example 2: Register the events using a query This example uses a query to subscribe to an event generated whenever there is a change in the instance of a class named **Win32_LocalTime**. ```powershell $query = "SELECT * FROM CIM_InstModification WHERE TargetInstance ISA 'Win32_LocalTime'" Register-CimIndicationEvent -Query $query -SourceIdentifier "Timer" ``` ### Example 3: Run a script when the event arrives This example shows how to use an action in response to an event. The variable `$action` holds the script block for **Action**, which uses the `$Event` variable to access the event received from CIM. ```powershell $action = { $name = $Event.SourceEventArgs.NewEvent.ProcessName $id = $Event.SourceEventArgs.NewEvent.ProcessId Write-Host -Object "New Process Started : Name = $name ID = $id" } $event = @{ ClassName = 'Win32_ProcessStartTrace' SourceIdentifier = 'ProcessStarted' Action = $action } Register-CimIndicationEvent @event ``` For more information, see [Win32_ProcessStartTrace](/previous-versions/windows/desktop/krnlprov/win32-processstarttrace). ### Example 4: Register the events on a remote computer This example subscribes to events on a remote computer named **Server01**. Events received from the CIM server are stored in the event queue in the current PowerShell session and then runs a local `Get-Event` to retrieve the events. ```powershell $event = @{ ClassName = 'Win32_ProcessStartTrace' SourceIdentifier = 'ProcessStarted' ComputerName = 'Server01' } Register-CimIndicationEvent @event Get-Event -SourceIdentifier "ProcessStarted" ``` ## PARAMETERS ### -Action Specifies the commands that handle the events. The commands specified by this parameter run when an event is raised, instead of sending the event to the event queue. Enclose the commands in braces (`{}`) to create a script block. The script block specified with **Action** can include the `$Event`, `$EventSubscriber`, `$Sender`, `$SourceEventArgs`, and `$SourceArgs` automatic variables, which provide information about the event to the **Action** script block. For more information, see [About Automatic Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md). ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CimSession Runs the command using the specified CIM session. Enter a variable that contains the CIM session, or a command that creates or gets the CIM session, such as the `New-CimSession` or `Get-CimSession` cmdlets. For more information, see [about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md). ```yaml Type: Microsoft.Management.Infrastructure.CimSession Parameter Sets: ClassNameSessionSet, QueryExpressionSessionSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ClassName Specifies the indication class to which you are subscribing. You can use tab completion to browse the list of classes, because PowerShell gets a list of classes from the local WMI server to provide a list of class names. ```yaml Type: System.String Parameter Sets: ClassNameComputerSet, ClassNameSessionSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies the name of the computer on which you want to run the CIM operation. You can specify a fully qualified domain name (FQDN), a NetBIOS name, or an IP address. If you specify this parameter, the cmdlet creates a temporary session to the specified computer using the WsMan protocol. If you do not specify this parameter, the cmdlet performs operation on the local system using Component Object Model (COM). If multiple operations are being performed on the same computer, connect using a CIM session for better performance. ```yaml Type: System.String Parameter Sets: ClassNameComputerSet, QueryExpressionComputerSet Aliases: CN, ServerName Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Forward Indicates that events for the subscription are forwarded to the session on the local computer. Use this parameter when you are registering for events on a remote computer or in a remote session. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaxTriggerCount Parameter to indicate that the subscriber should be auto-unregistered after being triggered for specified times. 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. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MessageData Specifies any additional data to associate with this event subscription. The value of this parameter appears in the **MessageData** property of all the events associated with this subscription. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Namespace Specifies the namespace for the CIM operation. The default namespace is **root/CIMV2**. You can use tab completion to browse the list of namespaces, because PowerShell gets a list of namespaces from the local WMI server to provide the list of namespaces. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OperationTimeoutSec Specifies the amount of time that the cmdlet waits for a response from the computer. By default, the value of this parameter is 0, which means that the cmdlet uses the default timeout value for the server. If the **OperationTimeoutSec** parameter is set to a value less than the robust connection retry timeout of 3 minutes, network failures that last more than the value of the **OperationTimeoutSec** parameter are not recoverable, because the operation on the server times out before the client can reconnect. ```yaml Type: System.UInt32 Parameter Sets: (All) Aliases: OT Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Query Specifies a query to run on the CIM server. If the value specified contains double quotes `"`, single quotes `'`, or a backslash `\`, you must escape those characters by prefixing them with the backslash character. If the value specified uses the WQL LIKE operator, then you must escape the following characters by enclosing them in square brackets `[]`: percent `%`, underscore `_`, or opening square bracket `[`. ```yaml Type: System.String Parameter Sets: QueryExpressionSessionSet, QueryExpressionComputerSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -QueryDialect Specifies the query language used for the **Query** parameter. The acceptable values for this parameter are: **WQL** or **CQL**. The default value is **WQL**. ```yaml Type: System.String Parameter Sets: QueryExpressionSessionSet, QueryExpressionComputerSet Aliases: Required: False Position: Named Default value: WQL Accept pipeline input: False Accept wildcard characters: False ``` ### -SourceIdentifier Specifies a name for the subscription. The name that you specify must be unique in the current session. The default value is a GUID that PowerShell assigns. This value appears in the value of the **SourceIdentifier** property of the subscriber object and of all event objects associated with this subscription. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SupportEvent Indicates that the event subscription is hidden. Use this parameter when the current subscription is part of a more complex event registration mechanism and it should not be discovered independently. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Object This cmdlet returns an **EventSubscription** object. ## NOTES PowerShell includes the following aliases for `Register-CimIndicationEvent`: - Windows: - `rcie` This cmdlet is only available on Windows platforms. ## RELATED LINKS [Get-Event](../Microsoft.Powershell.Utility/Get-Event.md) [Remove-Event](../Microsoft.Powershell.Utility/Remove-Event.md) [Unregister-Event](../Microsoft.Powershell.Utility/Unregister-Event.md) [Write-Host](../Microsoft.Powershell.Utility/Write-Host.md) [Get-CimSession](Get-CimSession.md) [New-CimSession](New-CimSession.md)

#File: reference/7.6/CimCmdlets/Remove-CimInstance.md

--- external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml Locale: en-US Module Name: CimCmdlets ms.date: 06/28/2023 online version: https://learn.microsoft.com/powershell/module/cimcmdlets/remove-ciminstance?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-CimInstance --- # Remove-CimInstance ## SYNOPSIS Removes a CIM instance from a computer. ## SYNTAX ### CimInstanceComputerSet (Default) ``` Remove-CimInstance [-ResourceUri <Uri>] [-ComputerName <String[]>] [-OperationTimeoutSec <UInt32>] [-InputObject] <CimInstance> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### CimInstanceSessionSet ``` Remove-CimInstance -CimSession <CimSession[]> [-ResourceUri <Uri>] [-OperationTimeoutSec <UInt32>] [-InputObject] <CimInstance> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### QuerySessionSet ``` Remove-CimInstance -CimSession <CimSession[]> [[-Namespace] <String>] [-OperationTimeoutSec <UInt32>] [-Query] <String> [-QueryDialect <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### QueryComputerSet ``` Remove-CimInstance [-ComputerName <String[]>] [[-Namespace] <String>] [-OperationTimeoutSec <UInt32>] [-Query] <String> [-QueryDialect <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** This cmdlet removes a CIM instance from a CIM server. You can specify the CIM instance to remove by using either a CIM instance object retrieved by the `Get-CimInstance` cmdlet, or by specifying a query. If the **InputObject** parameter is not specified, the cmdlet works in one of the following ways: - If neither the **ComputerName** parameter nor the **CimSession** parameter is specified, then this cmdlet works on local Windows Management Instrumentation (WMI) using a Component Object Model (COM) session. - If either the **ComputerName** parameter or the **CimSession** parameter is specified, then this cmdlet works against the CIM server specified by either the **ComputerName** parameter or the **CimSession** parameter. ## EXAMPLES ### Example 1: Remove the CIM instance This example use the **Query** parameter to remove CIM instances from the class named **Win32_Environment** that start with the character string **testvar** . ```powershell Remove-CimInstance -Query 'Select * from Win32_Environment where name LIKE "testvar%"' ``` ### Example 2: Remove the CIM instance using CIM instance object This example retrieves the CIM instance objects filtered by the **Query** parameter and stores them in variable named `$var` using the `Get-CimInstance` cmdlet. The contents of the variable are then passed to the `Remove-CimInstance` cmdlet, which removes the CIM instances. ```powershell notepad.exe $var = Get-CimInstance -Query 'Select * from Win32_Process where name LIKE "notepad%"' Remove-CimInstance -InputObject $var ``` ## PARAMETERS ### -CimSession Runs the command using the specified CIM session. Enter a variable that contains the CIM session, or a command that creates or gets the CIM session, such as the `New-CimSession` or `Get-CimSession` cmdlets. For more information, see [about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md). ```yaml Type: Microsoft.Management.Infrastructure.CimSession[] Parameter Sets: CimInstanceSessionSet, QuerySessionSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -ComputerName Specifies the name of the computer on which you want to run the CIM operation. You can specify a fully qualified domain name (FQDN) or a NetBIOS name. If you specify this parameter, the cmdlet creates a temporary session to the specified computer using the WsMan protocol. If you do not specify this parameter, the cmdlet performs the operation on the local computer using Component Object Model (COM). If multiple operations are being performed on the same computer, connecting using a CIM session gives better performance. ```yaml Type: System.String[] Parameter Sets: CimInstanceComputerSet, QueryComputerSet Aliases: CN, ServerName Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies a CIM instance object to be removed from the CIM server. The object passed to the cmdlet is not changed, only the instance in the CIM server is removed. The **InputObject** parameter doesn't enumerate over collections. If a collection is passed, an error is thrown. When working with collections, pipe the input to enumerate the values. ```yaml Type: Microsoft.Management.Infrastructure.CimInstance Parameter Sets: CimInstanceComputerSet, CimInstanceSessionSet Aliases: CimInstance Required: True Position: 1 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Namespace Specifies the namespace for the CIM operation. The default namespace is **root/CIMV2**. You can use tab completion to browse the list of namespaces, because PowerShell gets a list of namespaces from the local WMI server to provide the list of namespaces. ```yaml Type: System.String Parameter Sets: QuerySessionSet, QueryComputerSet Aliases: Required: False Position: 2 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -OperationTimeoutSec Specifies the amount of time that the cmdlet waits for a response from the computer. By default, the value of this parameter is `0`, which means that the cmdlet uses the default timeout value for the server. If the **OperationTimeoutSec** parameter is set to a value less than the robust connection retry timeout of 3 minutes, network failures that last more than the value of the **OperationTimeoutSec** parameter are not recoverable, because the operation on the server times out before the client can reconnect. ```yaml Type: System.UInt32 Parameter Sets: (All) Aliases: OT Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Query Specifies a query to run on the CIM server. You can specify the query dialect using the **QueryDialect** parameter. If the value specified contains double quotes (`"`), single quotes (`'`), or a backslash (`\`), you must escape those characters by prefixing them with the backslash (`\`) character. If the value specified uses the WQL `LIKE` operator, then you must escape the following characters by enclosing them in square brackets (`[]`): percent (`%`), underscore (`_`), or opening square bracket (`[`). ```yaml Type: System.String Parameter Sets: QuerySessionSet, QueryComputerSet Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -QueryDialect Specifies the query language used for the Query parameter. The acceptable values for this parameter are: `WQL` or `CQL`. The default value is `WQL`. ```yaml Type: System.String Parameter Sets: QuerySessionSet, QueryComputerSet Aliases: Required: False Position: Named Default value: WQL Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ResourceUri Specifies the resource uniform resource identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer. A URI consists of a prefix and a path to a resource. For example: - `http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk` - `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings` By default, if you do not specify this parameter, the DMTF standard resource URI `http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/` is used and the class name is appended to it. **ResourceUri** can only be used with CIM sessions created using the WSMan protocol, or when specifying the **ComputerName** parameter, which creates a CIM session using WSMan. If you specify this parameter without specifying the **ComputerName** parameter, or if you specify a CIM session created using DCOM protocol, you get an error, because the DCOM protocol does not support the **ResourceUri** parameter. If both the **ResourceUri** parameter and the **Filter** parameter are specified, the **Filter** parameter is ignored. ```yaml Type: System.Uri Parameter Sets: CimInstanceComputerSet, CimInstanceSessionSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Remove-CimInstance`: - Windows: - `rcim` This cmdlet is only available on Windows platforms. ## RELATED LINKS [New-CimInstance](New-CimInstance.md) [Get-CimInstance](Get-CimInstance.md) [Set-CimInstance](Set-CimInstance.md)

#File: reference/7.6/CimCmdlets/Remove-CimSession.md

--- external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml Locale: en-US Module Name: CimCmdlets ms.date: 06/28/2023 online version: https://learn.microsoft.com/powershell/module/cimcmdlets/remove-cimsession?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-CimSession --- # Remove-CimSession ## SYNOPSIS Removes one or more CIM sessions. ## SYNTAX ### CimSessionSet (Default) ``` Remove-CimSession [-CimSession] <CimSession[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ComputerNameSet ``` Remove-CimSession [-ComputerName] <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### SessionIdSet ``` Remove-CimSession [-Id] <UInt32[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### InstanceIdSet ``` Remove-CimSession -InstanceId <Guid[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### NameSet ``` Remove-CimSession -Name <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Remove-CimSession` cmdlet removes one or more CIM session objects from the local PowerShell session. ## EXAMPLES ### Example 1: Remove all the CIM sessions This example retrieves all the available CIM sessions on the local computer using the [Get-CimSession](Get-CimSession.md) cmdlet, and then removes them using the `Remove-CimSession`. ```powershell Get-CimSession | Remove-CimSession ``` ### Example 2: Remove a specific CIM session This example removes the CIM session that has an **Id** value of 5. ```powershell Remove-CimSession -Id 5 ``` ### Example 3: Show the list of CIM sessions to remove by using the WhatIf parameter This example uses the common parameter **WhatIf** to specify that the removal should not be done, but only output what would happen if it were done. ```powershell Remove-CimSession -Name a* -WhatIf ``` ## PARAMETERS ### -CimSession Specifies the session objects of the CIM sessions to close. Enter a variable that contains the CIM session, or a command that creates or gets the CIM session, such as the [`New-CimSession`](New-CimSession.md) or [`Get-CimSession`](Get-CimSession.md) cmdlets. For more information, see [about_CimSessions](../Microsoft.PowerShell.Core/About/about_CimSession.md). ```yaml Type: Microsoft.Management.Infrastructure.CimSession[] Parameter Sets: CimSessionSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -ComputerName Specifies an array of names of computers. Removes the sessions that connect to the specified computers. You can specify a fully qualified domain name (FQDN) or a NetBIOS name. ```yaml Type: System.String[] Parameter Sets: ComputerNameSet Aliases: CN, ServerName Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Id Specifies the ID of the CIM session to remove. Specify one or more IDs separated by commas, or use the range operator (`..`) to specify a range of IDs. An **Id** is an integer that uniquely identifies the CIM session in the current PowerShell session. For more information about the range operator, see [about_Operators](../Microsoft.PowerShell.Core/About/about_Operators.md). ```yaml Type: System.UInt32[] Parameter Sets: SessionIdSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InstanceId Specifies the instance ID of the CIM session to remove. **InstanceId** is a Globally Unique Identifier (GUID) that uniquely identifies a CIM session. The **InstanceId** is unique, even when you have multiple sessions running in PowerShell. The **InstanceId** is stored in the **InstanceId** property of the object that represents a CIM session. ```yaml Type: System.Guid[] Parameter Sets: InstanceIdSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies the friendly name of the CIM session to remove. You can use wildcard characters with this parameter. ```yaml Type: System.String[] Parameter Sets: NameSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Object This cmdlet returns an object that contains CIM session information. ## NOTES PowerShell includes the following aliases for `Remove-CimSession`: - Windows: - `rcms` This cmdlet is only available on Windows platforms. ## RELATED LINKS [Get-CimSession](Get-CimSession.md) [New-CimSession](New-CimSession.md) [about_CimSession](../Microsoft.PowerShell.Core/About/about_CimSession.md)

#File: reference/7.6/CimCmdlets/Set-CimInstance.md

--- external help file: Microsoft.Management.Infrastructure.CimCmdlets.dll-Help.xml Locale: en-US Module Name: CimCmdlets ms.date: 06/28/2023 online version: https://learn.microsoft.com/powershell/module/cimcmdlets/set-ciminstance?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-CimInstance --- # Set-CimInstance ## SYNOPSIS Modifies a CIM instance on a CIM server by calling the ModifyInstance method of the CIM class. ## SYNTAX ### CimInstanceComputerSet (Default) ``` Set-CimInstance [-ComputerName <String[]>] [-ResourceUri <Uri>] [-OperationTimeoutSec <UInt32>] [-InputObject] <CimInstance> [-Property <IDictionary>] [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### CimInstanceSessionSet ``` Set-CimInstance -CimSession <CimSession[]> [-ResourceUri <Uri>] [-OperationTimeoutSec <UInt32>] [-InputObject] <CimInstance> [-Property <IDictionary>] [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### QuerySessionSet ``` Set-CimInstance -CimSession <CimSession[]> [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-Query] <String> [-QueryDialect <String>] -Property <IDictionary> [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### QueryComputerSet ``` Set-CimInstance [-ComputerName <String[]>] [-Namespace <String>] [-OperationTimeoutSec <UInt32>] [-Query] <String> [-QueryDialect <String>] -Property <IDictionary> [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** This cmdlet modifies a CIM instance on a CIM server. If the **InputObject** parameter is not specified, the cmdlet works in one of the following ways: - If neither the **ComputerName** parameter nor the **CimSession** parameter is specified, then this cmdlet works on local Windows Management Instrumentation (WMI) using a Component Object Model (COM) session. - If either the **ComputerName** parameter or the **CimSession** parameter is specified, then this cmdlet works against the CIM server specified by either the **ComputerName** parameter or the **CimSession** parameter. If the **InputObject** parameter is specified, the cmdlet works in one of the following ways: - If neither the **ComputerName** parameter nor the **CimSession** parameter is specified, then this cmdlet uses the CIM session or computer name from the input object. - If the either the **ComputerName** parameter or the **CimSession** parameter is specified, then this cmdlet uses the either the **CimSession** parameter value or **ComputerName** parameter value. This is not very common. ## EXAMPLES ### Example 1: Set the CIM instance This example sets the value of the **VariableValue** property to **abcd** using the **Query** parameter. You can modify instances matching a Windows Management Instrumentation Query Language (WQL) query. ```powershell $instance = @ { Query = 'Select * from Win32_Environment where name LIKE "testvar%"' Property = @{VariableValue="abcd"} } Set-CimInstance @instance ``` ### Example 2: Set the CIM instance property using pipeline This example retrieves the CIM instance object filtered by the **Query** parameter using the `Get-CimInstance` cmdlet. The `Set-CimInstance` cmdlet modifies the value of **VariableValue** property to **abcd**. ```powershell Get-CimInstance -Query 'Select * from Win32_Environment where name LIKE "testvar%"' | Set-CimInstance -Property @{VariableValue="abcd"} ``` ### Example 3: Set the CIM instance property using input object ```powershell $x = Get-CimInstance -Query 'Select * from Win32_Environment where Name="testvar"' Set-CimInstance -InputObject $x -Property @{VariableValue="somevalue"} -PassThru ``` This example retrieves the CIM instance objects filtered by the Query parameter in to a variable `$x` using `Get-CimInstance`, and then passes the contents of the variable to the `Set-CimInstance` cmdlet. `Set-CimInstance` then modifies the **VariableValue** property to **somevalue**. Because the **PassThru** parameter is used, This example returns a modified CIM instance object. ### Example 4: Set the CIM instance property This example retrieves the CIM instance object that is specified in the **Query** parameter into a variable `$x` using the `Get-CimInstance` cmdlet, and changes the **VariableValue** property value of the object to change. The CIM instance object is then saved using the `Set-CimInstance` cmdlet. Because the **PassThru** parameter is used, This example returns a modified CIM instance object. ```powershell $x = Get-CimInstance -Query 'Select * from Win32_Environment where name="testvar"' $x.VariableValue = "Change" Set-CimInstance -CimInstance $x -PassThru ``` ### Example 5: Show the list of CIM instances to modify using WhatIf This example uses the common parameter **WhatIf** to specify that the modification should not be done, but only output what would happen if it were done. ```powershell $instance = @{ Query = 'Select * from Win32_Environment where name LIKE "testvar%"' Property = @{VariableValue="abcd"} WhatIf = $true } Set-CimInstance @instance ``` ### Example 6: Set the CIM instance after confirmation from the user This example uses the common parameter **Confirm** to specify that the modification should be done only after confirmation from the user. ```powershell $instance = @{ Query = 'Select * from Win32_Environment where name LIKE "testvar%"' Property = @{VariableValue="abcd"} Confirm = $true } Set-CimInstance @instance ``` ### Example 7: Set the created CIM instance This example creates a CIM instance with the specified properties using the `New-CimInstance` cmdlet, and retrieves its contents in to a variable `$x`. The variable is then passed to the `Set-CimInstance` cmdlet, which modifies the value of **VariableValue** property to **somevalue**. Because the **PassThru** parameter is used, This example returns a modified CIM instance object. ```powershell $instance = @{ ClassName = 'Win32_Environment' Property = @{ Name="testvar" UserName="domain\user" } Key = 'Name', 'UserName' ClientOnly = $true } $x = New-CimInstance @instance Set-CimInstance -CimInstance $x -Property @{VariableValue="somevalue"} -PassThru ``` ## PARAMETERS ### -CimSession Runs the cmdlets on a remote computer. Enter a computer name or a session object, such as the output of a `New-CimSession` or `Get-CimSession` cmdlet. ```yaml Type: Microsoft.Management.Infrastructure.CimSession[] Parameter Sets: CimInstanceSessionSet, QuerySessionSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -ComputerName Specifies the name of the computer on which you want to run the CIM operation. You can specify a fully qualified domain name (FQDN) or a NetBIOS name. If you do not specify this parameter, the cmdlet performs the operation on the local computer using Component Object Model (COM). If you specify this parameter, the cmdlet creates a temporary session to the specified computer using the WsMan protocol. If multiple operations are being performed on the same computer, connecting using a CIM session gives better performance. ```yaml Type: System.String[] Parameter Sets: CimInstanceComputerSet, QueryComputerSet Aliases: CN, ServerName Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies a CIM instance object to use as input. The **InputObject** parameter doesn't enumerate over collections. If a collection is passed, an error is thrown. When working with collections, pipe the input to enumerate the values. ```yaml Type: Microsoft.Management.Infrastructure.CimInstance Parameter Sets: CimInstanceComputerSet, CimInstanceSessionSet Aliases: CimInstance Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Namespace Specifies the namespace for the CIM operation. The default namespace is **root/CIMV2**. You can use tab completion to browse the list of namespaces, because PowerShell gets a list of namespaces from the local WMI server to provide the list of namespaces. ```yaml Type: System.String Parameter Sets: QuerySessionSet, QueryComputerSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -OperationTimeoutSec Specifies the amount of time that the cmdlet waits for a response from the computer. By default, the value of this parameter is 0, which means that the cmdlet uses the default timeout value for the server. If the **OperationTimeoutSec** parameter is set to a value less than the robust connection retry timeout of 3 minutes, network failures that last more than the value of the **OperationTimeoutSec** parameter are not recoverable, because the operation on the server times out before the client can reconnect. ```yaml Type: System.UInt32 Parameter Sets: (All) Aliases: OT Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Property Specifies the properties of the CIM instance as a hash table (using name-value pairs). Only the properties specified using this parameter are changed. Other properties of the CIM instance are not changed. ```yaml Type: System.Collections.IDictionary Parameter Sets: CimInstanceComputerSet, CimInstanceSessionSet, QuerySessionSet, QueryComputerSet Aliases: Arguments Required: True (QuerySessionSet, QueryComputerSet), False (CimInstanceComputerSet, CimInstanceSessionSet) Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Query Specifies a query to run on the CIM server to retrieve CIM instances on which to run the cmdlet. You can specify the query dialect using the QueryDialect parameter. If the value specified contains double quotes (`"`), single quotes (`'`), or a backslash (`\`), you must escape those characters by prefixing them with the backslash (`\`) character. If the value specified uses the WQL **LIKE** operator, then you must escape the following characters by enclosing them in square brackets (`[]`): percent (`%`), underscore (`_`), or opening square bracket (`[`). ```yaml Type: System.String Parameter Sets: QuerySessionSet, QueryComputerSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -QueryDialect Specifies the query language used for the Query parameter. The acceptable values for this parameter are: **WQL** or **CQL**. The default value is **WQL**. ```yaml Type: System.String Parameter Sets: QuerySessionSet, QueryComputerSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ResourceUri Specifies the resource uniform resource identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer. A URI consists of a prefix and a path to a resource. For example: - `http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk` - `http://intel.com/wbem/wscim/1/amt-schema/1/AMT_GeneralSettings` By default, if you do not specify this parameter, the DMTF standard resource URI `http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/` is used and the class name is appended to it. **ResourceUri** can only be used with CIM sessions created using the WSMan protocol, or when specifying the **ComputerName** parameter, which creates a CIM session using WSMan. If you specify this parameter without specifying the **ComputerName** parameter, or if you specify a CIM session created using DCOM protocol, you will get an error, because the DCOM protocol does not support the **ResourceUri** parameter. If both the **ResourceUri** parameter and the **Filter** parameter are specified, the **Filter** parameter is ignored. ```yaml Type: System.Uri Parameter Sets: CimInstanceComputerSet, CimInstanceSessionSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### Microsoft.Management.Infrastructure.CimInstance ## OUTPUTS ### None By default, this cmdlet returns no output. ### Microsoft.Management.Infrastructure.CimInstance When you use the **PassThru** parameter, this cmdlet returns the modified CIM instance object. ## NOTES PowerShell includes the following aliases for `Set-CimInstance`: - Windows: - `scim` This cmdlet is only available on Windows platforms. ## RELATED LINKS [Get-CimInstance](Get-CimInstance.md) [New-CimInstance](New-CimInstance.md) [Remove-CimInstance](Remove-CimInstance.md)

#File: reference/7.6/Microsoft.PowerShell.Archive/Compress-Archive.md

--- external help file: Microsoft.PowerShell.Archive-help.xml Locale: en-US Module Name: Microsoft.PowerShell.Archive ms.date: 03/03/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.archive/compress-archive?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Compress-Archive --- # Compress-Archive ## SYNOPSIS Creates a compressed archive, or zipped file, from specified files and directories. ## SYNTAX ### Path (Default) ``` Compress-Archive [-Path] <String[]> [-DestinationPath] <String> [-CompressionLevel <String>] [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### PathWithUpdate ``` Compress-Archive [-Path] <String[]> [-DestinationPath] <String> [-CompressionLevel <String>] -Update [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### PathWithForce ``` Compress-Archive [-Path] <String[]> [-DestinationPath] <String> [-CompressionLevel <String>] -Force [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPathWithUpdate ``` Compress-Archive -LiteralPath <String[]> [-DestinationPath] <String> [-CompressionLevel <String>] -Update [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPathWithForce ``` Compress-Archive -LiteralPath <String[]> [-DestinationPath] <String> [-CompressionLevel <String>] -Force [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath ``` Compress-Archive -LiteralPath <String[]> [-DestinationPath] <String> [-CompressionLevel <String>] [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Compress-Archive` cmdlet creates a compressed, or zipped, archive file from one or more specified files or directories. An archive packages multiple files, with optional compression, into a single zipped file for easier distribution and storage. An archive file can be compressed using the compression algorithm specified by the **CompressionLevel** parameter. The `Compress-Archive` cmdlet uses the **System.IO.Compression.ZipArchive** API to compress files. The API limits the maximum file size to 2GB. For more information, see [System.IO.Compression.ZipArchive](xref:System.IO.Compression.ZipArchive). > [!NOTE] > The `Compress-Archive` cmdlet ignores hidden files and folders when creating or updating the > archive file. On non-Windows machines, this includes files and folders with name that begins with > the period (`.`) character. > > To ensure hidden files and folders are compressed into the archive, use the .NET API instead. Some examples use splatting to reduce the line length of the code samples. For more information, see [about_Splatting](../Microsoft.PowerShell.Core/About/about_Splatting.md). ## EXAMPLES ### Example 1: Compress files to create an archive file This example compresses files from different directories and creates an archive file. A wildcard is used to get all files with a particular file extension. There's no directory structure in the archive file because the **Path** only specifies file names. ```powershell $compress = @{ Path = "C:\Reference\Draftdoc.docx", "C:\Reference\Images\*.vsd" CompressionLevel = "Fastest" DestinationPath = "C:\Archives\Draft.zip" } Compress-Archive @compress ``` The **Path** parameter accepts specific file names and file names with wildcards, `*.vsd`. The **Path** uses a comma-separated list to get files from different directories. The compression level is **Fastest** to reduce processing time. The **DestinationPath** parameter specifies the location for the `Draft.zip` file. The `Draft.zip` file contains `Draftdoc.docx` and all the files with a `.vsd` extension. ### Example 2: Compress files using a LiteralPath This example compresses specific named files and creates a new archive file. There's no directory structure in the archive file because the **Path** only specifies file names. ```powershell $compress = @{ LiteralPath= "C:\Reference\Draft Doc.docx", "C:\Reference\Images\diagram2.vsd" CompressionLevel = "Fastest" DestinationPath = "C:\Archives\Draft.zip" } Compress-Archive @compress ``` Absolute path and file names are used because the **LiteralPath** parameter doesn't accept wildcards. The **Path** uses a comma-separated list to get files from different directories. The compression level is **Fastest** to reduce processing time. The **DestinationPath** parameter specifies the location for the `Draft.zip` file. The `Draft.zip` file only contains `Draftdoc.docx` and `diagram2.vsd`. ### Example 3: Compress a directory that includes the root directory This example compresses a directory and creates an archive file that **includes** the root directory, and all its files and subdirectories. The archive file has a directory structure because the **Path** specifies a root directory. ```powershell Compress-Archive -Path C:\Reference -DestinationPath C:\Archives\Draft.zip ``` `Compress-Archive` uses the **Path** parameter to specify the root directory, `C:\Reference`. The **DestinationPath** parameter specifies the location for the archive file. The `Draft.zip` archive includes the `Reference` root directory, and all its files and subdirectories. ### Example 4: Compress a directory that excludes the root directory This example compresses a directory and creates an archive file that **excludes** the root directory because the **Path** uses an asterisk (`*`) wildcard. The archive contains a directory structure that contains the root directory's files and subdirectories. ```powershell Compress-Archive -Path C:\Reference\* -DestinationPath C:\Archives\Draft.zip ``` `Compress-Archive` uses the **Path** parameter to specify the root directory, `C:\Reference` with an asterisk (`*`) wildcard. The **DestinationPath** parameter specifies the location for the archive file. The `Draft.zip` archive contains the root directory's files and subdirectories. The `Reference` root directory is excluded from the archive. ### Example 5: Compress only the files in a root directory This example compresses only the files in a root directory and creates an archive file. There's no directory structure in the archive because only files are compressed. ```powershell Compress-Archive -Path C:\Reference\*.* -DestinationPath C:\Archives\Draft.zip ``` `Compress-Archive` uses the **Path** parameter to specify the root directory, `C:\Reference` with a **star-dot-star** (`*.*`) wildcard. The **DestinationPath** parameter specifies the location for the archive file. The `Draft.zip` archive only contains the `Reference` root directory's files and the root directory is excluded. ### Example 6: Use the pipeline to archive files This example sends files down the pipeline to create an archive. There's no directory structure in the archive file because the **Path** only specifies file names. ```powershell Get-ChildItem -Path C:\Reference\Afile.txt, C:\Reference\Images\Bfile.txt | Compress-Archive -DestinationPath C:\Archives\PipelineFiles.zip ``` `Get-ChildItem` uses the **Path** parameter to specify two files from different directories. Each file is represented by a **FileInfo** object and is sent down the pipeline to `Compress-Archive`. The two specified files are archived in `PipelineFiles.zip`. ### Example 7: Use the pipeline to archive a directory This example sends a directory down the pipeline to create an archive. Files are sent as **FileInfo** objects and directories as **DirectoryInfo** objects. The archive's directory structure doesn't include the root directory, but its files and subdirectories are included in the archive. ```powershell Get-ChildItem -Path C:\LogFiles | Compress-Archive -DestinationPath C:\Archives\PipelineDir.zip ``` `Get-ChildItem` uses the **Path** parameter to specify the `C:\LogFiles` root directory. Each **FileInfo** and **DirectoryInfo** object is sent down the pipeline. `Compress-Archive` adds each object to the `PipelineDir.zip` archive. The **Path** parameter isn't specified because the pipeline objects are received into parameter position 0. ### Example 8: How recursion can affect archives This example shows how recursion can duplicate files in your archive. For example, if you use `Get-ChildItem` with the **Recurse** parameter. As recursion processes, each **FileInfo** and **DirectoryInfo** object is sent down the pipeline and added to the archive. ```powershell Get-ChildItem -Path C:\TestLog -Recurse | Compress-Archive -DestinationPath C:\Archives\PipelineRecurse.zip ``` The `C:\TestLog` directory doesn't contain any files. It does contain a subdirectory named `testsub` that contains the `testlog.txt` file. `Get-ChildItem` uses the **Path** parameter to specify the root directory, `C:\TestLog`. The **Recurse** parameter processes the files and directories. A **DirectoryInfo** object is created for `testsub` and a **FileInfo** object `testlog.txt`. Each object is sent down the pipeline to `Compress-Archive`. The **DestinationPath** specifies the location for the archive file. The **Path** parameter isn't specified because the pipeline objects are received into parameter position 0. The following summary describes the `PipelineRecurse.zip` archive's contents that contains a duplicate file: - The **DirectoryInfo** object creates the `testsub` directory and contains the `testlog.txt` file, which reflects the original directory structure. - The **FileInfo** object creates a duplicate `testlog.txt` in the archive's root. The duplicate file is created because recursion sent a file object to `Compress-Archive`. This behavior is expected because each object sent down the pipeline is added to the archive. ### Example 9: Update an existing archive file This example updates an existing archive file, `Draft.zip`, in the `C:\Archives` directory. In this example, the existing archive file contains the root directory, and its files and subdirectories. ```powershell Compress-Archive -Path C:\Reference -Update -DestinationPath C:\Archives\Draft.zip ``` The command updates `Draft.zip` with newer versions of existing files in the `C:\Reference` directory and its subdirectories. And, new files that were added to `C:\Reference` or its subdirectories are included in the updated `Draft.zip` archive. ## PARAMETERS ### -CompressionLevel Specifies how much compression to apply when you're creating the archive file. Faster compression requires less time to create the file, but can result in larger file sizes. If this parameter isn't specified, the command uses the default value, **Optimal**. The following are the acceptable values for this parameter: - **Fastest**. Use the fastest compression method available to reduce processing time. Faster compression can result in larger file sizes. - **NoCompression**. Doesn't compress the source files. - **Optimal**. Processing time is dependent on file size. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: Optimal, NoCompression, Fastest Required: False Position: Named Default value: Optimal Accept pipeline input: False Accept wildcard characters: False ``` ### -DestinationPath This parameter is required and specifies the path to the archive output file. The **DestinationPath** should include the name of the zipped file, and either the absolute or relative path to the zipped file. If the file name in **DestinationPath** doesn't have a `.zip` file name extension, the cmdlet adds the `.zip` file name extension. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Use this parameter to overwrite an existing archive file. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: PathWithForce, LiteralPathWithForce Aliases: Required: True Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies the path or paths to the files that you want to add to the archive zipped file. Unlike the **Path** parameter, the value of **LiteralPath** is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose each escape character in single quotation marks, to instruct PowerShell not to interpret any characters as escape sequences. To specify multiple paths, and include files in multiple locations in your output zipped file, use commas to separate the paths. ```yaml Type: System.String[] Parameter Sets: LiteralPathWithUpdate, LiteralPathWithForce, LiteralPath Aliases: PSPath Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Causes the cmdlet to output a file object representing the archive file created. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path or paths to the files that you want to add to the archive zipped file. To specify multiple paths, and include files in multiple locations, use commas to separate the paths. This parameter accepts wildcard characters. Wildcard characters allow you to add all files in a directory to your archive file. Using wildcards with a root directory affects the archive's contents: - To create an archive that **includes** the root directory, and all its files and subdirectories, specify the root directory in the **Path** without wildcards. For example: `-Path C:\Reference` - To create an archive that **excludes** the root directory, but zips all its files and subdirectories, use the asterisk (`*`) wildcard. For example: `-Path C:\Reference\*` - To create an archive that only zips the files in the root directory, use the **star-dot-star** (`*.*`) wildcard. Subdirectories of the root aren't included in the archive. For example: `-Path C:\Reference\*.*` ```yaml Type: System.String[] Parameter Sets: Path, PathWithUpdate, PathWithForce Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Update Updates the specified archive by replacing older file versions in the archive with newer file versions that have the same names. You can also add this parameter to add files to an existing archive. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: PathWithUpdate, LiteralPathWithUpdate Aliases: Required: True Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a path to one or more files. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.IO.FileInfo When you use the **PassThru** parameter, this cmdlet returns a **FileInfo** object. ## NOTES Using recursion and sending objects down the pipeline can duplicate files in your archive. For example, if you use `Get-ChildItem` with the **Recurse** parameter, each **FileInfo** and **DirectoryInfo** object that's sent down the pipeline is added to the archive. The `Compress-Archive` cmdlet uses UTF-8 encoding. Other ZIP archive tools may use a different encoding scheme. When extracting files with filenames not stored using UTF-8 encoding, `Expand-Archive` uses the raw value found in the archive. This can result in a filename that's different than the source filename stored in the archive. ## RELATED LINKS [Expand-Archive](Expand-Archive.md) [Get-ChildItem](../Microsoft.PowerShell.Management/Get-ChildItem.md)

#File: reference/7.6/Microsoft.PowerShell.Archive/Expand-Archive.md

--- external help file: Microsoft.PowerShell.Archive-help.xml Locale: en-US Module Name: Microsoft.PowerShell.Archive ms.date: 10/06/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.archive/expand-archive?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Expand-Archive --- # Expand-Archive ## SYNOPSIS Extracts files from a specified archive (zipped) file. ## SYNTAX ### Path (Default) ``` Expand-Archive [-Path] <String> [[-DestinationPath] <String>] [-Force] [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath ``` Expand-Archive -LiteralPath <String> [[-DestinationPath] <String>] [-Force] [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Expand-Archive` cmdlet extracts files from a specified zipped archive file to a specified destination folder. An archive file allows multiple files to be packaged, and optionally compressed, into a single zipped file for easier distribution and storage. ## EXAMPLES ### Example 1: Extract the contents of an archive This example extracts the contents of an existing archive file into the folder specified by the **DestinationPath** parameter. ```powershell Expand-Archive -LiteralPath 'C:\Archives\Draft[v1].zip' -DestinationPath C:\Reference ``` In this example, the **LiteralPath** parameter is used because the filename contains characters that could be interpreted as wildcards. ### Example 2: Extract the contents of an archive in the current folder This example extracts the contents of an existing archive file in the current folder into the folder specified by the **DestinationPath** parameter. ```powershell Expand-Archive -Path Draftv2.zip -DestinationPath C:\Reference ``` ## PARAMETERS ### -DestinationPath By default, `Expand-Archive` creates a folder in the current location that's the same name as the ZIP file. The parameter allows you to specify the path to a different folder. The target folder is created if it doesn't exist. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: A folder in the current location Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Use this parameter to overwrite existing files. By default, `Expand-Archive` doesn't overwrite. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to an archive file. Unlike the **Path** parameter, the value of **LiteralPath** is used exactly as it's typed. Wildcard characters aren't supported. If the path includes escape characters, enclose each escape character in single quotation marks, to instruct PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String Parameter Sets: LiteralPath Aliases: PSPath Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Causes the cmdlet to output a list of the files expanded from the archive. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to the archive file. ```yaml Type: System.String Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a path to an existing archive file. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.IO.FileSystemInfo When you use the **PassThru** parameter, this cmdlet returns a list of files that were expanded from the archive. ## NOTES The `Compress-Archive` cmdlet uses UTF-8 encoding. Other ZIP archive tools may use a different encoding scheme. When extracting files with filenames not stored using UTF-8 encoding, `Expand-Archive` uses the raw value found in the archive. This can result in a filename that's different than the source filename stored in the archive. ## RELATED LINKS [Compress-Archive](Compress-Archive.md)

#File: reference/7.6/Microsoft.PowerShell.Archive/Microsoft.PowerShell.Archive.md

--- Download Help Link: https://aka.ms/powershell75-help Help Version: 7.6.0.0 Locale: en-US Module Guid: eb74e8da-9ae2-482a-a648-e96550fb8733 Module Name: Microsoft.PowerShell.Archive ms.date: 06/09/2017 schema: 2.0.0 title: Microsoft.PowerShell.Archive --- # Microsoft.PowerShell.Archive Module ## Description This section contains the help topics for the cmdlets that are installed with the PowerShell Microsoft.PowerShell.Archive module. The Archive module contains cmdlets that let you create and extract archive or ZIP files. ## Microsoft.PowerShell.Archive Cmdlets ### [Compress-Archive](Compress-Archive.md) Creates a compressed archive, or zipped file, from specified files and directories. ### [Expand-Archive](Expand-Archive.md) Extracts files from a specified archive (zipped) file.

#File: reference/7.6/Microsoft.PowerShell.Core/Add-History.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 09/15/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/add-history?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Add-History --- # Add-History ## SYNOPSIS Appends entries to the session history. ## SYNTAX ``` Add-History [[-InputObject] <PSObject[]>] [-PassThru] [<CommonParameters>] ``` ## DESCRIPTION The `Add-History` cmdlet adds entries to the end of the session history, that is, the list of commands entered during the current session. The session history is a list of the commands entered during the session. The session history represents the order of execution, the status, and the start and end times of the command. As you enter each command, PowerShell adds it to the history so that you can reuse it. For more information about the session history, see [about_History](About/about_History.md). The session history is managed separately from the history maintained by the **PSReadLine** module. Both histories are available in sessions where **PSReadLine** is loaded. This cmdlet only works with the session history. For more information see, [about_PSReadLine](../PSReadLine/About/about_PSReadLine.md). You can use the `Get-History` cmdlet to get the commands and pass them to `Add-History`, or you can export the commands to a CSV or XML file, then import the commands, and pass the imported file to `Add-History`. You can use this cmdlet to add specific commands to the history or to create a single history file that includes commands from more than one session. ## EXAMPLES ### Example 1: Add commands to the history of a different session This example add the commands typed in one PowerShell session to the history of a different PowerShell session. ```powershell Get-History | Export-Csv -Path C:\testing\history.csv -IncludeTypeInformation Import-Csv -Path C:\testing\history.csv | Add-History ``` The first command gets objects representing the commands in the history and exports them to the `History.csv` file. The second command is typed at the command line of a different session. It uses the `Import-Csv` cmdlet to import the objects in the `History.csv` file. The pipeline operator (`|`) passes the objects to the `Add-History` cmdlet, which adds the objects representing the commands in the `History.csv` file to the current session history. ### Example 2: Import and run commands This example imports commands from the `History.xml` file, adds them to the current session history, and then runs the commands in the combined history. ```powershell Import-Clixml -Path C:\temp\history.xml | Add-History -PassThru | ForEach-Object -Process {Invoke-History} ``` The first command uses the `Import-Clixml` cmdlet to import a command history that was exported to the `History.xml` file. The pipeline operator passes the commands to the `Add-History` cmdlet, which adds the commands to the current session history. The **PassThru** parameter passes the objects representing the added commands down the pipeline. The command then uses the `ForEach-Object` cmdlet to apply the `Invoke-History` command to each of the commands in the combined history. The `Invoke-History` command is formatted as a script block, enclosed in braces (`{}`), as required by the **Process** parameter of the `ForEach-Object` cmdlet. ### Example 3: Add commands in the history to the end of the history This example adds the first five commands in the history to the end of the history list. ```powershell Get-History -Id 5 -Count 5 | Add-History ``` The `Get-History` cmdlet gets the five commands ending in command 5. The pipeline operator passes them to the `Add-History` cmdlet, which appends them to the current history. The `Add-History` command does not include any parameters, but PowerShell associates the objects passed through the pipeline with the **InputObject** parameter of `Add-History`. ### Example 4: Add commands in a .csv file to the current history This example add the commands in the `History.csv` file to the current session history. ```powershell $a = Import-Csv -Path C:\testing\history.csv Add-History -InputObject $a -PassThru ``` The `Import-Csv` cmdlet imports the commands in the `History.csv` file and store its contents in the variable `$a`. The second command uses the `Add-History` cmdlet to add the commands from `History.csv` to the current session history. It uses the **InputObject** parameter to specify the `$a` variable and the **PassThru** parameter to generate an object to display at the command line. Without the **PassThru** parameter, the `Add-History` cmdlet does not generate any output. ### Example 5: Add commands in an .xml file to the current history This example adds the commands in the `history.xml` file to the current session history. ```powershell Add-History -InputObject (Import-Clixml -Path C:\temp\history.xml) ``` The **InputObject** parameter passes the results of the command in parentheses to the `Add-History` cmdlet. The command in parentheses, which is executed first, imports the `history.xml` file into PowerShell. The `Add-History` cmdlet then adds the commands in the file to the session history. ## PARAMETERS ### -InputObject Specifies an array of entries to add to the history as **HistoryInfo** object to the session history. You can use this parameter to submit a **HistoryInfo** object, such as the ones that are returned by the `Get-History`, `Import-Clixml`, or `Import-Csv` cmdlets, to `Add-History`. ```yaml Type: System.Management.Automation.PSObject[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -PassThru Indicates that this cmdlet returns a **HistoryInfo** object for each history entry. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### Microsoft.PowerShell.Commands.HistoryInfo You can pipe a **HistoryInfo** object to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### Microsoft.PowerShell.Commands.HistoryInfo When you use the **PassThru** parameter, this cmdlet returns a **HistoryInfo** object. ## NOTES The session history is a list of the commands entered during the session together with the ID. The session history represents the order of execution, the status, and the start and end times of the command. As you enter each command, PowerShell adds it to the history so that you can reuse it. For more information about the session history, see [about_History](About/about_History.md). To specify the commands to add to the history, use the **InputObject** parameter. The `Add-History` command accepts only **HistoryInfo** objects, such as those returned for each command by the `Get-History` cmdlet. You cannot pass it a path and file name or a list of commands. You can use the **InputObject** parameter to pass a file of **HistoryInfo** objects to `Add-History`. To do so, export the results of a `Get-History` command to a file by using the `Export-Csv` or `Export-Clixml` cmdlet and then import the file by using the `Import-Csv` or `Import-Clixml` cmdlets. You can then pass the file of imported **HistoryInfo** objects to `Add-History` through a pipeline or in a variable. For more information, see the examples. The file of **HistoryInfo** objects that you pass to the `Add-History` cmdlet must include the type information, column headings, and all of the properties of the **HistoryInfo** objects. If you intend to pass the objects back to `Add-History`, do not use the **NoTypeInformation** parameter of the `Export-Csv` cmdlet and do not delete the type information, column headings, or any fields in the file. To modify the session history, export the session to a CSV or XML file, modify the file, import the file, and use `Add-History` to append it to the current session history. ## RELATED LINKS [Clear-History](Clear-History.md) [Get-History](Get-History.md) [Invoke-History](Invoke-History.md) [about_PSReadLine](../PSReadLine/About/about_PSReadLine.md) [Get-PSReadLineOption](/powershell/module/psreadline/get-psreadlineoption) [Set-PSReadLineOption](/powershell/module/psreadline/set-psreadlineoption)

#File: reference/7.6/Microsoft.PowerShell.Core/Clear-History.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/clear-history?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Clear-History --- # Clear-History ## SYNOPSIS Deletes entries from the PowerShell session command history. ## SYNTAX ### IDParameter (Default) ``` Clear-History [[-Id] <int[]>] [[-Count] <int>] [-Newest] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### CommandLineParameter ``` Clear-History [[-Count] <int>] [-CommandLine <string[]>] [-Newest] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION `Clear-History` deletes the command history from a PowerShell session. Each PowerShell session has its own command history. To display the command history, use the `Get-History` cmdlet. By default, `Clear-History` deletes the entire command history from a PowerShell session. You can use parameters with `Clear-History` to delete selected commands. `Clear-History` does not clear the `PSReadLine` command history file. The `PSReadLine` module stores a history file that contains every PowerShell command from every PowerShell session. From a PowerShell prompt, use the up and down arrows on your keyboard to scroll through the command history. To display the `PSReadLine` configuration for command history, use `Get-PSReadLineOption`. `PSReadLine` shipped with PowerShell 5.0 and above. For more information, see [about_PSReadLine](../PSReadLine/About/about_PSReadLine.md). ## EXAMPLES ### Example 1: Delete the command history from a PowerShell session This command deletes all of the commands from a PowerShell session's history. ```powershell Get-History ``` ```Output Id CommandLine -- ----------- 1 Set-Location .\Test 2 Update-Help 3 Set-Location C:\Test\Logs 4 Get-Location ``` ```powershell Clear-History Get-History ``` ```Output Id CommandLine -- ----------- 5 Clear-History ``` The `Get-History` cmdlet displays the PowerShell session's history. `Clear-History` deletes the entire command history. `Get-History` displays the updated command history and confirms the prior history was deleted. ### Example 2: Delete the newest commands This command uses the **Count** and **Newest** parameters to delete the newest commands from a PowerShell session's history. ```powershell Get-History ``` ```Output Id CommandLine -- ----------- 1 Set-Location C:\Test\ 2 Get-Command Clear-History 3 Get-Command Clear-History -Syntax 4 Get-Command Clear-History -ShowCommandInfo 5 Get-Help Get-Alias 6 Get-Command Get-ChildItem -Syntax 7 Get-Help Clear-History 8 Set-Location C:\Test\Logs 9 Get-Help Get-Variable 10 Get-Help Get-ChildItem ``` ```powershell Clear-History -Count 5 -Newest Get-History ``` ```Output Id CommandLine -- ----------- 1 Set-Location C:\Test\ 2 Get-Command Clear-History 3 Get-Command Clear-History -Syntax 4 Get-Command Clear-History -ShowCommandInfo 5 Get-Help Get-Alias 11 Clear-History -Count 5 -Newest ``` The `Get-History` cmdlet displays the PowerShell session's history. `Clear-History` is used to delete the command history. The **Count** parameter specifies the number of commands to delete, inclusive of the specified **Id**. The **Newest** parameter specifies that the newest commands are cleared from the history. `Get-History` displays the updated command history and confirms that the five newest commands were deleted, **Id 6** - **Id 10**. ### Example 3: Delete commands that match specific criteria This command deletes commands that match specific criteria defined by the **CommandLine** parameter. ```powershell Get-History ``` ```Output Id CommandLine -- ----------- 1 Set-Location C:\Test\ 2 Get-Command Clear-History 3 Get-Command Clear-History -Syntax 4 Get-Command Clear-History -ShowCommandInfo 5 Get-Help Get-Alias 6 Get-Command Get-ChildItem -Syntax 7 Get-Help Clear-History ``` ```powershell Clear-History -CommandLine *Help*, *Syntax Get-History ``` ```Output Id CommandLine -- ----------- 1 Set-Location C:\Test\ 2 Get-Command Clear-History 4 Get-Command Clear-History -ShowCommandInfo 8 Clear-History -CommandLine *Help*, *Syntax ``` The `Get-History` cmdlet displays the PowerShell session's history. `Clear-History` deletes the command history. The **CommandLine** parameter specifies commands that contain **Help** or end with **Syntax**. `Get-History` displays the updated command history and confirms that commands **Id 3**, **Id 5**, **Id 6**, and **Id 7** were deleted. ### Example 4: Delete commands by Id number This command deletes specific history items using the **Id**. To delete multiple commands, submit a comma-separated list of **Id** numbers. ```powershell Get-History ``` ```Output Id CommandLine -- ----------- 1 Set-Location C:\Test\ 2 Get-History 3 Get-Help Get-Alias 4 Get-Command Clear-History 5 Get-Command Clear-History -Syntax 6 Get-Command Clear-History -ShowCommandInfo ``` ```powershell Clear-History -Id 3, 5 Get-History ``` ```Output Id CommandLine -- ----------- 1 Set-Location C:\Test\ 2 Get-History 4 Get-Command Clear-History 6 Get-Command Clear-History -ShowCommandInfo 7 Get-History 8 Clear-History -Id 3, 5 ``` The `Get-History` cmdlet displays the PowerShell session's history. `Clear-History` deletes the command history. The **Id** parameter specifies which commands to delete. `Get-History` displays the updated command history and confirms that **Id 3** and **Id 5** were deleted. ### Example 5: Delete commands by Id number and count This command uses the **Id** and **Count** parameters to delete command history. Commands are deleted from the specified **Id** in reverse order, newest to oldest. ```powershell Get-History ``` ```Output Id CommandLine -- ----------- 1 Set-Location C:\Test\ 2 Get-Command Clear-History 3 Get-Command Clear-History -Syntax 4 Get-Command Clear-History -ShowCommandInfo 5 Get-Help Get-Alias 6 Get-Command Get-ChildItem -Syntax 7 Get-Help Clear-History 8 Set-Location C:\Test\Logs 9 Get-Help Get-Variable 10 Get-Help Get-ChildItem ``` ```powershell Clear-History -Id 7 -Count 5 Get-History ``` ```Output Id CommandLine -- ----------- 1 Set-Location C:\Test\ 2 Get-Command Clear-History 8 Set-Location C:\Test\Logs 9 Get-Help Get-Variable 10 Get-Help Get-ChildItem 11 Clear-History -Id 7 -Count 5 ``` The `Get-History` cmdlet displays the PowerShell session's history. `Clear-History` deletes the command history. The **Id** parameter specifies to begin with **Id 7**. The **Count** parameter specifies to delete five commands, inclusive of the specified **Id**. `Get-History` displays the updated command history and confirms that five commands were deleted, **Id 3** - **Id 7**. ## PARAMETERS ### -CommandLine Deletes command history from a PowerShell session. The string must be an exact match or use wildcards to match commands in the PowerShell session history displayed by `Get-History`. If you enter more than one string, `Clear-History` deletes commands that match any of the strings. The **CommandLine** parameter can be used with **Count**. For strings with a space, use single quotations. For more information, see [about_Quoting_Rules](About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: CommandLineParameter Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Count Specifies the number of history entries that `Clear-History` deletes. Commands are deleted in order, beginning with the oldest entry in the history. The **Count** and **Id** parameters can be used together. The **Count** parameter specifies the number of commands to delete, inclusive of the specified **Id**. Beginning at the specified **Id**, commands are deleted in reverse sequential order. For example, if the **Id** is 30 and the **Count** is 10, `Clear-History` deletes items 21 through 30. The **Count** and **CommandLine** parameters can be used together. **Count** specifies the number of commands to delete that match **CommandLine** parameter value. The commands are deleted in sequential order. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies the command history **Id** that `Clear-History` deletes. To display **Id** numbers, use the `Get-History` cmdlet. The **Id** numbers are sequential and commands keep their **Id** number throughout a PowerShell session. The **Id** parameter can be used with **Count** and **Newest**. ```yaml Type: System.Int32[] Parameter Sets: IDParameter Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Newest When the **Newest** parameter is used, `Clear-History` deletes the newest entries in the history. By default, `Clear-History` deletes the oldest entries in the history. The **Newest** parameter can be used with **Id** and **Count**. The **Count** parameter specifies the number of commands to delete, inclusive of the specified **Id**. Beginning at the specified **Id**, commands are deleted in sequential order. For example, if the **Id** is 30 and the **Count** is 10, `Clear-History` deletes items 30 through 39. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the `Clear-History` cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the `Clear-History` cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Clear-History`: - All platforms: - `clhy` The PowerShell session history is a list of the commands entered during a PowerShell session. You can view the history, add and delete commands, and run commands from the history. For more information, see [about_History](About/about_History.md). The session history is managed separately from the history maintained by the **PSReadLine** module. Both histories are available in sessions where **PSReadLine** is loaded. This cmdlet only works with the session history. For more information see, [about_PSReadLine](../PSReadLine/About/about_PSReadLine.md). ## RELATED LINKS [about_History](About/about_History.md) [about_PSReadLine](../PSReadLine/About/about_PSReadLine.md) [about_Quoting_Rules](About/about_Quoting_Rules.md) [Add-History](Add-History.md) [Get-History](Get-History.md) [Invoke-History](Invoke-History.md) [Get-PSReadLineOption](/powershell/module/psreadline/get-psreadlineoption) [Set-PSReadLineOption](/powershell/module/psreadline/set-psreadlineoption)

#File: reference/7.6/Microsoft.PowerShell.Core/Clear-Host.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 04/29/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/clear-host?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Clear-Host --- # Clear-Host ## SYNOPSIS Clears the display in the host program. ## SYNTAX ``` Clear-Host ``` ## DESCRIPTION The `Clear-Host` function removes all text from the current display, including commands and output that might have accumulated. When complete, it displays the command prompt. You can use the function name or its alias, `cls`. `Clear-Host` affects only the current display. It does not delete saved results or remove any items from the session. Session-specific items, such as variables and functions, are not affected by this function. Because the behavior of the `Clear-Host` function is determined by the host program, `Clear-Host` might work differently in different host programs. ## EXAMPLES ### Example 1 ```powershell PS> Get-Process | Select-Object -First 5 Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 843 33 14428 22556 99 17.41 1688 CcmExec 44 6 2196 4964 52 0.23 692 conhost 646 12 2332 4896 49 1.12 388 csrss 189 11 2860 7084 114 0.66 2896 csrss 78 11 1876 4008 42 0.22 4000 csrss PS> Clear-Host ``` ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Clear-Host`: - Windows: - `clear` - `cls` - Linux and macOS: - `cls` `Clear-Host` is a simple function, not an advanced function. There are no parameters. ## RELATED LINKS [Get-Host](../Microsoft.PowerShell.Utility/Get-Host.md) [Out-Host](Out-Host.md) [Read-Host](../Microsoft.PowerShell.Utility/Read-Host.md) [Write-Host](../Microsoft.PowerShell.Utility/Write-Host.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Connect-PSSession.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 09/09/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/connect-pssession?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Connect-PSSession --- # Connect-PSSession ## SYNOPSIS Reconnects to disconnected sessions. ## SYNTAX ### Name (Default) ``` Connect-PSSession -Name <String[]> [-ThrottleLimit <Int32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Session ``` Connect-PSSession [-Session] <PSSession[]> [-ThrottleLimit <Int32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ComputerNameGuid ``` Connect-PSSession -ComputerName <String[]> [-ApplicationName <String>] [-ConfigurationName <String>] -InstanceId <Guid[]> [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [-Port <Int32>] [-UseSSL] [-SessionOption <PSSessionOption>] [-ThrottleLimit <Int32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ComputerName ``` Connect-PSSession -ComputerName <String[]> [-ApplicationName <String>] [-ConfigurationName <String>] [-Name <String[]>] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [-Port <Int32>] [-UseSSL] [-SessionOption <PSSessionOption>] [-ThrottleLimit <Int32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ConnectionUriGuid ``` Connect-PSSession [-ConfigurationName <String>] [-ConnectionUri] <Uri[]> [-AllowRedirection] -InstanceId <Guid[]> [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <Int32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ConnectionUri ``` Connect-PSSession [-ConfigurationName <String>] [-ConnectionUri] <Uri[]> [-AllowRedirection] [-Name <String[]>] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [-SessionOption <PSSessionOption>] [-ThrottleLimit <Int32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### InstanceId ``` Connect-PSSession -InstanceId <Guid[]> [-ThrottleLimit <Int32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Id ``` Connect-PSSession [-ThrottleLimit <Int32>] [-Id] <Int32[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Connect-PSSession` cmdlet reconnects to user-managed PowerShell sessions (**PSSessions**) that were disconnected. It works on sessions that are disconnected intentionally, such as by using the `Disconnect-PSSession` cmdlet or the **InDisconnectedSession** parameter of the `Invoke-Command` cmdlet, and those that were disconnected unintentionally, such as by a temporary network outage. `Connect-PSSession` can connect to any disconnected session that was started by the same user. These include those that were started by or disconnected from other sessions on other computers. However, `Connect-PSSession` cannot connect to broken or closed sessions, or interactive sessions started by using the `Enter-PSSession` cmdlet. Also you cannot connect sessions to sessions started by other users, unless you can provide the credentials of the user who created the session. For more information about the Disconnected Sessions feature, see [about_Remote_Disconnected_Sessions](about/about_Remote_Disconnected_Sessions.md). This cmdlet was introduced in Windows PowerShell 3.0. ## EXAMPLES ### Example 1: Reconnect to a session ```powershell Connect-PSSession -ComputerName Server01 -Name ITTask ``` ```Output Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 4 ITTask Server01 Opened ITTasks Available ``` This command reconnects to the `ITTask` session on the Server01 computer. The output shows that the command was successful. The **State** of the session is `Opened` and the **Availability** is `Available`, which indicates that you can run commands in the session. ### Example 2: Effect of disconnecting and reconnecting ```powershell Get-PSSession ``` ```Output Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 Backups Localhost Opened Microsoft.PowerShell Available ``` ```powershell Get-PSSession | Disconnect-PSSession ``` ```Output Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 Backups Localhost Disconnected Microsoft.PowerShell None ``` ```powershell Get-PSSession | Connect-PSSession ``` ```Output Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 Backups Localhost Opened Microsoft.PowerShell Available ``` This example shows the effect of disconnecting and then reconnecting to a session. The first command uses the `Get-PSSession` cmdlet. Without the **ComputerName** parameter, the command gets only sessions that were created in the current session. The output shows that the command gets the `Backups` session on the local computer. The **State** of the session is `Opened` and the **Availability** is `Available`. The second command uses the `Get-PSSession` cmdlet to get the **PSSession** objects that were created in the current session and the `Disconnect-PSSession` cmdlet to disconnect the sessions. The output shows that the `Backups` session was disconnected. The **State** of the session is `Disconnected` and the **Availability** is `None`. The third command uses the `Get-PSSession` cmdlet to get the **PSSession** objects that were created in the current session and the `Connect-PSSession` cmdlet to reconnect the sessions. The output shows that the `Backups` session was reconnected. The **State** of the session is `Opened` and the **Availability** is `Available`. If you use the `Connect-PSSession` cmdlet on a session that is not disconnected, the command does not affect the session and it does not generate any errors. ### Example 3: Series of commands in an enterprise scenario This series of commands shows how the `Connect-PSSession` cmdlet might be used in an enterprise scenario. In this case, a system administrator starts a long-running job in a session on a remote computer. After starting the job, the administrator disconnects from the session and goes home. Later that evening, the administrator logs on to her home computer and verifies that the job ran until it is completed. The administrator starts by creating a sessions on a remote computer and running a script in the session.The first command uses the `New-PSSession` cmdlet to create the `ITTask` session on the Server01 remote computer. The command uses the **ConfigurationName** parameter to specify the `ITTasks` session configuration. The command saves the sessions in the `$s` variable. The second command `Invoke-Command` cmdlet to start a background job in the session in the `$s` variable. It uses the **FilePath** parameter to run the script in the background job. The third command uses the `Disconnect-PSSession` cmdlet to disconnect from the session in the `$s` variable. The command uses the **OutputBufferingMode** parameter with a value of `Drop` to prevent the script from being blocked by having to deliver output to the session. It uses the **IdleTimeoutSec** parameter to extend the session time-out to 15 hours. When the command is completed, the administrator locks her computer and goes home for the evening. Later that evening, the administrator starts her home computer, logs on to the corporate network, and starts PowerShell. The fourth command uses the `Get-PSSession` cmdlet to get the sessions on the Server01 computer. The command finds the `ITTask` session. The fifth command uses the `Connect-PSSession` cmdlet to connect to the `ITTask` session. The command saves the session in the `$s` variable. The sixth command uses the `Invoke-Command` cmdlet to run a `Get-Job` command in the session in the `$s` variable. The output shows that the job finished successfully.The seventh command uses the `Invoke-Command` cmdlet to run a `Receive-Job` command in the session in the `$s` variable in the session. The command saves the results in the `$BackupSpecs` variable.The eighth command uses the `Invoke-Command` cmdlet to runs another script in the session. The command uses the value of the `$BackupSpecs` variable in the session as input to the script. ```powershell $s = New-PSSession -ComputerName Server01 -Name ITTask -ConfigurationName ITTasks Invoke-Command -Session $s -ScriptBlock {Start-Job -FilePath \\Server30\Scripts\Backup-SQLDatabase.ps1} ``` ```Output Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 2 Job2 Running True Server01 \\Server30\Scripts\Backup... ``` ```powershell Disconnect-PSSession -Session $s -OutputBufferingMode Drop -IdleTimeoutSec 60*60*15 ``` ```Output Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 ITTask Server01 Disconnected ITTasks None ``` ```powershell Get-PSSession -ComputerName Server01 -Name ITTask ``` ```Output Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 ITTask Server01 Disconnected ITTasks None ``` ```powershell $s = Connect-PSSession -ComputerName Server01 -Name ITTask ``` ```Output Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 ITTask Server01 Opened ITTasks Available ``` ```powershell Invoke-Command -Session $s -ScriptBlock {Get-Job} ``` ```Output Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 2 Job2 Completed True Server01 \\Server30\Scripts\Backup... ``` ```powershell Invoke-Command -Session $s -ScriptBlock {$BackupSpecs = Receive-Job -JobName Job2} Invoke-Command -Session $s -ScriptBlock {\\Server30\Scripts\New-SQLDatabase.ps1 -InitData $BackupSpecs.Initialization} Disconnect-PSSession -Session $s -OutputBufferingMode Drop -IdleTimeoutSec 60*60*15 ``` ```Output Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 ITTask Server01 Disconnected ITTasks None ``` The ninth command disconnects from the session in the `$s` variable. The administrator closes PowerShell and closes the computer. She can reconnect to the session on the next day and check the script status from her work computer. ## PARAMETERS ### -AllowRedirection Indicates that this cmdlet allows redirection of this connection to an alternate URI. When you use the **ConnectionURI** parameter, the remote destination can return an instruction to redirect to a different URI. By default, PowerShell does not redirect connections, but you can use this parameter to allow it to redirect the connection. You can also limit the number of times the connection is redirected by changing the **MaximumConnectionRedirectionCount** session option value. Use the **MaximumRedirection** parameter of the `New-PSSessionOption` cmdlet or set the **MaximumConnectionRedirectionCount** property of the **$PSSessionOption** preference variable. The default value is `5`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ConnectionUriGuid, ConnectionUri Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ApplicationName Specifies the name of an application. This cmdlet connects only to sessions that use the specified application. Enter the application name segment of the connection URI. For example, in the following connection URI, the application name is WSMan: `http://localhost:5985/WSMAN`. The application name of a session is stored in the **Runspace.ConnectionInfo.AppName** property of the session. The value of this parameter is used to select and filter sessions. It does not change the application that the session uses. ```yaml Type: System.String Parameter Sets: ComputerNameGuid, ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Authentication Specifies the mechanism that is used to authenticate user credentials in the command to reconnect to the disconnected session. The acceptable values for this parameter are: - `Default` - `Basic` - `Credssp` - `Digest` - `Kerberos` - `Negotiate` - `NegotiateWithImplicitCredential` The default value is `Default`. For more information about the values of this parameter, see [AuthenticationMechanism Enumeration](/dotnet/api/system.management.automation.runspaces.authenticationmechanism). > [!CAUTION] > Credential Security Support Provider (CredSSP) authentication, in which the user's credentials are > passed to a remote computer to be authenticated, is designed for commands that require > authentication on more than one resource, such as accessing a remote network share. This mechanism > increases the security risk of the remote operation. If the remote computer is compromised, the > credentials that are passed to it can be used to control the network session. ```yaml Type: System.Management.Automation.Runspaces.AuthenticationMechanism Parameter Sets: ComputerNameGuid, ComputerName, ConnectionUriGuid, ConnectionUri Aliases: Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential, Credssp, Digest, Kerberos Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to connect to the disconnected session. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts. They do not work with domain accounts. To get a certificate thumbprint, use a `Get-Item` or `Get-ChildItem` command in the PowerShell `Cert:` drive. ```yaml Type: System.String Parameter Sets: ComputerNameGuid, ComputerName, ConnectionUriGuid, ConnectionUri Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies the computers on which the disconnected sessions are stored. Sessions are stored on the computer that is at the server-side or receiving end of a connection. The default is the local computer. Type the NetBIOS name, an IP address, or a fully qualified domain name of one computer. Wildcard characters are not permitted. To specify the local computer, type the computer name, `localhost`, or a dot (`.`) ```yaml Type: System.String[] Parameter Sets: ComputerNameGuid, ComputerName Aliases: Cn Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ConfigurationName Connects only to sessions that use the specified session configuration. Enter a configuration name or the fully qualified resource URI for a session configuration. If you specify only the configuration name, the following schema URI is prepended: `http://schemas.microsoft.com/powershell`. The configuration name of a session is stored in the **ConfigurationName** property of the session. The value of this parameter is used to select and filter sessions. It does not change the session configuration that the session uses. For more information about session configurations, see [about_Session_Configurations](About/about_Session_Configurations.md). ```yaml Type: System.String Parameter Sets: ComputerNameGuid, ComputerName, ConnectionUriGuid, ConnectionUri Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ConnectionUri Specifies the URIs of the connection endpoints for the disconnected sessions. The URI must be fully qualified. The format of this string is as follows: `<Transport>://<ComputerName>:<Port>/<ApplicationName>` The default value is as follows: `http://localhost:5985/WSMAN` If you do not specify a connection URI, you can use the **UseSSL** and **Port** parameters to specify the connection URI values. Valid values for the **Transport** segment of the URI are HTTP and HTTPS. If you specify a connection URI with a Transport segment, but do not specify a port, the session is created with standards ports: `80` for HTTP and `443` for HTTPS. To use the default ports for PowerShell remoting, specify port `5985` for HTTP or `5986` for HTTPS. If the destination computer redirects the connection to a different URI, PowerShell prevents the redirection unless you use the **AllowRedirection** parameter in the command. ```yaml Type: System.Uri[] Parameter Sets: ConnectionUriGuid, ConnectionUri Aliases: URI, CU Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to connect to the disconnected session. The default is the current user. Type a username, such as `User01` or `Domain01\User01`, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. If you type a user name, you're prompted to enter the password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: ComputerNameGuid, ComputerName, ConnectionUriGuid, ConnectionUri Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies the IDs of the disconnected sessions. The **Id** parameter works only when the disconnected session was previously connected to the current session. This parameter is valid, but not effective, when the session is stored on the local computer, but was not connected to the current session. ```yaml Type: System.Int32[] Parameter Sets: Id Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InstanceId Specifies the instance IDs of the disconnected sessions. The instance ID is a GUID that uniquely identifies a **PSSession** on a local or remote computer. The instance ID is stored in the **InstanceId** property of the **PSSession**. ```yaml Type: System.Guid[] Parameter Sets: ComputerNameGuid, ConnectionUriGuid, InstanceId Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies the friendly names of the disconnected sessions. ```yaml Type: System.String[] Parameter Sets: Name, ComputerName, ConnectionUri Aliases: Required: True (Name), False (ComputerName, ConnectionUri) Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Port Specifies the network port on the remote computer that is used to reconnect to the session. To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are `5985`, which is the WinRM port for HTTP, and `5986`, which is the WinRM port for HTTPS. Before using an alternate port, you must configure the WinRM listener on the remote computer to listen at that port. To configure the listener, type the following two commands at the PowerShell prompt: `Remove-Item -Path WSMan:\Localhost\listener\listener* -Recurse` `New-Item -Path WSMan:\Localhost\listener -Transport http -Address * -Port \<port-number\>` Do not use the **Port** parameter unless you must. The port that is set in the command applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on all computers. ```yaml Type: System.Int32 Parameter Sets: ComputerNameGuid, ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Session Specifies the disconnected sessions. Enter a variable that contains the **PSSession** objects or a command that creates or gets the **PSSession** objects, such as a `Get-PSSession` command. ```yaml Type: System.Management.Automation.Runspaces.PSSession[] Parameter Sets: Session Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -SessionOption Specifies advanced options for the session. Enter a **SessionOption** object, such as one that you create by using the `New-PSSessionOption` cmdlet, or a hash table in which the keys are session option names and the values are session option values. The default values for the options are determined by the value of the `$PSSessionOption` preference variable, if it is set. Otherwise, the default values are established by options set in the session configuration. The session option values take precedence over default values for sessions set in the `$PSSessionOption` preference variable and in the session configuration. However, they do not take precedence over maximum values, quotas or limits set in the session configuration. For a description of the session options that includes the default values, see `New-PSSessionOption`. For information about the **$PSSessionOption** preference variable, see [about_Preference_Variables](About/about_Preference_Variables.md). For more information about session configurations, see [about_Session_Configurations](About/about_Session_Configurations.md). ```yaml Type: System.Management.Automation.Remoting.PSSessionOption Parameter Sets: ComputerNameGuid, ComputerName, ConnectionUriGuid, ConnectionUri Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ThrottleLimit Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of `0`, the default value, `32`, is used. The throttle limit applies only to the current command, not to the session or to the computer. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to connect to the disconnected session. By default, SSL is not used. WS-Management encrypts all PowerShell content transmitted over the network. The **UseSSL** parameter is an additional protection that sends the data across an HTTPS connection instead of an HTTP connection. If you use this parameter, but SSL is not available on the port that is used for the command, the command fails. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerNameGuid, ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.Runspaces.PSSession You can pipe a session (**PSSession**) to this cmdlet. ## OUTPUTS ### System.Management.Automation.Runspaces.PSSession This cmdlet returns an object that represents the session to which it reconnected. ## NOTES PowerShell includes the following aliases for `Connect-PSSession`: - Windows: - `cnsn` - This cmdlet is only available on Windows platforms. - `Connect-PSSession` reconnects only to sessions that are disconnected, that is, sessions that have a value of Disconnected for the **State** property. Only sessions that are connected to, or end at, computers that run Windows PowerShell 3.0 or later versions can be disconnected and reconnected. - If you use `Connect-PSSession` on a session that is not disconnected, the command does not affect the session and it does not generate errors. - Disconnected loopback sessions with interactive tokens, which are created by using the **EnableNetworkAccess** parameter, can be reconnected only from the computer on which the session was created. This restriction protects the computer from malicious access. - The value of the **State** property of a **PSSession** is relative to the current session. Therefore, a value of **Disconnected** means that the **PSSession** is not connected to the current session. However, it does not mean that the **PSSession** is disconnected from all sessions. It might be connected to a different session. To determine whether you can connect or reconnect to the session, use the **Availability** property. An **Availability** value of None indicates that you can connect to the session. A value of Busy indicates that you cannot connect to the **PSSession** because it is connected to another session. For more information about the values of the **State** property of sessions, see [RunspaceState Enumeration](/dotnet/api/system.management.automation.runspaces.runspacestate). For more information about the values of the **Availability** property of sessions, see [RunspaceAvailability Enumeration](/dotnet/api/system.management.automation.runspaces.runspaceavailability). - You cannot change the idle time-out value of a **PSSession** when you connect to the **PSSession**. The **SessionOption** parameter of `Connect-PSSession` takes a **SessionOption** object that has an **IdleTimeout** value. However, the **IdleTimeout** value of the **SessionOption** object and the **IdleTimeout** value of the `$PSSessionOption` variable are ignored when connecting to a **PSSession**. You can set and change the idle time-out of a **PSSession** when you create the **PSSession**, by using the `New-PSSession` or `Invoke-Command` cmdlets, and when you disconnect from the **PSSession**. The **IdleTimeout** property of a **PSSession** is critical to disconnected sessions, because it determines how long a disconnected session is maintained on the remote computer. Disconnected sessions are considered to be idle from the moment that they are disconnected, even if commands are running in the disconnected session. ## RELATED LINKS [Disconnect-PSSession](Disconnect-PSSession.md) [Enter-PSSession](Enter-PSSession.md) [Exit-PSSession](Exit-PSSession.md) [Get-PSSession](Get-PSSession.md) [Get-PSSessionConfiguration](Get-PSSessionConfiguration.md) [New-PSSession](New-PSSession.md) [New-PSSessionOption](New-PSSessionOption.md) [New-PSTransportOption](New-PSTransportOption.md) [Receive-PSSession](Receive-PSSession.md) [Register-PSSessionConfiguration](Register-PSSessionConfiguration.md) [Remove-PSSession](Remove-PSSession.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Debug-Job.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 01/20/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/debug-job?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Debug-Job --- # Debug-Job ## SYNOPSIS Debugs a running background or remote job. ## SYNTAX ### JobParameterSet (Default) ``` Debug-Job [-Job] <Job> [-BreakAll] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### JobNameParameterSet ``` Debug-Job [-Name] <String> [-BreakAll] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### JobIdParameterSet ``` Debug-Job [-Id] <Int32> [-BreakAll] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### JobInstanceIdParameterSet ``` Debug-Job [-InstanceId] <Guid> [-BreakAll] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Debug-Job` cmdlet lets you debug scripts that are running within jobs. The cmdlet is designed to debug PowerShell Workflow jobs, background jobs, and jobs running in remote sessions. `Debug-Job` accepts a running job object, name, ID, or instance ID as input, and starts a debugging session on the script it is running. The debugger `quit` command stops the job and running script. The `exit` command detaches the debugger, and allows the job to continue to run. ## EXAMPLES ### Example 1: Debug a job by job ID This command breaks into a running job with an ID of 3. ```powershell Debug-Job -Id 3 ``` ```Output Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 3 Job3 RemoteJob Running True PowerShellIx TestWFDemo1.ps1 Entering debug mode. Use h or ? for help. Hit Line breakpoint on 'C:\TestWFDemo1.ps1:8' At C:\TestWFDemo1.ps1:8 char:5 + Write-Output -InputObject "Now writing output:" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [DBG:PowerShellIx]: PS C:\> > list 3: 4: workflow SampleWorkflowTest 5: { 6: param ($MyOutput) 7: 8:* Write-Output -InputObject "Now writing output:" 9: Write-Output -Input $MyOutput 10: 11: Write-Output -InputObject "Get PowerShell process:" 12: Get-Process -Name powershell 13: 14: Write-Output -InputObject "Workflow function complete." 15: } 16: 17: # Call workflow function 18: SampleWorkflowTest -MyOutput "Hello" ``` ## PARAMETERS ### -BreakAll Allows you to break immediately in the current location when the debugger attaches. This parameter was added in PowerShell 7.2. ```yaml Type: SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies the ID number of a running job. To get the ID number of a job, run the `Get-Job` cmdlet. ```yaml Type: System.Int32 Parameter Sets: JobIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InstanceId Specifies the instance ID GUID of a running job. ```yaml Type: System.Guid Parameter Sets: JobInstanceIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Job Specifies a running job object. The simplest way to use this parameter is to save the results of a `Get-Job` command that returns the running job that you want to debug in a variable, and then specify the variable as the value of this parameter. ```yaml Type: System.Management.Automation.Job Parameter Sets: JobParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Name Specifies a job by the friendly name of the job. When you start a job, you can specify a job name by adding the **JobName** parameter, in cmdlets such as `Invoke-Command` and `Start-Job`. ```yaml Type: System.String Parameter Sets: JobNameParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.RemotingJob ## OUTPUTS ## NOTES ## RELATED LINKS [Get-Job](Get-Job.md) [Receive-Job](Receive-Job.md) [Remove-Job](Remove-Job.md) [Start-Job](Start-Job.md) [Stop-Job](Stop-Job.md) [Wait-Job](Wait-Job.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Disable-ExperimentalFeature.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/04/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/disable-experimentalfeature?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Disable-ExperimentalFeature --- # Disable-ExperimentalFeature ## SYNOPSIS Disable an experimental feature on startup of new instance of PowerShell. ## SYNTAX ``` Disable-ExperimentalFeature [-Name] <String[]> [-Scope <ConfigScope>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Disable-ExperimentalFeature` cmdlet disables experimental features by removing the named experimental features from the `powershell.config.json` settings file read on PowerShell startup. This cmdlet was introduced in PowerShell 6.2. > [!NOTE] > Any changes to experimental feature state only takes effect on restart of PowerShell ## EXAMPLES ### Example 1: Disable an experimental feature In this example, if this experimental feature was previously enabled, then the `powershell.config.json` file is updated for the user to not enable that feature once PowerShell is restarted. Upon success nothing is output to the pipeline and only a warning message is displayed. ```powershell Disable-ExperimentalFeature -Name PSImplicitRemotingBatching ``` ```Output WARNING: Enabling and disabling experimental features do not take effect until next start of PowerShell. ``` ## PARAMETERS ### -Name The name or names of the experimental features to disable. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Scope Determines which `powershell.config.json` to update whether it affects all users or just the current user. ```yaml Type: System.Management.Automation.Configuration.ConfigScope Parameter Sets: (All) Aliases: Accepted values: AllUsers, CurrentUser Required: False Position: Named Default value: CurrentUser Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.ExperimentalFeature Pipe instances of ExperimentalFeature from `Get-ExperimentalFeature` cmdlet to disable. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES Changes to state of an experimental feature only take effect on restart of PowerShell. ## RELATED LINKS [Enable-ExperimentalFeature](Enable-ExperimentalFeature.md) [Get-ExperimentalFeature](Get-ExperimentalFeature.md) [about_Experimental_Features](/powershell/module/microsoft.powershell.core/about/about_experimental_features) [Using Experimental Features](/powershell/scripting/learn/experimental-features)

#File: reference/7.6/Microsoft.PowerShell.Core/Disable-PSRemoting.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 10/06/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/disable-psremoting?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Disable-PSRemoting --- # Disable-PSRemoting ## SYNOPSIS Prevents PowerShell endpoints from receiving remote connections. ## SYNTAX ``` Disable-PSRemoting [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Disable-PSRemoting` cmdlet blocks remote access to all PowerShell version 6 and greater session endpoint configurations on the local computer. It does not affect Windows PowerShell endpoint configurations. To disable Windows PowerShell session endpoint configurations, run `Disable-PSRemoting` command from within a Windows PowerShell session. To re-enable remote access to all PowerShell version 6 and greater session endpoint configurations, use the `Enable-PSRemoting` cmdlet. To re-enable remote access to all Windows PowerShell session endpoint configurations, run `Enable-PSRemoting` from within a Windows PowerShell session. > [!NOTE] > If you want to disable all PowerShell remote access to a local Windows machine, you must run this > command both from a within PowerShell version 6 or greater session and from within a Windows > PowerShell session. Windows PowerShell is installed on all Windows machines by default. To disable and re-enable remote access to specific session endpoint configurations, use the `Enable-PSSessionConfiguration` and `Disable-PSSessionConfiguration` cmdlets. To set specific access configurations of individual endpoints, use the `Set-PSSessionConfiguration` cmdlet along with the **AccessMode** parameter. For more information about session configurations, see [about_Session_Configurations](About/about_Session_Configurations.md). > [!NOTE] > Even after running `Disable-PSRemoting` you can still make loopback connections on the local > machine. A loopback connection is a PowerShell remote session that originates from and connects to > the same local machine. Remote sessions from external sources remain blocked. For loopback > connections you must use implicit credentials along the **EnableNetworkAccess** parameter. For > more information about loopback connections, see [New-PSSession](New-PSSession.md). This cmdlet is only available on the Windows platform. It is not available on Linux or macOS versions of PowerShell. To run this cmdlet, start PowerShell with the **Run as administrator** option. ## EXAMPLES ### Example 1: Prevent remote access to all PowerShell session configurations This example prevents remote access to all PowerShell session endpoint configurations on the computer. ```powershell Disable-PSRemoting ``` ```Output WARNING: 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. WARNING: 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. ``` ### Example 2: Prevent remote access to all PowerShell session configurations without confirmation prompt This example prevents remote access all PowerShell session endpoint configurations on the computer without prompting. ```powershell Disable-PSRemoting -Force ``` ```Output WARNING: 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. WARNING: 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. ``` ### Example 3: Effects of running this cmdlet This example shows the effect of using the `Disable-PSRemoting` cmdlet. To run this command sequence, start PowerShell with the **Run as administrator** option. After disabling the sessions configurations, the `New-PSSession` cmdlet attempts to create a remote session to the local computer (also known as a "loopback"). Because remote access is disabled on the local machine, the command fails. ```powershell Disable-PSRemoting -Force New-PSSession -ComputerName localhost -ConfigurationName PowerShell.6 ``` ```Output WARNING: 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. New-PSSession : [localhost] Connecting to remote server localhost failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic. At line:1 char:1 + New-PSSession -ComputerName localhost -ConfigurationName PowerShell.6 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OpenError: (System.Management.A\u2026tion.RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException + FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed ``` ### Example 4: Effects of running this cmdlet and Enable-PSRemoting This example shows the effect on the session configurations of using the `Disable-PSRemoting` and `Enable-PSRemoting` cmdlets. `Disable-PSRemoting` is used to disable remote access to all PowerShell session endpoint configurations. The **Force** parameter suppresses all user prompts. The `Get-PSSessionConfiguration` and `Format-Table` cmdlets display the session configurations on the computer. The output shows that all remote users with a network token are denied access to the endpoint configurations. Administrators group on the local computer are allowed access to the endpoint configurations as long as they are connecting locally (also known as loopback) and using implicit credentials. ```powershell Disable-PSRemoting -Force Get-PSSessionConfiguration | Format-Table -Property Name, Permission -AutoSize Enable-PSRemoting -Force Get-PSSessionConfiguration | Format-Table -Property Name, Permission -AutoSize ``` ```Output Name Permission ---- ---------- PowerShell.6 NT AUTHORITY\NETWORK AccessDenied, NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed ... PowerShell.6.2.0 NT AUTHORITY\NETWORK AccessDenied, NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed ... Name Permission ---- ---------- PowerShell.6 NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed ... PowerShell.6.2.0 NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed ... ``` The `Enable-PSRemoting` cmdlet re-enables remote access to all PowerShell session endpoint configurations on the computer. The **Force** parameter suppresses all user prompts and restarts the WinRM service without prompting. The new output shows that the **AccessDenied** security descriptors have been removed from all session configurations. ### Example 5: Loopback connections with disabled session endpoint configurations This example demonstrates how endpoint configurations are disabled, and shows how to make a successful loopback connection to a disabled endpoint. `Disable-PSRemoting` disables all PowerShell session endpoint configurations. ```powershell Disable-PSRemoting -Force ``` ```Output WARNING: 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. WARNING: 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. ``` ```powershell New-PSSession -ComputerName localhost -ConfigurationName powershell.6 -Credential (Get-Credential) ``` ```Output PowerShell credential request Enter your credentials. User: UserName Password for user UserName: ************ New-PSSession: [localhost] Connecting to remote server localhost failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic. ``` ```powershell New-PSSession -ComputerName localhost -ConfigurationName powershell.6 -EnableNetworkAccess ``` ```Output Id Name Transport ComputerName ComputerType State ConfigurationName Availability -- ---- --------- ------------ ------------ ----- ----------------- ------------ 1 Runspace1 WSMan localhost RemoteMachine Opened powershell.6 Available ``` The first use of `New-PSSession` attempts to create a remote session to the local machine. The **ConfigurationName** parameter is used to specify a disabled PowerShell endpoint. Credentials are explicitly passed to the command through the **Credential** parameter. This type of connection goes through the network stack and is not a loopback. Consequently, the connection attempt to the disabled endpoint fails with an **Access is denied** error. The second use of `New-PSSession` also attempts to create a remote session to the local machine. In this case, it succeeds because it is a loopback connection that bypasses the network stack. A loopback connection is created when the following conditions are met: - The computer name to connect to is 'localhost'. - No credentials are passed in. Current logged in user (implicit credentials) is used for the connection. - The **EnableNetworkAccess** switch parameter is used. For more information on loopback connections, see [New-PSSession](New-PSSession.md) document. ### Example 6: Disabling all PowerShell remoting endpoint configurations This example demonstrates how running the `Disable-PSRemoting` command does not affect Windows PowerShell endpoint configurations. `Get-PSSessionConfiguration` run within Windows PowerShell shows all endpoint configurations. We see that the Windows PowerShell endpoint configurations are not disabled. ```powershell Disable-PSRemoting -Force powershell.exe -Command 'Get-PSSessionConfiguration' ``` ```Output WARNING: 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. WARNING: 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. Name : microsoft.powershell PSVersion : 5.1 StartupScript : RunAsUser : Permission : NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed Name : microsoft.powershell.workflow PSVersion : 5.1 StartupScript : RunAsUser : Permission : BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed Name : microsoft.powershell32 PSVersion : 5.1 StartupScript : RunAsUser : Permission : NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed Name : PowerShell.6 PSVersion : 6.2 StartupScript : RunAsUser : Permission : NT AUTHORITY\NETWORK AccessDenied, NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed Name : PowerShell.6.2.2 PSVersion : 6.2 StartupScript : RunAsUser : Permission : NT AUTHORITY\NETWORK AccessDenied, NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed ``` ```powershell powershell.exe -Command 'Disable-PSRemoting -Force' powershell.exe -Command 'Get-PSSessionConfiguration' ``` ```Output WARNING: 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. Name : microsoft.powershell PSVersion : 5.1 StartupScript : RunAsUser : Permission : NT AUTHORITY\NETWORK AccessDenied, NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed Name : microsoft.powershell.workflow PSVersion : 5.1 StartupScript : RunAsUser : Permission : NT AUTHORITY\NETWORK AccessDenied, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed Name : microsoft.powershell32 PSVersion : 5.1 StartupScript : RunAsUser : Permission : NT AUTHORITY\NETWORK AccessDenied, NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed Name : PowerShell.6 PSVersion : 6.2 StartupScript : RunAsUser : Permission : NT AUTHORITY\NETWORK AccessDenied, NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed Name : PowerShell.6.2.2 PSVersion : 6.2 StartupScript : RunAsUser : Permission : NT AUTHORITY\NETWORK AccessDenied, NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed ``` To disable these endpoint configurations, the `Disable-PSRemoting` command must be run from within a Windows PowerShell session. Now, `Get-PSSessionConfiguration` run from within Windows PowerShell shows that all endpoint configurations are disabled. ### Example 7: Prevent remote access to session configurations that have custom security descriptors This example demonstrates that the `Disable-PSRemoting` cmdlet disables remote access to all session configurations that include session configurations with custom security descriptors. `Register-PSSessionConfiguration` creates the **Test** session configuration. The **FilePath** parameter specifies a session configuration file that customizes the session. The **ShowSecurityDescriptorUI** parameter displays a dialog box that sets permissions for the session configuration. In the Permissions dialog box, we create custom full-access permissions for the indicated user. The `Get-PSSessionConfiguration` and `Format-Table` cmdlets display the session configurations and their properties. The output shows that the **Test** session configuration allows interactive access and special permissions for the indicated user. `Disable-PSRemoting` disables remote access to all session configurations. ```powershell Register-PSSessionConfiguration -Name Test -FilePath .\TestEndpoint.pssc -ShowSecurityDescriptorUI -Force Get-PSSessionConfiguration | Format-Table -Property Name, Permission -Wrap Disable-PSRemoting -Force Get-PSSessionConfiguration | Format-Table -Property Name, Permission -Wrap New-PSSession -ComputerName localhost -ConfigurationName Test ``` ```Output Name Permission ---- ---------- PowerShell.6 NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed PowerShell.6.2.0 NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed Test NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, User01 AccessAllowed WARNING: 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. Name Permission ---- ---------- PowerShell.6 NT AUTHORITY\NETWORK AccessDenied, NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed PowerShell.6.2.0 NT AUTHORITY\NETWORK AccessDenied, NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed Test NT AUTHORITY\NETWORK AccessDenied, NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, User01 AccessAllowed New-PSSession : [localhost] Connecting to remote server localhost failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic. At line:1 char:1 + New-PSSession -ComputerName localhost -ConfigurationName Test + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OpenError: (System.Management.A\u2026tion.RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException + FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed ``` Now the `Get-PSSessionConfiguration` and `Format-Table` cmdlets shows that an **AccessDenied** security descriptor for all network users is added to all session configurations, including the **Test** session configuration. Although the other security descriptors are not changed, the "network_deny_all" security descriptor takes precedence. This is illustrated by the attempt to use `New-PSSession` to connect to the **Test** session configuration. ### Example 8: Re-enable remote access to selected session configurations This example shows how to re-enable remote access only to selected session configurations. After disabling all session configurations, we re-enable a specific session. The `Set-PSSessionConfiguration` cmdlet is used to change the **PowerShell.6** session configuration. The **AccessMode** parameter with a value of **Remote** re-enables remote access to the configuration. ```powershell Disable-PSRemoting -Force Get-PSSessionConfiguration | Format-Table -Property Name, Permission -AutoSize Set-PSSessionConfiguration -Name PowerShell.6 -AccessMode Remote -Force Get-PSSessionConfiguration | Format-Table -Property Name, Permission -AutoSize ``` ```Output WARNING: 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. Name Permission ---- ---------- PowerShell.6 NT AUTHORITY\NETWORK AccessDenied, NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Adm ... PowerShell.6.2.0 NT AUTHORITY\NETWORK AccessDenied, NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Adm ... Name Permission ---- ---------- PowerShell.6 NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\ ... PowerShell.6.2.0 NT AUTHORITY\NETWORK AccessDenied, NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Adm ... ``` ## PARAMETERS ### -Force Forces the command to run without asking for user confirmation. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES This cmdlet is only available on Windows platforms. - Disabling the session configurations does not undo all the changes that were made by the `Enable-PSRemoting` or `Enable-PSSessionConfiguration` cmdlets. You might have to undo the following changes manually. 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. - A session endpoint configuration is a group of settings that define the environment for a session. Every session that connects to the computer must use one of the session endpoint configurations that are registered on the computer. By denying remote access to all session endpoint configurations, you effectively prevent remote users from establishing sessions that connect to the computer. ## RELATED LINKS [Disable-PSSessionConfiguration](Disable-PSSessionConfiguration.md) [Enable-PSRemoting](Enable-PSRemoting.md) [Get-PSSessionConfiguration](Get-PSSessionConfiguration.md) [New-PSSession](New-PSSession.md) [Register-PSSessionConfiguration](Register-PSSessionConfiguration.md) [Set-PSSessionConfiguration](Set-PSSessionConfiguration.md) [Unregister-PSSessionConfiguration](Unregister-PSSessionConfiguration.md) [WSMan Provider](../Microsoft.WsMan.Management/About/about_WSMan_Provider.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Disable-PSSessionConfiguration.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/disable-pssessionconfiguration?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Disable-PSSessionConfiguration --- # Disable-PSSessionConfiguration ## SYNOPSIS Disables session configurations on the local computer. ## SYNTAX ``` Disable-PSSessionConfiguration [[-Name] <String[]>] [-Force] [-NoServiceRestart] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Disable-PSSessionConfiguration` cmdlet disables session configurations on the local computer, which prevents all users from using the session configurations to create a user-managed sessions (**PSSessions**) on the local computer. This is an advanced cmdlet that is designed to be used by system administrators to manage customized session configurations for their users. Starting in PowerShell 3.0, the `Disable-PSSessionConfiguration` cmdlet sets the **Enabled** setting of the session configuration (`WSMan:\localhost\Plugins\<SessionConfiguration>\Enabled`) to False. In PowerShell 2.0, the `Disable-PSSessionConfiguration` cmdlet adds a **Deny_All** entry to the security descriptor of one or more registered session configurations. Without parameters, `Disable-PSSessionConfiguration` disables the **Microsoft.PowerShell** configuration, the default configuration used for sessions. Unless the user specifies a different configuration, both local and remote users are effectively prevented from creating any sessions that connect to the computer. To disable all session configurations on the computer, use `Disable-PSRemoting`. ## EXAMPLES ### Example 1: Disable the default configuration This example disables the **Microsoft.PowerShell** session configuration. ```powershell Disable-PSSessionConfiguration ``` ### Example 2: Disable all registered session configurations This example disables all registered session configurations on the computer. ```powershell Disable-PSSessionConfiguration -Name * ``` ### Example 3: Disable session configurations by name This example disables all session configurations that have names that begin with `Microsoft`. The **Force** parameter suppresses all user prompts from the cmdlet. ```powershell Disable-PSSessionConfiguration -Name Microsoft* -Force ``` ### Example 4: Disable session configurations by using the pipeline This example disables the **MaintenanceShell** and **AdminShell** session configurations. The pipeline operator (`|`) sends the results of a `Get-PSSessionConfiguration` to `Disable-PSSessionConfiguration`. ```powershell Get-PSSessionConfiguration -Name MaintenanceShell, AdminShell | Disable-PSSessionConfiguration ``` ### Example 5: Effects of disabling a session configuration This example shows the permissions before and after running `Disable-PSSessionConfiguration` and the effect of disabling a session configuration. ``` PS> Get-PSSessionConfiguration | Format-Table -Property Name, Permission -Auto Name Permission ---- ---------- MaintenanceShell BUILTIN\Administrators AccessAllowed microsoft.powershell BUILTIN\Administrators AccessAllowed microsoft.powershell32 BUILTIN\Administrators AccessAllowed PS> Disable-PSSessionConfiguration -Name MaintenanceShell -Force PS> Get-PSSessionConfiguration | Format-Table -Property Name, Permission -Auto Name Permission ---- ---------- MaintenanceShell Everyone AccessDenied, BUILTIN\Administrators AccessAllowed microsoft.powershell BUILTIN\Administrators AccessAllowed microsoft.powershell32 BUILTIN\Administrators AccessAllowed PS> New-PSSession -ComputerName localhost -ConfigurationName MaintenanceShell [localhost] Connecting to remote server failed with the following error message : Access is denied. For more information, see the about_Remote_Troubleshooting Help topic. + CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException + FullyQualifiedErrorId : PSSessionOpenFailed ``` > [!NOTE] > Disabling the configuration does not prevent you from changing the configuration using the > `Set-PSSessionConfiguration` cmdlet. It only prevents use of the configuration. ## PARAMETERS ### -Force Forces the command to run without asking for user confirmation. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies an array of names of session configurations to disable. Enter one or more configuration names. Wildcard characters are permitted. You can also pipe a string that contains a configuration name or a session configuration object to `Disable-PSSessionConfiguration`. If you omit this parameter, `Disable-PSSessionConfiguration` disables the **Microsoft.PowerShell** session configuration. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -NoServiceRestart Used to prevent the restart of the WSMan service. It is not necessary to restart the service to disable the configuration. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#PSSessionConfiguration You can pipe a session configuration object to this cmdlet. ### System.String You can pipe a string that contains the name of a session configuration to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES This cmdlet is only available on Windows platforms. To run this cmdlet you must start PowerShell by using the **Run as administrator** option. ## RELATED LINKS [Enable-PSSessionConfiguration](Enable-PSSessionConfiguration.md) [Get-PSSessionConfiguration](Get-PSSessionConfiguration.md) [New-PSSessionConfigurationFile](New-PSSessionConfigurationFile.md) [Register-PSSessionConfiguration](Register-PSSessionConfiguration.md) [Set-PSSessionConfiguration](Set-PSSessionConfiguration.md) [Test-PSSessionConfigurationFile](Test-PSSessionConfigurationFile.md) [Unregister-PSSessionConfiguration](Unregister-PSSessionConfiguration.md) [WSMan Provider](../Microsoft.WsMan.Management/About/about_WSMan_Provider.md) [about_Session_Configurations](About/about_Session_Configurations.md) [about_Session_Configuration_Files](About/about_Session_Configuration_Files.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Disconnect-PSSession.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/disconnect-pssession?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Disconnect-PSSession --- # Disconnect-PSSession ## SYNOPSIS Disconnects from a session. ## SYNTAX ### Session (Default) ``` Disconnect-PSSession [-Session] <PSSession[]> [-IdleTimeoutSec <Int32>] [-OutputBufferingMode <OutputBufferingMode>] [-ThrottleLimit <Int32>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Name ``` Disconnect-PSSession [-IdleTimeoutSec <Int32>] [-OutputBufferingMode <OutputBufferingMode>] [-ThrottleLimit <Int32>] -Name <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### InstanceId ``` Disconnect-PSSession [-IdleTimeoutSec <Int32>] [-OutputBufferingMode <OutputBufferingMode>] [-ThrottleLimit <Int32>] -InstanceId <Guid[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Id ``` Disconnect-PSSession [-IdleTimeoutSec <Int32>] [-OutputBufferingMode <OutputBufferingMode>] [-ThrottleLimit <Int32>] [-Id] <Int32[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Disconnect-PSSession` cmdlet disconnects a PowerShell session (**PSSession**), such as one started by using the `New-PSSession` cmdlet, from the current session. As a result, the **PSSession** is in a disconnected state. You can connect to the disconnected **PSSession** from the current session or from another session on the local computer or a different computer. The `Disconnect-PSSession` cmdlet disconnects only open **PSSessions** that are connected to the current session. `Disconnect-PSSession` cannot disconnect broken or closed **PSSessions**, or interactive **PSSessions** started by using the `Enter-PSSession` cmdlet, and it cannot disconnect **PSSessions** that are connected to other sessions. To reconnect to a disconnected **PSSession**, use the `Connect-PSSession` or `Receive-PSSession` cmdlets. When a **PSSession** is disconnected, the commands in the **PSSession** continue to run until they complete, unless the **PSSession** times out or the commands in the **PSSession** are blocked by a full output buffer. To change the idle timeout, use the **IdleTimeoutSec** parameter. To change the output buffering mode, use the **OutputBufferingMode** parameter You can also use the **InDisconnectedSession** parameter of the `Invoke-Command` cmdlet to run a command in a disconnected session. For more information about the Disconnected Sessions feature, see [about_Remote_Disconnected_Sessions](./About/about_Remote_Disconnected_Sessions.md). This cmdlet is introduced in Windows PowerShell 3.0. ## EXAMPLES ### Example 1 - Disconnect a session by name This command disconnects the `UpdateSession` **PSSession** on the Server01 computer from the current session. The command uses the **Name** parameter to identify the **PSSession**. ``` PS> Disconnect-PSSession -Name UpdateSession Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 UpdateSession Server01 Disconnected Microsoft.PowerShell None ``` The output shows that the attempt to disconnect was successful. The session state is `Disconnected` and the **Availability** is `None`, which indicates that the session is not busy and can be reconnected. ### Example 2 - Disconnect a session from a specific computer This command disconnects the `ITTask` **PSSession** on the Server12 computer from the current session. The `ITTask` session was created in the current session and connects to the Server12 computer. The command uses the `Get-PSSession` cmdlet to get the session and the `Disconnect-PSSession` cmdlet to disconnect it. ``` PS> Get-PSSession -ComputerName Server12 -Name ITTask | Disconnect-PSSession -OutputBufferingMode Drop -IdleTimeoutSec 86400 Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 ITTask Server12 Disconnected ITTasks None ``` The `Disconnect-PSSession` command uses the **OutputBufferingMode** parameter to set the output mode to `Drop`. This setting ensures that the script that is running in the session can continue to run even if the session output buffer is full. Because the script writes its output to a report on a file share, other output can be lost without consequence. The command also uses the **IdleTimeoutSec** parameter to extend the idle timeout of the session to 24 hours. This setting allows time for this administrator or other administrators to reconnect to the session to verify that the script ran and troubleshoot if needed. ### Example 3 - Using multiple PSSessions on multiple computers This series of commands shows how the `Disconnect-PSSession` cmdlet might be used in an enterprise scenario. In this case, a new technician starts a script in a session on a remote computer and runs into a problem. The technician disconnects from the session so that a more experienced manager can connect to the session and resolve the problem. ``` PS> $s = New-PSSession -ComputerName Srv1, Srv2, Srv30 -Name ITTask PS> Invoke-Command $s -FilePath \\Server01\Scripts\Get-PatchStatus.ps1 PS> Get-PSSession -Name ITTask -ComputerName Srv1 | Disconnect-PSSession Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 ITTask Srv1 Disconnected Microsoft.PowerShell None PS> Get-PSSession -ComputerName Srv1, Srv2, Srv30 -Name ITTask Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 ITTask Srv1 Disconnected Microsoft.PowerShell None 2 ITTask Srv2 Opened Microsoft.PowerShell Available 3 ITTask Srv30 Opened Microsoft.PowerShell Available PS> Get-PSSession -ComputerName Srv1 -Name ITTask -Credential Domain01\User01 Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 ITTask Srv1 Disconnected Microsoft.PowerShell None PS> $s = Connect-PSSession -ComputerName Srv1 -Name ITTask -Credential Domain01\User01 PS> Invoke-Command -Session $s {dir $HOME\Scripts\PatchStatusOutput.ps1} PS> Invoke-Command -Session $s {mkdir $HOME\Scripts\PatchStatusOutput} PS> Invoke-Command -Session $s -FilePath \\Server01\Scripts\Get-PatchStatus.ps1 PS> Disconnect-PSSession -Session $s ``` The technician begins by creating sessions on several remote computers and running a script in each session. The first command uses the `New-PSSession` cmdlet to create the `ITTask` session on three remote computers. The command saves the sessions in the `$s` variable. The second command uses the **FilePath** parameter of the `Invoke-Command` cmdlet to run a script in the sessions in the `$s` variable. The script running on the Srv1 computer generates unexpected errors. The technician contacts his manager and asks for assistance. The manager directs the technician to disconnect from the session so he can investigate.The second command uses the `Get-PSSession` cmdlet to get the `ITTask` session on the Srv1 computer and the `Disconnect-PSSession` cmdlet to disconnect it. This command does not affect the `ITTask` sessions on the other computers. The third command uses the `Get-PSSession` cmdlet to get the `ITTask` sessions. The output shows that the `ITTask` sessions on the Srv2 and Srv30 computers were not affected by the command to disconnect. The manager logs on to his home computer, connects to his corporate network, starts PowerShell, and uses the `Get-PSSession` cmdlet to get the `ITTask` session on the Srv1 computer. He uses the credentials of the technician to access the session. Next, the manager uses the `Connect-PSSession` cmdlet to connect to the `ITTask` session on the Srv1 computer. The command saves the session in the `$s` variable. The manager uses the `Invoke-Command` cmdlet to run some diagnostic commands in the session in the `$s` variable. He recognizes that the script failed because it did not find a required directory. The manager uses the `MkDir` function to create the directory, and then he restarts the `Get-PatchStatus.ps1` script and disconnects from the session.The manager reports his findings to the technician, suggests that he reconnect to the session to complete the tasks, and asks him to add a command to the `Get-PatchStatus.ps1` script that creates the required directory if it does not exist. ### Example 4 - Change the timeout value for a PSSession This example shows how to correct the value of the **IdleTimeout** property of a session so that it can be disconnected. The idle timeout property of a session is critical to disconnected sessions, because it determines how long a disconnected session is maintained before it is deleted. You can set the idle timeout option when you create a session and when you disconnect it. The default values for the idle timeout of a session are set in the `$PSSessionOption` preference variable on the local computer and in the session configuration on the remote computer. Values set for the session take precedence over values set in the session configuration, but session values cannot exceed quotas set in the session configuration, such as the **MaxIdleTimeoutMs** value. ``` PS> $Timeout = New-PSSessionOption -IdleTimeout 172800000 PS> $s = New-PSSession -Computer Server01 -Name ITTask -SessionOption $Timeout PS> Disconnect-PSSession -Session $s Disconnect-PSSession : The session ITTask cannot be disconnected because the specified idle timeout value 172800(seconds) is either greater than the server maximum allowed 43200 (seconds) or less that the minimum allowed60(seconds). Choose an idle time out value that is within the allowed range and try again. PS> Invoke-Command -ComputerName Server01 {Get-PSSessionConfiguration Microsoft.PowerShell} | Format-List -Property * Architecture : 64 Filename : %windir%\system32\pwrshplugin.dll ResourceUri : http://schemas.microsoft.com/powershell/microsoft.powershell MaxConcurrentCommandsPerShell : 1000 UseSharedProcess : false ProcessIdleTimeoutSec : 0 xmlns : http://schemas.microsoft.com/wbem/wsman/1/config/PluginConfiguration MaxConcurrentUsers : 5 lang : en-US SupportsOptions : true ExactMatch : true RunAsUser : IdleTimeoutms : 7200000 PSVersion : 3.0 OutputBufferingMode : Block AutoRestart : false SecurityDescriptorSddl : O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;SA;GXGW;;;WD) MaxMemoryPerShellMB : 1024 MaxIdleTimeoutMs : 2147483647 Uri : http://schemas.microsoft.com/powershell/microsoft.powershell SDKVersion : 2 Name : microsoft.powershell XmlRenderingType : text Capability : {Shell} RunAsPassword : MaxProcessesPerShell : 15 ParentResourceUri : http://schemas.microsoft.com/powershell/microsoft.powershell Enabled : true MaxShells : 25 MaxShellsPerUser : 25 Permission : BUILTIN\Administrators AccessAllowed PSComputerName : localhost RunspaceId : aea84310-6dbf-4c21-90ac-13980039925a PSShowComputerName : True PS> $s.Runspace.ConnectionInfo ConnectionUri : http://Server01/wsman ComputerName : Server01 Scheme : http Port : 80 AppName : /wsman Credential : ShellUri : http://schemas.microsoft.com/powershell/Microsoft.PowerShell AuthenticationMechanism : Default CertificateThumbprint : MaximumConnectionRedirectionCount : 5 MaximumReceivedDataSizePerCommand : MaximumReceivedObjectSize : 209715200 UseCompression : True NoMachineProfile : False ProxyAccessType : None ProxyAuthentication : Negotiate ProxyCredential : SkipCACheck : False SkipCNCheck : False SkipRevocationCheck : False NoEncryption : False UseUTF16 : False OutputBufferingMode : Drop IncludePortInSPN : False Culture : en-US UICulture : en-US OpenTimeout : 180000 CancelTimeout : 60000 OperationTimeout : 180000 IdleTimeout : 172800000 PS> Disconnect-PSSession $s -IdleTimeoutSec 43200 Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 4 ITTask Server01 Disconnected Microsoft.PowerShell None PS> $s.Runspace.ConnectionInfo.IdleTimeout 43200000 ``` The first command uses the `New-PSSessionOption` cmdlet to create a session option object. It uses the **IdleTimeout** parameter to set an idle timeout of 48 hours (`172800000` milliseconds). The command saves the session option object in the `$Timeout` variable. The second command uses the `New-PSSession` cmdlet to create the `ITTask` session on the Server01 computer. The command save the session in the `$s` variable. The value of the **SessionOption** parameter is the 48-hour idle timeout in the `$Timeout` variable. The third command disconnects the `ITTask` session in the `$s` variable. The command fails because the idle timeout value of the session exceeds the **MaxIdleTimeoutMs** quota in the session configuration. Because the idle timeout is not used until the session is disconnected, this violation can go undetected while the session is in use. The fourth command uses the `Invoke-Command` cmdlet to run a `Get-PSSessionConfiguration` command for the `Microsoft.PowerShell` session configuration on the Server01 computer. The command uses the `Format-List` cmdlet to display all properties of the session configuration in a list.The output shows that the **MaxIdleTimeoutMs** property, which establishes the maximum permitted **IdleTimeout** value for sessions that use the session configuration, is `43200000` milliseconds (12 hours). The fifth command gets the session option values of the session in the `$s` variable. The values of many session options are properties of the **ConnectionInfo** property of the **Runspace** property of the session.The output shows that the value of the **IdleTimeout** property of the session is `172800000` milliseconds (48 hours), which violates the **MaxIdleTimeoutMs** quota of 12 hours in the session configuration.To resolve this conflict, you can use the **ConfigurationName** parameter to select a different session configuration or use the **IdleTimeout** parameter to reduce the idle timeout of the session. The sixth command disconnects the session. It uses the **IdleTimeoutSec** parameter to set the idle timeout to the 12-hour maximum. The seventh command gets the value of the **IdleTimeout** property of the disconnected session, which is measured in milliseconds. The output confirms that the command was successful. ## PARAMETERS ### -Id Disconnects from sessions with the specified session ID. Type one or more IDs (separated by commas), or use the range operator (`..`) to specify a range of IDs. To get the ID of a session, use the `Get-PSSession` cmdlet. The instance ID is stored in the **Id** property of the session. ```yaml Type: System.Int32[] Parameter Sets: Id Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -IdleTimeoutSec Changes the idle timeout value of the disconnected **PSSession**. Enter a value in seconds. The minimum value is `60` (1 minute). The idle timeout determines how long the disconnected **PSSession** is maintained on the remote computer. When the timeout expires, the **PSSession** is deleted. Disconnected **PSSessions** are considered to be idle from the moment that they are disconnected, even if commands are running in the disconnected session. The default value for the idle timeout of a session is set by the value of the **IdleTimeoutMs** property of the session configuration. The default value is `7200000` milliseconds (2 hours). The value of this parameter takes precedence over the value of the **IdleTimeout** property of the `$PSSessionOption` preference variable and the default idle timeout value in the session configuration. However, this value cannot exceed the value of the **MaxIdleTimeoutMs** property of the session configuration. The default value of **MaxIdleTimeoutMs** is 12 hours (`43200000` milliseconds). ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 60 Accept pipeline input: False Accept wildcard characters: False ``` ### -InstanceId Disconnects from sessions with the specified instance IDs. The instance ID is a GUID that uniquely identifies a session on a local or remote computer. The instance ID is unique, even across multiple sessions on multiple computers. To get the instance ID of a session, use the `Get-PSSession` cmdlet. The instance ID is stored in the **InstanceId** property of the session. ```yaml Type: System.Guid[] Parameter Sets: InstanceId Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Disconnects from sessions with the specified friendly names. Wildcards are permitted. To get the friendly name of a session, use the `Get-PSSession` cmdlet. The friendly name is stored in the **Name** property of the session. ```yaml Type: System.String[] Parameter Sets: Name Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -OutputBufferingMode Determines how command output is managed in the disconnected session when the output buffer is full. The default value is `Block`. If the command in the disconnected session is returning output and the output buffer fills, the value of this parameter effectively determines whether the command continues to run while the session is disconnected. A value of `Block` suspends the command until the session is reconnected. A value of `Drop` allows the command to complete, although data might be lost. When using the `Drop` value, redirect the command output to a file on disk. Valid values are: - `Block`: When the output buffer is full, execution is suspended until the buffer is clear. - `Drop`: When the output buffer is full, execution continues. As new output is saved, the oldest output is discarded. - `None`: No output buffering mode is specified. The value of the **OutputBufferingMode** property of the session configuration is used for the disconnected session. ```yaml Type: System.Management.Automation.Runspaces.OutputBufferingMode Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Block Accept pipeline input: False Accept wildcard characters: False ``` ### -Session Disconnects from the specified **PSSessions**. Enter **PSSession** objects, such as those that the `New-PSSession` cmdlet returns. You can also pipe a **PSSession** object to `Disconnect-PSSession`. The `Get-PSSession` cmdlet can get all **PSSessions** that terminate at a remote computer, including **PSSessions** that are disconnected and **PSSessions** that are connected to other sessions on other computers. `Disconnect-PSSession` disconnects only **PSSession** that are connected to the current session. If you pipe other **PSSessions** to `Disconnect-PSSession`, the `Disconnect-PSSession` command fails. ```yaml Type: System.Management.Automation.Runspaces.PSSession[] Parameter Sets: Session Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -ThrottleLimit Sets the throttle limit for the `Disconnect-PSSession` command. The throttle limit is the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of `0`, the default value, `32`, is used. The throttle limit applies only to the current command, not to the session or to the computer. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 32 Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](./About/about_CommonParameters.md). ## INPUTS ### System.Management.Automation.Runspaces.PSSession You can pipe a session to this cmdlet. ## OUTPUTS ### System.Management.Automation.Runspaces.PSSession This cmdlet returns an object representing the session that it disconnected. ## NOTES PowerShell includes the following aliases for `Disconnect-PSSession`: - Windows: - `dnsn` This cmdlet is only available on Windows platforms. - The `Disconnect-PSSession` cmdlet works only when the local and remote computers are running PowerShell 3.0 or later. - If you use the `Disconnect-PSSession` cmdlet on a disconnected session, the command has no effect on the session and it does not generate errors. - Disconnected loopback sessions with interactive security tokens (those created with the **EnableNetworkAccess** parameter) can be reconnected only from the computer on which the session was created. This restriction protects the computer from malicious access. - When you disconnect a **PSSession**, the session state is `Disconnected` and the availability is **None**. The value of the **State** property is relative to the current session. Therefore, a value of `Disconnected` means that the **PSSession** is not connected to the current session. However, it does not mean that the **PSSession** is disconnected from all sessions. It might be connected to a different session. To determine whether you can connect or reconnect to the session, use the **Availability** property. An **Availability** value of `None` indicates that you can connect to the session. A value of `Busy` indicates that you cannot connect to the **PSSession** because it is connected to another session. For more information about the values of the **State** property of sessions, see [RunspaceState Enumeration](/dotnet/api/system.management.automation.runspaces.runspacestate). For more information about the values of the **Availability** property of sessions, see [RunspaceAvailability Enumeration](/dotnet/api/system.management.automation.runspaces.runspaceavailability). ## RELATED LINKS [Connect-PSSession](Connect-PSSession.md) [Enter-PSSession](Enter-PSSession.md) [Exit-PSSession](Exit-PSSession.md) [Get-PSSession](Get-PSSession.md) [Get-PSSessionConfiguration](Get-PSSessionConfiguration.md) [New-PSSession](New-PSSession.md) [New-PSSessionOption](New-PSSessionOption.md) [New-PSTransportOption](New-PSTransportOption.md) [Receive-PSSession](Receive-PSSession.md) [Register-PSSessionConfiguration](Register-PSSessionConfiguration.md) [Remove-PSSession](Remove-PSSession.md) [about_PSSessions](About/about_PSSessions.md) [about_Remote](About/about_Remote.md) [about_Remote_Disconnected_Sessions](About/about_Remote_Disconnected_Sessions.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Enable-ExperimentalFeature.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/04/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/enable-experimentalfeature?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Enable-ExperimentalFeature --- # Enable-ExperimentalFeature ## SYNOPSIS Enable an experimental feature on startup of new instance of PowerShell. ## SYNTAX ``` Enable-ExperimentalFeature [-Name] <String[]> [-Scope <ConfigScope>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Enable-ExperimentalFeature` cmdlet enables experimental features by adding the named experimental features to the `powershell.config.json` settings file read on PowerShell startup. This cmdlet was introduced in PowerShell 6.2. > [!NOTE] > Any changes to experimental feature state only takes effect on restart of PowerShell ## EXAMPLES ### Example 1: Enable an experimental feature In this example, if this experimental feature was previously disabled, then the `powershell.config.json` file is updated for the user to enable that feature once PowerShell is restarted. Upon success nothing is output to the pipeline and only a warning message is displayed. ```powershell Enable-ExperimentalFeature PSImplicitRemotingBatching ``` ```Output WARNING: Enabling and disabling experimental features do not take effect until next start of PowerShell. ``` ## PARAMETERS ### -Name The name or names of the experimental features to enable. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Scope Determines which `powershell.config.json` to update whether it affects all users or just the current user. ```yaml Type: System.Management.Automation.Configuration.ConfigScope Parameter Sets: (All) Aliases: Accepted values: AllUsers, CurrentUser Required: False Position: Named Default value: CurrentUser Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.ExperimentalFeature Pipe instances of ExperimentalFeature from `Get-ExperimentalFeature` cmdlet to enable. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES Changes to state of an experimental feature only take effect on restart of PowerShell. ## RELATED LINKS [Disable-ExperimentalFeature](Disable-ExperimentalFeature.md) [Get-ExperimentalFeature](Get-ExperimentalFeature.md) [about_Experimental_Features](/powershell/module/microsoft.powershell.core/about/about_experimental_features) [Using Experimental Features](/powershell/scripting/learn/experimental-features)

#File: reference/7.6/Microsoft.PowerShell.Core/Enable-PSRemoting.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 11/25/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/enable-psremoting?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Enable-PSRemoting --- # Enable-PSRemoting ## SYNOPSIS Configures the computer to receive remote commands. ## SYNTAX ``` Enable-PSRemoting [-Force] [-SkipNetworkProfileCheck] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Enable-PSRemoting` cmdlet configures the computer to receive PowerShell remote commands that are sent by using the WS-Management technology. WS-Management based PowerShell remoting is currently supported only on Windows platform. PowerShell remoting is enabled by default on Windows Server platforms. You can use `Enable-PSRemoting` to enable PowerShell remoting on other supported versions of Windows and to re-enable remoting if it becomes disabled. You need to run this command only one time on each computer that receive commands. You don't need to run it on computers that only send commands. Because the configuration starts listeners, it's prudent to run it only where it's needed. Enabling PowerShell remoting on client versions of Windows when the computer is on a public network is normally disallowed, but you can skip this restriction by using the **SkipNetworkProfileCheck** parameter. For more information, see the description of the **SkipNetworkProfileCheck** parameter. Multiple PowerShell installations can exist side-by-side on a single computer. Running `Enable-PSRemoting` will configure a remoting endpoint for the specific installation version that you are running the cmdlet in. So if you run `Enable-PSRemoting` while running PowerShell 6.2, a remoting endpoint will be configured that runs PowerShell 6.2. If you run `Enable-PSRemoting` while running PowerShell 7-preview, a remoting endpoint will be configured that runs PowerShell 7-preview. `Enable-PSRemoting` creates two remoting endpoint configurations as needed. If the endpoint configurations already exist, then they are simply ensured to be enabled. The created configurations are identical but have different names. One will have a simple name corresponding to the PowerShell version that hosts the session. The other configuration name contains more detailed information about the PowerShell version which hosts the session. For example, when running `Enable-PSRemoting` in PowerShell 6.2, you will get two configured endpoints named **PowerShell.6**, **PowerShell.6.2.2**. This allows you to create a connection to the latest PowerShell 6 host version by using the simple name **PowerShell.6**. Or you can connect to a specific PowerShell host version by using the longer name **PowerShell.6.2.2**. To use the newly enabled remoting endpoints, you must specify them by name with the **ConfigurationName** parameter when creating a remote connection using the `Invoke-Command`,`New-PSSession`,`Enter-PSSession` cmdlets. For more information, see Example 4. The `Enable-PSRemoting` cmdlet performs the following operations: - Runs the [Set-WSManQuickConfig](../Microsoft.WSMan.Management/Set-WSManQuickConfig.md) cmdlet, which performs the following tasks: - Starts the WinRM service. - Sets the startup type on the WinRM service to Automatic. - Creates a listener to accept requests on any IP address. - Enables a firewall exception for WS-Management communications. - Creates the simple and long name session endpoint configurations if needed. - Enables all session configurations. - Changes the security descriptor of all session configurations to allow remote access. - Restarts the WinRM service to make the preceding changes effective. To run this cmdlet on the Windows platform, start PowerShell by using the Run as administrator option. This cmdlet is not available on Linux or macOS versions of PowerShell. > [!CAUTION] > This cmdlet does not affect remote endpoint configurations created by Windows PowerShell. > It only affects endpoints created with PowerShell version 6 and greater. To enable and > disable PowerShell remoting endpoints that are hosted by Windows PowerShell, run the > `Enable-PSRemoting` cmdlet from within a Windows PowerShell session. For more information about using PowerShell remoting, see the following articles: - [about_Remote_Requirements](about/about_Remote_Requirements.md) - [about_Remote](about/about_Remote.md) ## EXAMPLES ### Example 1: Configure a computer to receive remote commands This command configures the computer to receive remote commands. ```powershell Enable-PSRemoting ``` ```Output WARNING: PowerShell remoting has been enabled only for PowerShell Core configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. ``` ### Example 2: Configure a computer to receive remote commands without a confirmation prompt This command configures the computer to receive remote commands. The **Force** parameter suppresses the user prompts. ```powershell Enable-PSRemoting -Force ``` ```Output WARNING: PowerShell remoting has been enabled only for PowerShell Core configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. ``` ### Example 3: Allow remote access on clients This example shows how to allow remote access from public networks on client versions of the Windows operating system. The name of the firewall rule can be different for different versions of Windows. Use `Get-NetFirewallRule` to see a list of rules. Before enabling the firewall rule, view the security settings in the rule to verify that the configuration is appropriate for your environment. ```powershell Get-NetFirewallRule -Name 'WINRM*' | Select-Object -Property Name ``` ```Output Name ---- WINRM-HTTP-In-TCP-NoScope WINRM-HTTP-In-TCP WINRM-HTTP-Compat-In-TCP-NoScope WINRM-HTTP-Compat-In-TCP ``` ```powershell Enable-PSRemoting -SkipNetworkProfileCheck -Force Set-NetFirewallRule -Name 'WINRM-HTTP-In-TCP' -RemoteAddress Any ``` By default, `Enable-PSRemoting` creates network rules that allow remote access from private and domain networks. The command uses the **SkipNetworkProfileCheck** parameter to allow remote access from public networks in the same local subnet. The command specifies the **Force** parameter to suppress confirmation messages. The **SkipNetworkProfileCheck** parameter does not affect server versions of the Windows operating system, which allow remote access from public networks in the same local subnet by default. The `Set-NetFirewallRule` cmdlet in the **NetSecurity** module adds a firewall rule that allows remote access from public networks from any remote location. This includes locations in different subnets. ### Example 4: Create a remote session to the newly enabled endpoint configuration This example shows how to enable PowerShell remoting on a computer, find the configured endpoint names, and create a remote session to one of the endpoints. The first command enables PowerShell remoting on the computer. The second command lists the endpoint configurations. The third command creates a remote PowerShell session to the same machine, specifying the **PowerShell.7** endpoint by name. The remote session will be hosted with the latest PowerShell 7 version (7.3.0). The last command accesses the `$PSVersionTable` variable in the remote session to display the PowerShell version that is hosting the session. ```powershell Enable-PSRemoting -Force Get-PSSessionConfiguration $session = New-PSSession -ComputerName localhost -ConfigurationName PowerShell.7 Invoke-Command -Session $session -ScriptBlock { $PSVersionTable } ``` ```Output WARNING: PowerShell remoting has been enabled only for PowerShell Core configurations and does not affect Windows PowerShell remoting configurations. Run this cmdlet in Windows PowerShell to affect all PowerShell remoting configurations. Name : PowerShell.7 PSVersion : 7.3 StartupScript : RunAsUser : Permission : NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed Name : PowerShell.7.3.0 PSVersion : 7.3 StartupScript : RunAsUser : Permission : NT AUTHORITY\INTERACTIVE AccessAllowed, BUILTIN\Administrators AccessAllowed, BUILTIN\Remote Management Users AccessAllowed Name Value ---- ----- PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…} PSEdition Core PSRemotingProtocolVersion 2.3 Platform Win32NT SerializationVersion 1.1.0.1 GitCommitId 6.2.2 WSManStackVersion 3.0 PSVersion 6.2.2 OS Microsoft Windows 10.0.18363 ``` > [!NOTE] > The name of the firewall rule can be different depending on the version of Windows. Use the > `Get-NetFirewallRule` cmdlet to list the names of the rules on your system. ## PARAMETERS ### -Force Forces the command to run without asking for user confirmation. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipNetworkProfileCheck Indicates that this cmdlet enables remoting on client versions of the Windows operating system when the computer is on a public network. This parameter enables a firewall rule for public networks that allows remote access only from computers in the same local subnet. This parameter doesn't affect server versions of the Windows operating system, which, by default, have a local subnet firewall rule for public networks. If the local subnet firewall rule is disabled on a server version, `Enable-PSRemoting` re-enables it, regardless of the value of this parameter. To remove the local subnet restriction and enable remote access from all locations on public networks, use the `Set-NetFirewallRule` cmdlet in the **NetSecurity** module. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns strings that describe its results. ## NOTES This cmdlet is only available on Windows platforms. On server versions of the Windows operating system, `Enable-PSRemoting` creates firewall rules for private and domain networks that allow remote access, and creates a firewall rule for public networks that allows remote access only from computers in the same local subnet. On client versions of the Windows operating system, `Enable-PSRemoting` creates firewall rules for private and domain networks that allow unrestricted remote access. To create a firewall rule for public networks that allows remote access from the same local subnet, use the **SkipNetworkProfileCheck** parameter. On client or server versions of the Windows operating system, to create a firewall rule for public networks that removes the local subnet restriction and allows remote access , use the `Set-NetFirewallRule` cmdlet in the NetSecurity module to run the following command: `Set-NetFirewallRule -Name "WINRM-HTTP-In-TCP-PUBLIC" -RemoteAddress Any` `Enable-PSRemoting` enables all session configurations by setting the value of the **Enabled** property of all session configurations to `$true`. `Enable-PSRemoting` removes the **Deny_All** and **Network_Deny_All** settings. This provides remote access to session configurations that were reserved for local use. ## RELATED LINKS [Disable-PSSessionConfiguration](Disable-PSSessionConfiguration.md) [Enable-PSSessionConfiguration](Enable-PSSessionConfiguration.md) [Get-PSSessionConfiguration](Get-PSSessionConfiguration.md) [Register-PSSessionConfiguration](Register-PSSessionConfiguration.md) [Set-PSSessionConfiguration](Set-PSSessionConfiguration.md) [Disable-PSRemoting](Disable-PSRemoting.md) [WSMan Provider](../Microsoft.WsMan.Management/About/about_WSMan_Provider.md) [about_Remote](About/about_Remote.md) [about_Session_Configurations](About/about_Session_Configurations.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Enable-PSSessionConfiguration.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/enable-pssessionconfiguration?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Enable-PSSessionConfiguration --- # Enable-PSSessionConfiguration ## SYNOPSIS Enables the session configurations on the local computer. ## SYNTAX ``` Enable-PSSessionConfiguration [[-Name] <String[]>] [-Force] [-SecurityDescriptorSddl <String>] [-SkipNetworkProfileCheck] [-NoServiceRestart] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Enable-PSSessionConfiguration` cmdlet enables registered session configurations that have been disabled, such as by using the `Disable-PSSessionConfiguration` or `Disable-PSRemoting` cmdlets, or the **AccessMode** parameter of `Register-PSSessionConfiguration`. This is an advanced cmdlet that is designed to be used by system administrators to manage customized session configurations for their users. Without parameters, `Enable-PSSessionConfiguration` enables the **Microsoft.PowerShell** configuration, which is the default configuration that is used for sessions. `Enable-PSSessionConfiguration` removes the **Deny_All** setting from the security descriptor of the affected session configurations, turns on the listener that accepts requests on any IP address, and restarts the WinRM service. Beginning in PowerShell 3.0, `Enable-PSSessionConfiguration` also sets the value of the **Enabled** property of the session configuration (`WSMan:\<computer>\PlugIn\<SessionConfigurationName>\Enabled`) to True. However, `Enable-PSSessionConfiguration` does not remove or change the **Network_Deny_All** (`AccessMode=Local`) security descriptor setting that allows only users of the local computer to use to the session configuration. ## EXAMPLES ### Example 1: Re-enable the default session This example re-enables the **Microsoft.PowerShell** default session configuration on the computer. ```powershell Enable-PSSessionConfiguration ``` ### Example 2: Re-enable specified sessions This example re-enables the **MaintenanceShell** and **AdminShell** session configurations on the computer. ```powershell Enable-PSSessionConfiguration -Name MaintenanceShell, AdminShell ``` ### Example 3: Re-enable the all sessions This example re-enables all session configurations on the computer. These commands are equivalent. Therefore, you can use either. ```powershell Enable-PSSessionConfiguration -Name * Get-PSSessionConfiguration | Enable-PSSessionConfiguration ``` `Enable-PSSessionConfiguration` does not generate an error if you enable a session configuration that is already enabled. ### Example 4: Re-enable a session and specify a new security descriptor This example re-enables the **MaintenanceShell** session configuration and specifies a new security descriptor for the configuration. ```powershell $sddl = "O:NSG:BAD:P(A;;GXGWGR;;;BA)(A;;GAGR;;;S-1-5-21-123456789-188441444-3100496)S:P" Enable-PSSessionConfiguration -Name MaintenanceShell -SecurityDescriptorSDDL $sddl ``` ## PARAMETERS ### -Force Indicates that the cmdlet does not prompt you for confirmation, and restarts the WinRM service without prompting. Restarting the service makes the configuration change effective. To prevent a restart and suppress the restart prompt, use the **NoServiceRestart** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies the names of session configurations to enable. Enter one or more configuration names. Wildcard characters are permitted. You can also pipe a string that contains a configuration name or a session configuration object to `Enable-PSSessionConfiguration`. If you omit this parameter, `Enable-PSSessionConfiguration` enables the **Microsoft.PowerShell** session configuration. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -NoServiceRestart Indicates that the cmdlet does not restart the service. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SecurityDescriptorSddl Specifies a security descriptor with which this cmdlet replaces the security descriptor on the session configuration. If you omit this parameter, `Enable-PSSessionConfiguration` only deletes the deny all item from the security descriptor. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipNetworkProfileCheck Indicates that this cmdlet enables the session configuration when the computer is on a public network. This parameter enables a firewall rule for public networks that allows remote access only from computers in the same local subnet. By default, `Enable-PSSessionConfiguration` fails on a public network. This parameter is designed for client versions of the Windows operating system. Server versions of the Windows operating system have a local subnet firewall rule for public networks. However, if the local subnet firewall rule is disabled on a server version of the Windows operating system, this parameter re-enables it. To remove the local subnet restriction and enable remote access from all locations on public networks, use the `Set-NetFirewallRule` cmdlet in the NetSecurity module. For more information, see `Enable-PSRemoting`. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#PSSessionConfiguration You can pipe a session configuration object to this cmdlet. ### System.String You can pipe a string that contains the name of a session configuration to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES This cmdlet is only available on Windows platforms. To use this cmdlet, you must start PowerShell by using the **Run as administrator** option. ## RELATED LINKS [Disable-PSSessionConfiguration](Disable-PSSessionConfiguration.md) [Get-PSSessionConfiguration](Get-PSSessionConfiguration.md) [New-PSSessionConfigurationFile](New-PSSessionConfigurationFile.md) [New-PSSessionOption](New-PSSessionOption.md) [Register-PSSessionConfiguration](Register-PSSessionConfiguration.md) [Set-PSSessionConfiguration](Set-PSSessionConfiguration.md) [Test-PSSessionConfigurationFile](Test-PSSessionConfigurationFile.md) [Unregister-PSSessionConfiguration](Unregister-PSSessionConfiguration.md) [WSMan Provider](../Microsoft.WsMan.Management/About/about_WSMan_Provider.md) [about_Session_Configurations](About/about_Session_Configurations.md) [about_Session_Configuration_Files](About/about_Session_Configuration_Files.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Enter-PSHostProcess.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 01/31/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/enter-pshostprocess?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Enter-PSHostProcess --- # Enter-PSHostProcess ## SYNOPSIS Connects to and enters into an interactive session with a local process. ## SYNTAX ### ProcessIdParameterSet (Default) ``` Enter-PSHostProcess [-Id] <Int32> [[-AppDomainName] <String>] [<CommonParameters>] ``` ### ProcessParameterSet ``` Enter-PSHostProcess [-Process] <Process> [[-AppDomainName] <String>] [<CommonParameters>] ``` ### ProcessNameParameterSet ``` Enter-PSHostProcess [-Name] <String> [[-AppDomainName] <String>] [<CommonParameters>] ``` ### PSHostProcessInfoParameterSet ``` Enter-PSHostProcess [-HostProcessInfo] <PSHostProcessInfo> [[-AppDomainName] <String>] [<CommonParameters>] ``` ### PipeNameParameterSet ``` Enter-PSHostProcess -CustomPipeName <String> [<CommonParameters>] ``` ## DESCRIPTION The `Enter-PSHostProcess` cmdlet connects to and enters into an interactive session with a local process. Beginning in PowerShell 6.2, this cmdlet is supported on non-Windows platforms. Instead of creating a new process to host PowerShell and run a remote session, the remote, interactive session is run in an existing process that is already running PowerShell. When you are interacting with a remote session on a specified process, you can enumerate running runspaces, and then select a runspace to debug by running either `Debug-Runspace` or `Enable-RunspaceDebug`. The process that you want to enter must be hosting PowerShell (System.Management.Automation.dll). You must be either a member of the Administrators group on the computer on which the process is found, or you must be the user who is running the script that started the process. After you have selected a runspace to debug, a remote debug session is opened for the runspace if it is either currently running a command or is stopped in the debugger. You can then debug the runspace script in the same way you would debug other remote session scripts. Detach from a debugging session, and then the interactive session with the process, by running exit twice, or stop script execution by running the existing debugger quit command. If you specify a process by using the **Name** parameter, and there is only one process found with the specified name, the process is entered. If more than one process with the specified name is found, PowerShell returns an error, and lists all processes found with the specified name. To support attaching to processes on remote computers, the `Enter-PSHostProcess` cmdlet is enabled in a specified remote computer, so that you can attach to a local process within a remote PowerShell session. ## EXAMPLES ### Example Part 1: Start debugging a runspace within the PowerShell ISE process In this example, you run `Enter-PSHostProcess` from within the PowerShell console to enter the PowerShell ISE process. In the resulting interactive session, you can find a runspace that you want to debug by running `Get-Runspace`, and then debug the runspace. ``` PS C:\> Enter-PSHostProcess -Name powershell_ise [Process:1520]: PS C:\> Get-Runspace Id Name InstanceId State Availability -- ------- ----------- ------ ------------- 1 Runspace1 2d91211d-9cce-42f0-ab0e-71ac258b32b5 Opened Available 2 Runspace2 a3855043-cb16-424a-a616-685360c3763b Opened RemoteDebug 3 MyLocalRS 2236dbd8-2105-4dec-a15a-a27d0bfaacb5 Opened LocalDebug 4 MyRunspace 771356e9-8c44-4b70-9de5-dd17cb41e48e Opened Busy 5 Runspace8 3e517382-a97a-49ba-9c3c-fd21f6664288 Broken None ``` ### Example part 2: Debug a specific runspace Next, debug runspace ID 4, that is running another user's long-running script. From the list returned from `Get-Runspace`, note that the runspace **State** is Opened, and **Availability** is Busy, meaning that the runspace is still running the long-running script. The runspace objects returned by `Get-Runspace` also have a **NoteProperty** called **ScriptStackTrace** of the running command stack, if available. ``` [Process:1520]: PS C:\> (Get-Runspace -Id 4).ScriptStackTrace Command Arguments Location ------- --------- -------- MyModuleWorkflowF1 {} TestNoFile3.psm1: line 6 WFTest1 {} TestNoFile2.ps1: line 14 TestNoFile2.ps1 {} TestNoFile2.ps1: line 22 <ScriptBlock> {} <No file> [Process: 1520]: PS C:\> Debug-Runspace -Id 4 Hit Line breakpoint on 'C:\TestWFVar1.ps1:83' At C:\TestWFVar1.ps1:83 char:1 + $scriptVar = "Script Variable" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Process: 1520]: [RSDBG: 4]: PS C:\> ``` Start an interactive debugging session with this runspace by running the `Debug-Runspace` cmdlet. ### Example part 3: Finish the debugging session and exit After you are finished debugging, allow the script to continue running without the debugger attached by running the exit debugger command. Alternatively, you can quit the debugger with the q or Stop commands. When you are finished working in the process, exit the process by running the `Exit-PSHostProcess` cmdlet. This returns you to the `PS C:\>` prompt. ``` [Process:346]: [RSDBG: 3]: PS C:\> exit [Process:1520]: PS C:\> [Process:1520]: PS C:\> Exit-PSHostProcess PS C:\> ``` ## PARAMETERS ### -AppDomainName Specifies an application domain name to connect to if omitted, uses **DefaultAppDomain**. Use `Get-PSHostProcessInfo` to display the application domain names. ```yaml Type: System.String Parameter Sets: ProcessIdParameterSet, ProcessParameterSet, ProcessNameParameterSet, PSHostProcessInfoParameterSet Aliases: Required: False Position: 1 Default value: DefaultAppDomain Accept pipeline input: False Accept wildcard characters: False ``` ### -CustomPipeName Gets or sets the custom named pipe name to connect to. This is usually used in conjunction with `pwsh -CustomPipeName`. This parameter was introduced in PowerShell 6.2. ```yaml Type: System.String Parameter Sets: PipeNameParameterSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -HostProcessInfo Specifies a **PSHostProcessInfo** object that can be connected to with PowerShell. Use `Get-PSHostProcessInfo` to get the object. ```yaml Type: Microsoft.PowerShell.Commands.PSHostProcessInfo Parameter Sets: PSHostProcessInfoParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Id Specifies a process by the process ID. To get a process ID, run the `Get-Process` cmdlet. ```yaml Type: System.Int32 Parameter Sets: ProcessIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies a process by the process name. To get a process name, run the `Get-Process` cmdlet. You can also get process names from the Properties dialog box of a process in Task Manager. ```yaml Type: System.String Parameter Sets: ProcessNameParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Process Specifies a process by the process object. The simplest way to use this parameter is to save the results of a `Get-Process` command that returns process that you want to enter in a variable, and then specify the variable as the value of this parameter. ```yaml Type: System.Diagnostics.Process Parameter Sets: ProcessParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Diagnostics.Process ## OUTPUTS ## NOTES `Enter-PSHostProcess` cannot enter the process of the PowerShell session in which you are running the command. You can, however, enter the process of another PowerShell session, or a PowerShell ISE session that is running at the same time as the session in which you are running `Enter-PSHostProcess`. `Enter-PSHostProcess` can enter only those processes that are hosting PowerShell. That is, they have loaded the PowerShell engine. To exit a process from within the process, type **exit**, and then press <kbd>Enter</kbd>. Prior to PowerShell 7.1, remoting over SSH did not support second-hop remote sessions. This capability was limited to sessions using WinRM. PowerShell 7.1 allows `Enter-PSSession` and `Enter-PSHostProcess` to work from within any interactive remote session. ## RELATED LINKS [Exit-PSHostProcess](Exit-PSHostProcess.md) [Get-PSHostProcessInfo](Get-PSHostProcessInfo.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Enter-PSSession.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 06/14/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/enter-pssession?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Enter-PSSession --- # Enter-PSSession ## SYNOPSIS Starts an interactive session with a remote computer. ## SYNTAX ### ComputerName (Default) ``` Enter-PSSession [-ComputerName] <String> [-EnableNetworkAccess] [[-Credential] <PSCredential>] [-ConfigurationName <String>] [-Port <Int32>] [-UseSSL] [-ApplicationName <String>] [-SessionOption <PSSessionOption>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ### SSHHost ``` Enter-PSSession [-HostName] <String> [-Options <Hashtable>] [-Port <Int32>] [-UserName <String>] [-KeyFilePath <String>] [-Subsystem <String>] [-ConnectingTimeout <Int32>] [-SSHTransport] [<CommonParameters>] ``` ### Session ``` Enter-PSSession [[-Session] <PSSession>] [<CommonParameters>] ``` ### Uri ``` Enter-PSSession [[-ConnectionUri] <Uri>] [-EnableNetworkAccess] [[-Credential] <PSCredential>] [-ConfigurationName <String>] [-AllowRedirection] [-SessionOption <PSSessionOption>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ### InstanceId ``` Enter-PSSession [-InstanceId <Guid>] [<CommonParameters>] ``` ### Id ``` Enter-PSSession [[-Id] <Int32>] [<CommonParameters>] ``` ### Name ``` Enter-PSSession [-Name <String>] [<CommonParameters>] ``` ### VMId ``` Enter-PSSession [-VMId] <Guid> [-Credential] <PSCredential> [-ConfigurationName <String>] [<CommonParameters>] ``` ### VMName ``` Enter-PSSession [-VMName] <String> [-Credential] <PSCredential> [-ConfigurationName <String>] [<CommonParameters>] ``` ### ContainerId ``` Enter-PSSession [-ContainerId] <String> [-ConfigurationName <String>] [-RunAsAdministrator] [<CommonParameters>] ``` ## DESCRIPTION The `Enter-PSSession` cmdlet starts an interactive session with a single remote computer. During the session, the commands that you type run on the remote computer, just as if you were typing directly on the remote computer. You can have only one interactive session at a time. Typically, you use the **ComputerName** parameter to specify the name of the remote computer. However, you can also use a session that you create by using the `New-PSSession` cmdlet for the interactive session. However, you can't use the `Disconnect-PSSession`, `Connect-PSSession`, or `Receive-PSSession` cmdlets to disconnect from or re-connect to an interactive session. Starting with PowerShell 6.0 you can use Secure Shell (SSH) to establish a connection to a remote computer. You must have SSH on the local computer and the remote computer must be configured with a PowerShell SSH endpoint. The benefit an SSH based PowerShell remote session is that it works across multiple platforms (Windows, Linux, macOS). For SSH based remoting you use the **HostName** parameter set to specify the remote computer and relevant connection information. For more information about how to set up PowerShell SSH remoting, see [PowerShell Remoting Over SSH](/powershell/scripting/learn/remoting/ssh-remoting-in-powershell-core). To end the interactive session and disconnect from the remote computer, use the `Exit-PSSession` cmdlet, or type `exit`. > [!IMPORTANT] > `Enter-PSSession` is designed to substitute the current interactive session with a new interactive > remote session. You shouldn't call it from within a function or script or by passing it as a > command to the `pwsh` executable. ## EXAMPLES ### Example 1: Start an interactive session ``` PS> Enter-PSSession [localhost]: PS> ``` This command starts an interactive session on the local computer. The command prompt changes to indicate that you are now running commands in a different session. The commands that you enter run in the new session, and the results are returned to the default session as text. ### Example 2: Work with an interactive session The first command uses the `Enter-PSSession` cmdlet to start an interactive session with Server01, a remote computer. When the session starts, the command prompt changes to include the computer name. The second command gets the PowerShell process and redirects the output to the `Process.txt` file. The command is submitted to the remote computer, and the file is saved on the remote computer. The third command uses the `exit` keyword to end the interactive session and close the connection. The fourth command confirms that the Process.txt file is on the remote computer. A `Get-ChildItem` ("dir") command on the local computer can't find the file. ```powershell PS C:\> Enter-PSSession -ComputerName Server01 [Server01]: PS C:\> [Server01]: PS C:\> Get-Process powershell > C:\ps-test\Process.txt [Server01]: PS C:\> exit PS C:\> PS C:\> dir C:\ps-test\Process.txt Get-ChildItem : Cannot find path 'C:\ps-test\Process.txt' because it does not exist. At line:1 char:4 + dir <<<< C:\ps-test\Process.txt ``` This command shows how to work in an interactive session with a remote computer. ### Example 3: Use the Session parameter ```powershell PS> $s = New-PSSession -ComputerName Server01 PS> Enter-PSSession -Session $s [Server01]: PS> ``` These commands use the **Session** parameter of `Enter-PSSession` to run the interactive session in an existing PowerShell session (**PSSession**). ### Example 4: Start an interactive session and specify the Port and Credential parameters ```powershell PS> Enter-PSSession -ComputerName Server01 -Port 90 -Credential Domain01\User01 [Server01]: PS> ``` This command starts an interactive session with the Server01 computer. It uses the **Port** parameter to specify the port and the **Credential** parameter to specify the account of a user who has permission to connect to the remote computer. ### Example 5: Stop an interactive session ```powershell PS> Enter-PSSession -ComputerName Server01 [Server01]: PS> Exit-PSSession PS> ``` This example shows how to start and stop an interactive session. The first command uses the `Enter-PSSession` cmdlet to start an interactive session with the Server01 computer. The second command uses the `Exit-PSSession` cmdlet to end the session. You can also use the `exit` keyword to end the interactive session. `Exit-PSSession` and `exit` have the same effect. ### Example 6: Start an interactive session using SSH ```powershell PS> Enter-PSSession -HostName UserA@LinuxServer01 ``` This example shows how to start an interactive session using Secure Shell (SSH). If SSH is configured on the remote computer to use passwords then you are prompted to enter a password. Otherwise, you must use key-based user authentication. ### Example 7: Start an interactive session using SSH with a port and user authentication key ```powershell PS> Enter-PSSession -HostName UserA@LinuxServer02:22 -KeyFilePath C:\sshkeys\userAKey_rsa ``` This example shows how to start an interactive session using SSH. The username and SSH port number are specified as parts of the value of the **HostName** parameter. The **KeyFilePath** parameter specifies the location of an RSA key used to authenticate the user on the remote computer. ### Example 8: Start an interactive session using SSH options ```powershell $options = @{ Port=22 User = 'UserA' Host = 'LinuxServer02' } Enter-PSSession -KeyFilePath C:\sshkeys\userAKey_rsa -Options $options ``` This example shows how to start an interactive session using SSH. The **Options** parameter takes a hashtable of values that are passed as options to the underlying `ssh` command the established the connection to the remote system. ## PARAMETERS ### -AllowRedirection Allows redirection of this connection to an alternate Uniform Resource Identifier (URI). By default, redirection isn't allowed. When you use the **ConnectionURI** parameter, the remote destination can return an instruction to redirect to a different URI. By default, PowerShell doesn't redirect connections, but you can use this parameter to allow it to redirect the connection. You can also limit the number of times the connection is redirected by changing the **MaximumConnectionRedirectionCount** session option value. Use the **MaximumRedirection** parameter of the `New-PSSessionOption` cmdlet or set the **MaximumConnectionRedirectionCount** property of the `$PSSessionOption` preference variable. The default value is 5. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Uri Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ApplicationName Specifies the application name segment of the connection URI. Use this parameter to specify the application name when you aren't using the **ConnectionURI** parameter in the command. The default value is the value of the `$PSSessionApplicationName` preference variable on the local computer. If this preference variable isn't defined, the default value is WSMAN. This value is appropriate for most uses. For more information, see [about_Preference_Variables](About/about_Preference_Variables.md). The **WinRM** service uses the application name to select a listener to service the connection request. The value of this parameter should match the value of the **URLPrefix** property of a listener on the remote computer. ```yaml Type: System.String Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Authentication Specifies the mechanism that's used to authenticate the user's credentials. The acceptable values for this parameter are: - Default - Basic - Credssp - Digest - Kerberos - Negotiate - NegotiateWithImplicitCredential The default value is Default. CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of the Windows operating system. For more information about the values of this parameter, see [AuthenticationMechanism Enum](/dotnet/api/system.management.automation.runspaces.authenticationmechanism). > [!CAUTION] > Credential Security Support Provider (CredSSP) authentication, in which the user's credentials are > passed to a remote computer to be authenticated, is designed for commands that require > authentication on more than one resource, such as accessing a remote network share. This mechanism > increases the security risk of the remote operation. If the remote computer is compromised, the > credentials that are passed to it can be used to control the network session. ```yaml Type: System.Management.Automation.Runspaces.AuthenticationMechanism Parameter Sets: ComputerName, Uri Aliases: Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential, Credssp, Digest, Kerberos Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to perform this action. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they don't work with domain accounts. To get a certificate, use the `Get-Item` or `Get-ChildItem` command in the PowerShell Cert: drive. ```yaml Type: System.String Parameter Sets: ComputerName, Uri Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies a computer name. This cmdlet starts an interactive session with the specified remote computer. Enter only one computer name. The default is the local computer. Type the NetBIOS name, the IP address, or the fully qualified domain name of the computer. You can also pipe a computer name to `Enter-PSSession`. To use an IP address in the value of the **ComputerName** parameter, the command must include the **Credential** parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote computer must be included in the WinRM TrustedHosts list on the local computer. For instructions for adding a computer name to the TrustedHosts list, see "How to Add a Computer to the Trusted Host List" in [about_Remote_Troubleshooting](About/about_Remote_Troubleshooting.md). > [!NOTE] > On the Windows operating system, to include the local computer in the value of the > **ComputerName** parameter, you must start PowerShell with the Run as administrator option. ```yaml Type: System.String Parameter Sets: ComputerName Aliases: Cn Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -ConfigurationName Specifies the session configuration that's used for the interactive session. Enter a configuration name or the fully qualified resource URI for a session configuration. If you specify only the configuration name, the following schema URI is prepended: `http://schemas.microsoft.com/powershell`. When used with SSH, this specifies the subsystem to use on the target as defined in sshd_config. The default value for SSH is the `powershell` subsystem. The session configuration for a session is located on the remote computer. If the specified session configuration doesn't exist on the remote computer, the command fails. The default value is the value of the `$PSSessionConfigurationName` preference variable on the local computer. If this preference variable isn't set, the default is Microsoft.PowerShell. For more information, see [about_Preference_Variables](About/about_Preference_Variables.md). ```yaml Type: System.String Parameter Sets: ComputerName, Uri, VMId, VMName, ContainerId Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ConnectingTimeout Specifies the amount of time in milliseconds allowed for the initial SSH connection to complete. If the connection doesn't complete within the specified time, an error is returned. This parameter was introduced in PowerShell 7.2 ```yaml Type: System.Int32 Parameter Sets: SSHHost Aliases: Required: False Position: Named Default value: unlimited Accept pipeline input: False Accept wildcard characters: False ``` ### -ConnectionUri Specifies a URI that defines the connection endpoint for the session. The URI must be fully qualified. The format of this string is as follows: `<Transport>://<ComputerName>:<Port>/<ApplicationName>` The default value is as follows: `http://localhost:5985/WSMAN` If you don't specify a **ConnectionURI**, you can use the **UseSSL**, **ComputerName**, **Port**, and **ApplicationName** parameters to specify the **ConnectionURI** values. Valid values for the Transport segment of the URI are HTTP and HTTPS. If you specify a connection URI with a Transport segment, but don't specify a port, the session is created by using standards ports: 80 for HTTP and 443 for HTTPS. To use the default ports for PowerShell remoting, specify port 5985 for HTTP or 5986 for HTTPS. If the destination computer redirects the connection to a different URI, PowerShell prevents the redirection unless you use the **AllowRedirection** parameter in the command. ```yaml Type: System.Uri Parameter Sets: Uri Aliases: URI, CU Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ContainerId Specifies the ID of a container. ```yaml Type: System.String Parameter Sets: ContainerId Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. If you type a user name, you're prompted to enter the password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: ComputerName, Uri, VMId, VMName Aliases: Required: True (VMId, VMName), False (ComputerName, Uri) Position: 1 Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -EnableNetworkAccess Indicates that this cmdlet adds an interactive security token to loopback sessions. The interactive token lets you run commands in the loopback session that get data from other computers. For example, you can run a command in the session that copies XML files from a remote computer to the local computer. A loopback session is a **PSSession** that originates and ends on the same computer. To create a loopback session, omit the **ComputerName** parameter or set its value to . (dot), localhost, or the name of the local computer. By default, loopback sessions are created by using a network token, which might not provide sufficient permission to authenticate to remote computers. The **EnableNetworkAccess** parameter is effective only in loopback sessions. If you use **EnableNetworkAccess** when you create a session on a remote computer, the command succeeds, but the parameter is ignored. You can also allow remote access in a loopback session by using the **CredSSP** value of the **Authentication** parameter, which delegates the session credentials to other computers. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerName, Uri Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -HostName Specifies a computer name for a Secure Shell (SSH) based connection. This is similar to the **ComputerName** parameter except that the connection to the remote computer is made using SSH rather than Windows WinRM. This parameter supports specifying the user name and/or port as part of the **HostName** parameter value using the form `user@hostname:port`. The user name and/or port specified as part of the host name takes precedence over the `-UserName` and `-Port` parameters, if specified. This allows passing multiple computer names to this parameter where some have specific user names and/or ports, while others use the user name and/or port from the `-UserName` and `-Port` parameters. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.String Parameter Sets: SSHHost Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Id Specifies the ID of an existing session. `Enter-PSSession` uses the specified session for the interactive session. To find the ID of a session, use the `Get-PSSession` cmdlet. ```yaml Type: System.Int32 Parameter Sets: Id Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InstanceId Specifies the instance ID of an existing session. `Enter-PSSession` uses the specified session for the interactive session. The instance ID is a GUID. To find the instance ID of a session, use the `Get-PSSession` cmdlet. You can also use the **Session**, **Name**, or **Id** parameters to specify an existing session. Or, you can use the **ComputerName** parameter to start a temporary session. ```yaml Type: System.Guid Parameter Sets: InstanceId Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -KeyFilePath Specifies a key file path used by Secure Shell (SSH) to authenticate a user on a remote computer. SSH allows user authentication to be performed via private/public keys as an alternative to basic password authentication. If the remote computer is configured for key authentication then this parameter can be used to provide the key that identifies the user. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.String Parameter Sets: SSHHost Aliases: IdentityFilePath Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies the friendly name of an existing session. `Enter-PSSession` uses the specified session for the interactive session. If the name that you specify matches more than one session, the command fails. You can also use the **Session**, **InstanceId**, or **Id** parameters to specify an existing session. Or, you can use the **ComputerName** parameter to start a temporary session. To establish a friendly name for a session, use the **Name** parameter of the `New-PSSession` cmdlet. ```yaml Type: System.String Parameter Sets: Name Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Options Specifies a hashtable of SSH options used when connecting to a remote SSH-based session. The possible options are any values supported by the Unix-based version of the [ssh](https://man.openbsd.org/ssh#o) command. Any values explicitly passed by parameters take precedence over values passed in the **Options** hashtable. For example, using the **Port** parameter overrides any `Port` key-value pair passed in the **Options** hashtable. ```yaml Type: System.Collections.Hashtable Parameter Sets: SSHHost Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Port Specifies the network port on the remote computer that's used for this command. In PowerShell 6.0 this parameter was included in the **HostName** parameter set which supports Secure Shell (SSH) connections. **WinRM (ComputerName parameter set)** To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are 5985, which is the WinRM port for HTTP, and 5986, which is the WinRM port for HTTPS. Before using an alternate port, you must configure the WinRM listener on the remote computer to listen at that port. Use the following commands to configure the listener: 1. `winrm delete winrm/config/listener?Address=*+Transport=HTTP` 2. `winrm create winrm/config/listener?Address=*+Transport=HTTP @{Port="\<port-number\>"}` Don't use the **Port** parameter unless you must. The port setting in the command applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on all computers. **SSH (HostName parameter set)** To connect to a remote computer, the remote computer must be configured with the SSH service (SSHD) and must be listening on the port that the connection uses. The default port for SSH is 22. ```yaml Type: System.Int32 Parameter Sets: ComputerName, SSHHost Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RunAsAdministrator Indicates that the **PSSession** runs as administrator. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ContainerId Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Session Specifies a PowerShell session (**PSSession**) to use for the interactive session. This parameter takes a session object. You can also use the **Name**, **InstanceId**, or **Id** parameters to specify a **PSSession**. Enter a variable that contains a session object or a command that creates or gets a session object, such as a `New-PSSession` or `Get-PSSession` command. You can also pipe a session object to `Enter-PSSession`. You can submit only one **PSSession** by using this parameter. If you enter a variable that contains more than one **PSSession**, the command fails. When you use `Exit-PSSession` or the `exit` keyword, the interactive session ends, but the **PSSession** that you created remains open and available for use. ```yaml Type: System.Management.Automation.Runspaces.PSSession Parameter Sets: Session Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -SessionOption Sets advanced options for the session. Enter a **SessionOption** object, such as one that you create by using the `New-PSSessionOption` cmdlet, or a hash table in which the keys are session option names and the values are session option values. The default values for the options are determined by the value of the `$PSSessionOption` preference variable, if it's set. Otherwise, the default values are established by options set in the session configuration. The session option values take precedence over default values for sessions set in the `$PSSessionOption` preference variable and in the session configuration. However, they don't take precedence over maximum values, quotas or limits set in the session configuration. For a description of the session options, including the default values, see `New-PSSessionOption`. For information about the `$PSSessionOption` preference variable, see [about_Preference_Variables](About/about_Preference_Variables.md). For more information about session configurations, see [about_Session_Configurations](About/about_Session_Configurations.md). ```yaml Type: System.Management.Automation.Remoting.PSSessionOption Parameter Sets: ComputerName, Uri Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SSHTransport Indicates that the remote connection is established using Secure Shell (SSH). By default PowerShell uses Windows WinRM to connect to a remote computer. This switch forces PowerShell to use the HostName parameter set for establishing an SSH based remote connection. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: SSHHost Aliases: Accepted values: true Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Subsystem Specifies the SSH subsystem used for the new **PSSession**. This specifies the subsystem to use on the target as defined in sshd_config. The subsystem starts a specific version of PowerShell with predefined parameters. If the specified subsystem doesn't exist on the remote computer, the command fails. If this parameter isn't used, the default is the `powershell` subsystem. ```yaml Type: System.String Parameter Sets: SSHHost Aliases: Required: False Position: Named Default value: Powershell Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -UserName Specifies the user name for the account used to create a session on the remote computer. User authentication method depends on how Secure Shell (SSH) is configured on the remote computer. If SSH is configured for basic password authentication then you are prompted for the user password. If SSH is configured for key based user authentication then uou aren't prompted for a password. You must provide a path to an SSH key file. If the user key file is located in an SSH known location then the **KeyFilePath** parameter isn't needed. User authentication occurs automatically based on the user name. See SSH documentation about key based user authentication for more information. If the **UserName** parameter isn't specified then the current logged on username is used. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.String Parameter Sets: SSHHost Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL isn't used. WS-Management encrypts all PowerShell content transmitted over the network. The **UseSSL** parameter is an additional protection that sends the data across an HTTPS connection instead of an HTTP connection. If you use this parameter, but SSL isn't available on the port that's used for the command, the command fails. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -VMId Specifies the ID of a virtual machine. ```yaml Type: System.Guid Parameter Sets: VMId Aliases: VMGuid Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -VMName Specifies the name of a virtual machine. ```yaml Type: System.String Parameter Sets: VMName Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a computer name as a string to this cmdlet. ### System.Management.Automation.Runspaces.PSSession You can pipe a session object to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Enter-PSSession`: - All platforms: - `etsn` To connect to a remote computer, you must be a member of the Administrators group on the remote computer. To start an interactive session on the local computer, you must start PowerShell with the **Run as administrator** option. When you use `Enter-PSSession`, your user profile on the remote computer is used for the interactive session. The commands in the remote user profile, including commands to add PowerShell modules and to change the command prompt, run before the remote prompt is displayed. `Enter-PSSession` uses the UI culture setting on the local computer for the interactive session. To find the local UI culture, use the `$UICulture` automatic variable. `Enter-PSSession` requires the `Get-Command`, `Out-Default`, and `Exit-PSSession` cmdlets. If these cmdlets aren't included in the session configuration on the remote computer, the `Enter-PSSession` commands fails. Unlike `Invoke-Command`, which parses and interprets the commands before it sends them to the remote computer, `Enter-PSSession` sends the commands directly to the remote computer without interpretation. If the session you want to enter is busy processing a command, there might be a delay before PowerShell responds to the `Enter-PSSession` command. You are connected as soon as the session is available. To cancel the `Enter-PSSession` command, press <kbd>CTRL</kbd>+<kbd>C</kbd>. The **HostName** parameter set was included starting with PowerShell 6.0. It was added to provide PowerShell remoting based on Secure Shell (SSH). Both SSH and PowerShell are supported on multiple platforms (Windows, Linux, macOS) and PowerShell remoting works over these platforms where PowerShell and SSH are installed and configured. This is separate from the previous Windows only remoting that's based on WinRM and much of the WinRM specific features and limitations don't apply. For example, WinRM based quotas, session options, custom endpoint configuration, and disconnect/reconnect features are currently not supported. For more information about how to set up PowerShell SSH remoting, see [PowerShell Remoting Over SSH](/powershell/scripting/learn/remoting/ssh-remoting-in-powershell-core). Prior to PowerShell 7.1, remoting over SSH didn't support second-hop remote sessions. This capability was limited to sessions using WinRM. PowerShell 7.1 allows `Enter-PSSession` and `Enter-PSHostProcess` to work from within any interactive remote session. The `ssh` executable obtains configuration data from the following sources in the following order: 1. command-line options 1. user's configuration file (~/.ssh/config) 1. system-wide configuration file (/etc/ssh/ssh_config) The following cmdlet parameters get mapped into `ssh` parameters and options: | Cmdlet parameter | ssh parameter | equivalent ssh -o option | | -------------------------- | ------------------------------- | ------------------------------- | | `-KeyFilePath` | `-i <KeyFilePath>` | `-o IdentityFile=<KeyFilePath>` | | `-UserName` | `-l <UserName>` | `-o User=<UserName>` | | `-Port` | `-p <Port>` | `-o Port=<Port>` | | `-ComputerName -Subsystem` | `-s <ComputerName> <Subsystem>` | `-o Host=<ComputerName>` | Any values explicitly passed by parameters take precedence over values passed in the **Options** hashtable. For more information about `ssh_config` files, see [ssh_config(5)](https://man.openbsd.org/ssh_config.5). ## RELATED LINKS [Exit-PSSession](Exit-PSSession.md) [Get-PSSession](Get-PSSession.md) [Invoke-Command](Invoke-Command.md) [New-PSSession](New-PSSession.md) [Remove-PSSession](Remove-PSSession.md) [Connect-PSSession](Connect-PSSession.md) [Disconnect-PSSession](Disconnect-PSSession.md) [Receive-PSSession](Receive-PSSession.md) [about_PSSessions](About/about_PSSessions.md) [about_Remote](About/about_Remote.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Exit-PSHostProcess.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 11/06/2020 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/exit-pshostprocess?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Exit-PSHostProcess --- # Exit-PSHostProcess ## SYNOPSIS Closes an interactive session with a local process. ## SYNTAX ``` Exit-PSHostProcess [<CommonParameters>] ``` ## DESCRIPTION The `Exit-PSHostProcess` cmdlet closes an interactive session with a local process that you have opened by running the `Enter-PSHostProcess` cmdlet. You run the `Exit-PSHostProcess` cmdlet from within the process, when you are finished debugging or troubleshooting a script that is running within a process. Beginning in PowerShell 6.2, this cmdlet is supported on non-Windows platforms. ## EXAMPLES ### Example 1: Exit a process ``` [Process:1520]: PS> Exit-PSHostProcess PS> ``` In this example, you have been working in an active process to debug a script running in a runspace in the process, as described in `Enter-PSHostProcess`. After you type the `exit` command to exit the debugger, run the `Exit-PSHostProcess` cmdlet to close your interactive session with the process. The cmdlet closes your session in the process, and returns you to the `PS C:\>` prompt. ## PARAMETERS ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ## NOTES ## RELATED LINKS [Enter-PSHostProcess](Enter-PSHostProcess.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Exit-PSSession.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/exit-pssession?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Exit-PSSession --- # Exit-PSSession ## SYNOPSIS Ends an interactive session with a remote computer. ## SYNTAX ``` Exit-PSSession [<CommonParameters>] ``` ## DESCRIPTION The `Exit-PSSession` cmdlet ends interactive sessions that you started by using the `Enter-PSSession` cmdlet. You can also use the `exit` keyword to end an interactive session. The effect is the same as using `Exit-PSSession`. ## EXAMPLES ### Example 1: Start and stop an interactive session ```powershell PS> Enter-PSSession -ComputerName Server01 Server01\PS> Exit-PSSession PS> ``` These commands start and then stop an interactive session with the Server01 remote computer. ### Example 2: Start and stop an interactive session by using a PSSession object ```powershell PS> $s = New-PSSession -ComputerName Server01 PS> Enter-PSSession -Session $s Server01\PS> Exit-PSSession PS> $s Id Name ComputerName State ConfigurationName -- ---- ------------ ----- ----------------- 1 Session1 Server01 Opened Microsoft.PowerShell ``` These commands start and stop an interactive session with the Server01 computer that uses a PowerShell session (**PSSession**). Because the interactive session was started by using a PowerShell session, the **PSSession** is still available when the interactive session ends. If you use the _ComputerName_ parameter, `Enter-PSSession` creates a temporary session that it closes when the interactive session ends. The first command uses the `New-PSSession` cmdlet to create a **PSSession** on the Server01 computer. The command saves the **PSSession** in the `$s` variable. The second command uses `Enter-PSSession` to start an interactive session using the **PSSession** in `$s`. The third command uses `Exit-PSSession` to stop the interactive session. The final command displays the **PSSession** in the `$s` variable. The **State** property shows the **PSSession** is still open and available for use. ### Example 3: Use the `exit` keyword to stop a session ```powershell PS> Enter-PSSession -ComputerName Server01 Server01\PS> exit PS> ``` This example uses the `exit` keyword to stop an interactive session started by using `Enter-PSSession`. The `exit` keyword has the same effect as using `Exit-PSSession`. ## PARAMETERS ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Exit-PSSession`: - All platforms: - `exsn` This cmdlet takes only the common parameters. ## RELATED LINKS [Connect-PSSession](Connect-PSSession.md) [Disconnect-PSSession](Disconnect-PSSession.md) [Enter-PSSession](Enter-PSSession.md) [Get-PSSession](Get-PSSession.md) [Invoke-Command](Invoke-Command.md) [New-PSSession](New-PSSession.md) [Receive-PSSession](Receive-PSSession.md) [Remove-PSSession](Remove-PSSession.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Export-ModuleMember.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/export-modulemember?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Export-ModuleMember --- # Export-ModuleMember ## SYNOPSIS Specifies the module members that are exported. ## SYNTAX ``` Export-ModuleMember [[-Function] <String[]>] [-Cmdlet <String[]>] [-Variable <String[]>] [-Alias <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Export-ModuleMember` cmdlet specifies the module members that are exported from a script module (`.psm1`) file, or from a dynamic module created by using the `New-Module` cmdlet. Module members include cmdlets, functions, variables, and aliases. This cmdlet can be used only in a script module file or a dynamic module. If a script module does not include an `Export-ModuleMember` command, the functions and aliases in the script module are exported, but the variables are not. When a script module includes `Export-ModuleMember` commands, only the members specified in the `Export-ModuleMember` commands are exported. You can also use `Export-ModuleMember` to suppress or export members that the script module imports from other modules. An `Export-ModuleMember` command is optional, but it is a best practice. Even if the command confirms the default values, it demonstrates the intention of the module author. ## EXAMPLES ### Example 1: Export functions and aliases in a script module ```powershell Export-ModuleMember -Function * -Alias * ``` This command exports all the functions and aliases defined in the script module. ### Example 2: Export specific aliases and functions ```powershell Export-ModuleMember -Function Get-Test, New-Test, Start-Test -Alias gtt, ntt, stt ``` This command exports three aliases and three functions defined in the script module. You can use this command format to specify the names of module members. ### Example 3: Export no members ```powershell Export-ModuleMember ``` This command specifies that no members defined in the script module are exported. This command prevents the module members from being exported, but it does not hide the members. Users can read and copy module members or use the call operator (`&`) to invoke module members that are not exported. ### Example 4: Export a specific variable ```powershell Export-ModuleMember -Variable increment ``` This command exports only the `$increment` variable from the script module. No other members are exported. If you want to export a variable, in addition to exporting the functions in a module, the `Export-ModuleMember` command must include the names of all of the functions and the name of the variable. ### Example 5: Multiple export commands ```powershell # From TestModule.psm1 function New-Test { Write-Output 'I am New-Test function' } Export-ModuleMember -Function New-Test function Validate-Test { Write-Output 'I am Validate-Test function' } function Start-Test { Write-Output 'I am Start-Test function' } Set-Alias stt Start-Test Export-ModuleMember -Function Start-Test -Alias stt ``` These commands show how multiple `Export-ModuleMember` commands are interpreted in a script module (`.psm1`) file. These commands create three functions and one alias, and then they export two of the functions and the alias. Without the `Export-ModuleMember` commands, all three of the functions and the alias would be exported. With the `Export-ModuleMember` commands, only the `New-Test` and `Start-Test` functions and the `STT` alias are exported. ### Example 6: Export members in a dynamic module ```powershell New-Module -Script {function SayHello {"Hello!"}; Set-Alias Hi SayHello; Export-ModuleMember -Alias Hi -Function SayHello} ``` This command shows how to use `Export-ModuleMember` in a dynamic module that is created by using the `New-Module` cmdlet. In this example, `Export-ModuleMember` is used to export both the `Hi` alias and the `SayHello` function in the dynamic module. ## PARAMETERS ### -Alias Specifies the aliases that are exported from the script module file. Enter the alias names. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Cmdlet Specifies the cmdlets that are exported from the script module file. Enter the cmdlet names. Wildcard characters are permitted. You cannot create cmdlets in a script module file, but you can import cmdlets from a binary module into a script module and re-export them from the script module. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Function Specifies the functions that are exported from the script module file. Enter the function names. Wildcard characters are permitted. You can also pipe function name strings to `Export-ModuleMember`. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Variable Specifies the variables that are exported from the script module file. Enter the variable names, without a dollar sign character (`$`). Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe function name strings to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES - To exclude a member from the list of exported members, add an `Export-ModuleMember` command that lists all other members but omits the member that you want to exclude. ## RELATED LINKS [Get-Module](Get-Module.md) [Import-Module](Import-Module.md) [Remove-Module](Remove-Module.md) [about_Modules](About/about_Modules.md)

#File: reference/7.6/Microsoft.PowerShell.Core/ForEach-Object.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 04/23/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/foreach-object?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: ForEach-Object --- # ForEach-Object ## SYNOPSIS Performs an operation against each item in a collection of input objects. ## SYNTAX ### ScriptBlockSet (Default) ``` ForEach-Object [-InputObject <PSObject>] [-Begin <ScriptBlock>] [-Process] <ScriptBlock[]> [-End <ScriptBlock>] [-RemainingScripts <ScriptBlock[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### PropertyAndMethodSet ``` ForEach-Object [-InputObject <PSObject>] [-MemberName] <String> [-ArgumentList <Object[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ParallelParameterSet ``` ForEach-Object -Parallel <scriptblock> [-InputObject <psobject>] [-ThrottleLimit <int>] [-TimeoutSeconds <int>] [-AsJob] [-UseNewRunspace] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `ForEach-Object` cmdlet performs an operation on each item in a collection of input objects. The input objects can be piped to the cmdlet or specified using the **InputObject** parameter. Starting in Windows PowerShell 3.0, there are two different ways to construct a `ForEach-Object` command. - **Script block syntax**. You can use a script block to specify the operation. Within the script block, use the `$_` variable to represent the current object. The script block is the value of the **Process** parameter. The script block can contain any PowerShell script. For example, the following command gets the value of the **ProcessName** property of each process on the computer. `Get-Process | ForEach-Object {$_.ProcessName}` `ForEach-Object` supports the `begin`, `process`, and `end` blocks as described in [about_Functions](about/about_functions.md#piping-objects-to-functions). > [!NOTE] > The script blocks run in the caller's scope. Therefore, the blocks have access to variables in > that scope and can create new variables that persist in that scope after the cmdlet completes. - **Simplified syntax**. Using the simplified syntax, you specify a property or method name of the object in the pipeline. `ForEach-Object` returns the value of the property or method for each object in the pipeline. For example, the following command also gets the value of the **ProcessName** property of each process on the computer. `Get-Process | ForEach-Object ProcessName` The simplified syntax was introduced in Windows PowerShell 3.0. For more information, see [about_Simplified_Syntax](About/about_Simplified_Syntax.md). - **Parallel running script block**. Beginning with PowerShell 7.0, a third parameter set is available that runs each script block in parallel. The **ThrottleLimit** parameter limits the number of parallel scripts running at a time. As before, use the `$_` variable to represent the current input object in the script block. Use the `Using:` scope modifier to pass variable references to the running script. In PowerShell 7, a new runspace is created for each loop iteration to ensure maximum isolation. This can be a large performance and resource hit if the work you are doing is small compared to creating new runspaces or if there are a lot of iterations performing significant work. As of PowerShell 7.1, runspaces from a runspace pool are reused by default. The **ThrottleLimit** parameter sets the runspace pool size. The default runspace pool size is 5. You can still create a new runspace for each iteration using the **UseNewRunspace** switch. By default, the parallel scriptblocks use the current working directory of the caller that started the parallel tasks. For more information, see the [NOTES](#notes) section of this article. ## EXAMPLES ### Example 1: Divide integers in an array This example takes an array of three integers and divides each one of them by 1024. ```powershell 30000, 56798, 12432 | ForEach-Object -Process {$_/1024} ``` ```Output 29.296875 55.466796875 12.140625 ``` ### Example 2: Get the length of all the files in a directory This example processes the files and directories in the PowerShell installation directory `$PSHOME`. ```powershell Get-ChildItem $PSHOME | ForEach-Object -Process { if (!$_.PSIsContainer) {$_.Name; $_.Length / 1024; " " } } ``` If the object isn't a directory, the script block gets the name of the file, divides the value of its **Length** property by 1024, and adds a space (" ") to separate it from the next entry. The cmdlet uses the **PSIsContainer** property to determine whether an object is a directory. ### Example 3: Operate on the most recent System events This example writes the 1000 most recent events from the System event log to a text file. The current time is displayed before and after processing the events. ```powershell Get-EventLog -LogName System -Newest 1000 | ForEach-Object -Begin {Get-Date} -Process { Out-File -FilePath Events.txt -Append -InputObject $_.Message } -End {Get-Date} ``` `Get-EventLog` gets the 1000 most recent events from the System event log and pipes them to the `ForEach-Object` cmdlet. The **Begin** parameter displays the current date and time. Next, the **Process** parameter uses the `Out-File` cmdlet to create a text file that's named events.txt and stores the message property of each of the events in that file. Last, the **End** parameter is used to display the date and time after all the processing has completed. ### Example 4: Change the value of a Registry key This example changes the value of the **RemotePath** registry entry in all the subkeys under the `HKCU:\Network` key to uppercase text. ```powershell Get-ItemProperty -Path HKCU:\Network\* | ForEach-Object { Set-ItemProperty -Path $_.PSPath -Name RemotePath -Value $_.RemotePath.ToUpper() } ``` You can use this format to change the form or content of a registry entry value. Each subkey in the **Network** key represents a mapped network drive that reconnects at sign on. The **RemotePath** entry contains the UNC path of the connected drive. For example, if you map the `E:` drive to `\\Server\Share`, an **E** subkey is created in `HKCU:\Network` with the **RemotePath** registry value set to `\\Server\Share`. The command uses the `Get-ItemProperty` cmdlet to get all the subkeys of the **Network** key and the `Set-ItemProperty` cmdlet to change the value of the **RemotePath** registry entry in each key. In the `Set-ItemProperty` command, the path is the value of the **PSPath** property of the registry key. This is a property of the Microsoft .NET Framework object that represents the registry key, not a registry entry. The command uses the **ToUpper()** method of the **RemotePath** value, which is a string **REG_SZ**. Because `Set-ItemProperty` is changing the property of each key, the `ForEach-Object` cmdlet is required to access the property. ### Example 5: Use the $null automatic variable This example shows the effect of piping the `$null` automatic variable to the `ForEach-Object` cmdlet. ```powershell 1, 2, $null, 4 | ForEach-Object {"Hello"} ``` ```Output Hello Hello Hello Hello ``` Because PowerShell treats `$null` as an explicit placeholder, the `ForEach-Object` cmdlet generates a value for `$null` as it does for other objects piped to it. ### Example 6: Get property values This example gets the value of the **Path** property of all installed PowerShell modules using the **MemberName** parameter of the `ForEach-Object` cmdlet. ```powershell Get-Module -ListAvailable | ForEach-Object -MemberName Path Get-Module -ListAvailable | foreach Path ``` The second command is equivalent to the first. It uses the `Foreach` alias of the `ForEach-Object` cmdlet and omits the name of the **MemberName** parameter, which is optional. The `ForEach-Object` cmdlet is useful for getting property values, because it gets the value without changing the type, unlike the **Format** cmdlets or the `Select-Object` cmdlet, which change the property value type. ### Example 7: Split module names into component names This example shows three ways to split two dot-separated module names into their component names. The commands call the **Split** method of strings. The three commands use different syntax, but they are equivalent and interchangeable. The output is the same for all three cases. ```powershell "Microsoft.PowerShell.Core", "Microsoft.PowerShell.Host" | ForEach-Object {$_.Split(".")} "Microsoft.PowerShell.Core", "Microsoft.PowerShell.Host" | ForEach-Object -MemberName Split -ArgumentList "." "Microsoft.PowerShell.Core", "Microsoft.PowerShell.Host" | foreach Split "." ``` ```Output Microsoft PowerShell Core Microsoft PowerShell Host ``` The first command uses the traditional syntax, which includes a script block and the current object operator `$_`. It uses the dot syntax to specify the method and parentheses to enclose the delimiter argument. The second command uses the **MemberName** parameter to specify the **Split** method and the **ArgumentList** parameter to identify the dot (`.`) as the split delimiter. The third command uses the `foreach` alias of the `ForEach-Object` cmdlet and omits the names of the **MemberName** and **ArgumentList** parameters, which are optional. ### Example 8: Using ForEach-Object with two script blocks In this example, we pass two script blocks positionally. All the script blocks bind to the **Process** parameter. However, they're treated as if they had been passed to the **Begin** and **Process** parameters. ```powershell 1..2 | ForEach-Object { 'begin' } { 'process' } ``` ```Output begin process process ``` ### Example 9: Using ForEach-Object with more than two script blocks In this example, we pass four script blocks positionally. All the script blocks bind to the **Process** parameter. However, they're treated as if they had been passed to the **Begin**, **Process**, and **End** parameters. ```powershell 1..2 | ForEach-Object { 'begin' } { 'process A' } { 'process B' } { 'end' } ``` ```Output begin process A process B process A process B end ``` > [!NOTE] > The first script block is always mapped to the `begin` block, the last block is mapped to the > `end` block, and the two middle blocks are mapped to the `process` block. ### Example 10: Run multiple script blocks for each pipeline item As shown in the previous example, multiple script blocks passed using the **Process** parameter get mapped to the **Begin** and **End** parameters. To avoid this mapping, you must provide explicit values for the **Begin** and **End** parameters. ```powershell 1..2 | ForEach-Object -Begin $null -Process { 'one' }, { 'two' }, { 'three' } -End $null ``` ```Output one two three one two three ``` ### Example 11: Run slow script in parallel batches This example runs a script block that evaluates a string and sleeps for one second. ```powershell $Message = "Output:" 1..8 | ForEach-Object -Parallel { "$Using:Message $_" Start-Sleep 1 } -ThrottleLimit 4 ``` ```Output Output: 1 Output: 2 Output: 3 Output: 4 Output: 5 Output: 6 Output: 7 Output: 8 ``` The **ThrottleLimit** parameter value is set to 4 so that the input is processed in batches of four. The `Using:` scope modifier is used to pass the `$Message` variable into each parallel script block. ### Example 12: Retrieve log entries in parallel This example retrieves 50,000 log entries from 5 system logs on a local Windows machine. ```powershell $logNames = 'Security', 'Application', 'System', 'Windows PowerShell', 'Microsoft-Windows-Store/Operational' $logEntries = $logNames | ForEach-Object -Parallel { Get-WinEvent -LogName $_ -MaxEvents 10000 } -ThrottleLimit 5 $logEntries.Count ``` ```Output 50000 ``` The **Parallel** parameter specifies the script block that's run in parallel for each input log name. The **ThrottleLimit** parameter ensures that all five script blocks run at the same time. ### Example 13: Run in parallel as a job This example creates a job that runs a script block in parallel, two at a time. ```powershell PS> $job = 1..10 | ForEach-Object -Parallel { "Output: $_" Start-Sleep 1 } -ThrottleLimit 2 -AsJob PS> $job Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 23 Job23 PSTaskJob Running True PowerShell PS> $job.ChildJobs Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 24 Job24 PSTaskChildJob Completed True PowerShell 25 Job25 PSTaskChildJob Completed True PowerShell 26 Job26 PSTaskChildJob Running True PowerShell 27 Job27 PSTaskChildJob Running True PowerShell 28 Job28 PSTaskChildJob NotStarted False PowerShell 29 Job29 PSTaskChildJob NotStarted False PowerShell 30 Job30 PSTaskChildJob NotStarted False PowerShell 31 Job31 PSTaskChildJob NotStarted False PowerShell 32 Job32 PSTaskChildJob NotStarted False PowerShell 33 Job33 PSTaskChildJob NotStarted False PowerShell ``` The **ThrottleLimit** parameter limits the number of parallel script blocks running at a time. The **AsJob** parameter causes the `ForEach-Object` cmdlet to return a job object instead of streaming output to the console. The `$job` variable receives the job object that collects output data and monitors running state. The `$job.ChildJobs` property contains the child jobs that run the parallel script blocks. ### Example 14: Using thread safe variable references This example invokes script blocks in parallel to collect uniquely named Process objects. ```powershell $threadSafeDictionary = [System.Collections.Concurrent.ConcurrentDictionary[string,object]]::new() Get-Process | ForEach-Object -Parallel { $dict = $Using:threadSafeDictionary $dict.TryAdd($_.ProcessName, $_) } $threadSafeDictionary["pwsh"] ``` ```Output NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 82 82.87 130.85 15.55 2808 2 pwsh ``` A single instance of a **ConcurrentDictionary** object is passed to each script block to collect the objects. Since the **ConcurrentDictionary** is thread safe, it's safe to be modified by each parallel script. A non-thread-safe object, such as **System.Collections.Generic.Dictionary**, would not be safe to use here. > [!NOTE] > This example is an inefficient use of **Parallel** parameter. The script adds the input object to > a concurrent dictionary object. It's trivial and not worth the overhead of invoking each script in > a separate thread. Running `ForEach-Object` without the **Parallel** switch is more efficient and > faster. This example is only intended to demonstrate how to use thread safe variables. ### Example 15: Writing errors with parallel execution This example writes to the error stream in parallel, where the order of written errors is random. ```powershell 1..3 | ForEach-Object -Parallel { Write-Error "Error: $_" } ``` ```Output Write-Error: Error: 1 Write-Error: Error: 3 Write-Error: Error: 2 ``` ### Example 16: Terminating errors in parallel execution This example demonstrates a terminating error in one parallel running scriptblock. ```powershell 1..5 | ForEach-Object -Parallel { if ($_ -eq 3) { throw "Terminating Error: $_" } Write-Output "Output: $_" } ``` ```Output Exception: Terminating Error: 3 Output: 1 Output: 4 Output: 2 Output: 5 ``` `Output: 3` is never written because the parallel scriptblock for that iteration was terminated. > [!NOTE] > [PipelineVariable](About/about_CommonParameters.md) common parameter variables are _not_ > supported in `ForEach-Object -Parallel` scenarios even with the `Using:` scope modifier. ### Example 17: Passing variables in nested parallel scriptblocks You can create a variable outside a `ForEach-Object -Parallel` scoped scriptblock and use it inside the scriptblock with the `Using:` scope modifier. Beginning in PowerShell 7.2, you can create a variable inside a `ForEach-Object -Parallel` scoped scriptblock and use it inside a nested scriptblock. ```powershell $test1 = 'TestA' 1..2 | ForEach-Object -Parallel { $Using:test1 $test2 = 'TestB' 1..2 | ForEach-Object -Parallel { $Using:test2 } } ``` ```Output TestA TestA TestB TestB TestB TestB ``` > [!NOTE] > In versions prior to PowerShell 7.2, the nested scriptblock can't access the `$test2` variable and > an error is thrown. ### Example 18: Creating multiple jobs that run scripts in parallel The ThrottleLimit parameter limits the number of parallel scripts running during each instance of `ForEach-Object -Parallel`. It doesn't limit the number of jobs that can be created when using the **AsJob** parameter. Since jobs themselves run concurrently, it's possible to create multiple parallel jobs, each running up to the throttle limit number of concurrent scriptblocks. ```powershell $jobs = for ($i=0; $i -lt 10; $i++) { 1..10 | ForEach-Object -Parallel { ./RunMyScript.ps1 } -AsJob -ThrottleLimit 5 } $jobs | Receive-Job -Wait ``` This example creates 10 running jobs. Each job runs no more that 5 scripts concurrently. The total number of instances running concurrently is limited to 50 (10 jobs times the **ThrottleLimit** of 5). ## PARAMETERS ### -ArgumentList Specifies an array of arguments to a method call. For more information about the behavior of **ArgumentList**, see [about_Splatting](about/about_Splatting.md#splatting-with-arrays). This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Object[] Parameter Sets: PropertyAndMethodSet Aliases: Args Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -AsJob Causes the parallel invocation to run as a PowerShell job. A single job object is returned instead of output from the running script blocks. The job object contains child jobs for each parallel script block that runs. You can use the job object with any of the PowerShell job cmdlets to see the running state and retrieve data. This parameter was introduced in PowerShell 7.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ParallelParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Begin Specifies a script block that runs before this cmdlet processes any input objects. This script block is only run once for the entire pipeline. For more information about the `begin` block, see [about_Functions](about/about_functions.md#piping-objects-to-functions). ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: ScriptBlockSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -End Specifies a script block that runs after this cmdlet processes all input objects. This script block is only run once for the entire pipeline. For more information about the `end` block, see [about_Functions](about/about_functions.md#piping-objects-to-functions). ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: ScriptBlockSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the input objects. `ForEach-Object` runs the script block or operation statement on each input object. Enter a variable that contains the objects, or type a command or expression that gets the objects. When you use the **InputObject** parameter with `ForEach-Object`, instead of piping command results to `ForEach-Object`, the **InputObject** value is treated as a single object. This is true even if the value is a collection that's the result of a command, such as `-InputObject (Get-Process)`. Because **InputObject** can't return individual properties from an array or collection of objects, we recommend that if you use `ForEach-Object` to perform operations on a collection of objects for those objects that have specific values in defined properties, you use `ForEach-Object` in the pipeline, as shown in the examples in this topic. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -MemberName Specifies the name of the member property to get or the member method to call. The members must be instance members, not static members. Wildcard characters are permitted, but work only if the resulting string resolves to a unique value. For example, if you run `Get-Process | foreach -MemberName *Name`, the wildcard pattern matches more than one member causing the command to fail. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String Parameter Sets: PropertyAndMethodSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Parallel Specifies the script block to be used for parallel processing of input objects. Enter a script block that describes the operation. This parameter was introduced in PowerShell 7.0. ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: ParallelParameterSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Process Specifies the operation that's performed on each input object. This script block is run for every object in the pipeline. For more information about the `process` block, see [about_Functions](about/about_functions.md#piping-objects-to-functions). When you provide multiple script blocks to the **Process** parameter, the first script block is always mapped to the `begin` block. If there are only two script blocks, the second block is mapped to the `process` block. If there are three or more script blocks, first script block is always mapped to the `begin` block, the last block is mapped to the `end` block, and the middle blocks are mapped to the `process` block. ```yaml Type: System.Management.Automation.ScriptBlock[] Parameter Sets: ScriptBlockSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RemainingScripts Specifies all script blocks that aren't taken by the **Process** parameter. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.ScriptBlock[] Parameter Sets: ScriptBlockSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ThrottleLimit Specifies the number of script blocks that run in parallel. Input objects are blocked until the running script block count falls below the **ThrottleLimit**. The default value is `5`. The ThrottleLimit parameter limits the number of parallel scripts running during each instance of `ForEach-Object -Parallel`. It doesn't limit the number of jobs that can be created when using the **AsJob** parameter. Since jobs themselves run concurrently, it's possible to create a number of parallel jobs, each running up to the throttle limit number of concurrent scriptblocks. This parameter was introduced in PowerShell 7.0. ```yaml Type: System.Int32 Parameter Sets: ParallelParameterSet Aliases: Required: False Position: Named Default value: 5 Accept pipeline input: False Accept wildcard characters: False ``` ### -TimeoutSeconds Specifies the number of seconds to wait for all input to be processed in parallel. After the specified timeout time, all running scripts are stopped. And any remaining input objects to be processed are ignored. Default value of `0` disables the timeout, and `ForEach-Object -Parallel` can run indefinitely. Typing <kbd>Ctrl</kbd>+<kbd>C</kbd> at the command line stops a running `ForEach-Object -Parallel` command. This parameter can't be used along with the **AsJob** parameter. This parameter was introduced in PowerShell 7.0. ```yaml Type: System.Int32 Parameter Sets: ParallelParameterSet Aliases: Required: False Position: Named Default value: 0 Accept pipeline input: False Accept wildcard characters: False ``` ### -UseNewRunspace Causes the parallel invocation to create a new runspace for every loop iteration instead of reusing runspaces from the runspace pool. This parameter was introduced in PowerShell 7.1 ```yaml Type: SwitchParameter Parameter Sets: ParallelParameterSet Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSObject This cmdlet returns objects that are determined by the input. ## NOTES PowerShell includes the following aliases for `ForEach-Object`: - All Platforms: - `%` - `foreach` The `ForEach-Object` cmdlet works much like the `foreach` statement, except that you can't pipe input to a `foreach` statement. For more information about the `foreach` statement, see [about_Foreach](./About/about_Foreach.md). Starting in PowerShell 4.0, `Where` and `ForEach` methods were added for use with collections. You can read more about these new methods here [about_Arrays](./About/about_Arrays.md) Using `ForEach-Object -Parallel`: - `ForEach-Object -Parallel` runs each script block in a new runspace. The new runspaces create significantly more overhead than running `ForEach-Object` with sequential processing. It's important to use **Parallel** where the overhead of running in parallel is small compared to work the script block performs. For example: - Compute intensive scripts on multi-core machines - Scripts that spend time waiting for results or doing file operations Using the **Parallel** parameter can cause scripts to run much slower than normal. Especially if the parallel scripts are trivial. Experiment with **Parallel** to discover where it can be beneficial. - When running in parallel, objects decorated with **ScriptProperties** or **ScriptMethods** can't be guaranteed to function correctly if they're run in a different runspace than the scripts were originally attached to them. Scriptblock invocation always attempts to run in its _home_ runspace, regardless of where it's actually invoked. However, `ForEach-Object -Parallel` creates temporary runspaces that get deleted after use, so there's no runspace for the scripts to execute in anymore. This behavior can work as long as the _home_ runspace still exists. However, you may not get the desired result if the script is dependent on external variables that are only present in the caller's runspace and not the _home_ runspace. - Non-terminating errors are written to the cmdlet error stream as they occur in parallel running scriptblocks. Because parallel scriptblock execution order is non-deterministic, the order in which errors appear in the error stream is random. Likewise, messages written to other data streams, like warning, verbose, or information are written to those data streams in an indeterminate order. Terminating errors, such as exceptions, terminate the individual parallel instance of the scriptblocks in which they occur. A terminating error in one scriptblocks may not cause the termination of the `ForEach-Object` cmdlet. The other scriptblocks, running in parallel, continue to run unless they also encounter a terminating error. The terminating error is written to the error data stream as an **ErrorRecord** with a **FullyQualifiedErrorId** of `PSTaskException`. Terminating errors can be converted to non-terminating errors using PowerShell `try`/`catch` or `trap` blocks. - [PipelineVariable](About/about_CommonParameters.md) common parameter variables are _not_ supported in parallel scenarios even with the `Using:` scope modifier. > [!IMPORTANT] > The `ForEach-Object -Parallel` parameter set runs script blocks in parallel on separate process > threads. The `Using:` modifier allows passing variable references from the cmdlet invocation > thread to each running script block thread. Since the script blocks run in different threads, > the object variables passed by reference must be used safely. Generally it's safe to read from > referenced objects that don't change. If you need to modify the object state then you must > use thread safe objects, such as .NET **System.Collection.Concurrent** types (See Example 14). ## RELATED LINKS [Compare-Object](../Microsoft.PowerShell.Utility/Compare-Object.md) [Where-Object](Where-Object.md) [Group-Object](../Microsoft.PowerShell.Utility/Group-Object.md) [Measure-Object](../Microsoft.PowerShell.Utility/Measure-Object.md) [New-Object](../Microsoft.PowerShell.Utility/New-Object.md) [Select-Object](../Microsoft.PowerShell.Utility/Select-Object.md) [Sort-Object](../Microsoft.PowerShell.Utility/Sort-Object.md) [Tee-Object](../Microsoft.PowerShell.Utility/Tee-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Get-Command.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 01/17/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/get-command?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Command --- # Get-Command ## SYNOPSIS Gets all commands. ## SYNTAX ### CmdletSet (Default) ``` Get-Command [[-ArgumentList] <Object[]>] [-Verb <string[]>] [-Noun <string[]>] [-Module <string[]>] [-ExcludeModule <string[]>] [-FullyQualifiedModule <ModuleSpecification[]>] [-TotalCount <int>] [-Syntax] [-ShowCommandInfo] [-All] [-ListImported] [-ParameterName <string[]>] [-ParameterType <PSTypeName[]>] [<CommonParameters>] ``` ### AllCommandSet ``` Get-Command [[-Name] <string[]>] [[-ArgumentList] <Object[]>] [-Module <string[]>] [-ExcludeModule <string[]>] [-FullyQualifiedModule <ModuleSpecification[]>] [-CommandType <CommandTypes>] [-TotalCount <int>] [-Syntax] [-ShowCommandInfo] [-All] [-ListImported] [-ParameterName <string[]>] [-ParameterType <PSTypeName[]>] [-UseFuzzyMatching] [-FuzzyMinimumDistance <uint>] [-UseAbbreviationExpansion] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Command` cmdlet gets all commands that are installed on the computer, including cmdlets, aliases, functions, filters, scripts, and applications. `Get-Command` gets the commands from PowerShell modules and commands that were imported from other sessions. To get only commands that have been imported into the current session, use the **ListImported** parameter. Without parameters, `Get-Command` gets all the cmdlets, functions, and aliases installed on the computer. `Get-Command *` gets all types of commands, including all the non-PowerShell files in the PATH environment variable (`$Env:PATH`), which it lists in the Application command type. `Get-Command` that uses the exact name of the command, without wildcard characters, automatically imports the module that contains the command so that you can use the command immediately. To enable, disable, and configure automatic importing of modules, use the `$PSModuleAutoLoadingPreference` preference variable. For more information, see [about_Preference_Variables](About/about_Preference_Variables.md). `Get-Command` gets its data directly from the command code, unlike `Get-Help`, which gets its information from help topics. Starting in Windows PowerShell 5.0, results of the `Get-Command` cmdlet display a **Version** column by default. A new **Version** property has been added to the **CommandInfo** class. ## EXAMPLES ### Example 1: Get cmdlets, functions, and aliases This command gets the PowerShell cmdlets, functions, and aliases that are installed on the computer. ```powershell Get-Command ``` ### Example 2: Get commands in the current session This command uses the **ListImported** parameter to get only the commands in the current session. ```powershell Get-Command -ListImported ``` ### Example 3: Get cmdlets and display them in order This command gets all the cmdlets, sorts them alphabetically by the noun in the cmdlet name, and then displays them in noun-based groups. This display can help you find the cmdlets for a task. ```powershell Get-Command -Type Cmdlet | Sort-Object -Property Noun | Format-Table -GroupBy Noun ``` ### Example 4: Get commands in a module This command uses the **Module** parameter to get the commands in the Microsoft.PowerShell.Security and Microsoft.PowerShell.Utility modules. ```powershell Get-Command -Module Microsoft.PowerShell.Security, Microsoft.PowerShell.Utility ``` ### Example 5: Get information about a cmdlet This command gets information about the `Get-AppLockerPolicy` cmdlet. It also imports the **AppLocker** module, which adds all the commands in the **AppLocker** module to the current session. ```powershell Get-Command Get-AppLockerPolicy ``` When a module is imported automatically, the effect is the same as using the Import-Module cmdlet. The module can add commands, types and formatting files, and run scripts in the session. To enable, disable, and configuration automatic importing of modules, use the `$PSModuleAutoLoadingPreference` preference variable. For more information, see [about_Preference_Variables](../Microsoft.PowerShell.Core/About/about_Preference_Variables.md). ### Example 6: Get the syntax of a cmdlet This command uses the **ArgumentList** and **Syntax** parameters to get the syntax of the `Get-ChildItem` cmdlet when it's used in the Cert: drive. The Cert: drive is a PowerShell drive that the Certificate Provider adds to the session. ```powershell Get-Command -Name Get-ChildItem -Args Cert: -Syntax ``` When you compare the syntax displayed in the output with the syntax that's displayed when you omit the **Args** (**ArgumentList**) parameter, you'll see that the **Certificate provider** adds a dynamic parameter, **CodeSigningCert**, to the `Get-ChildItem` cmdlet. For more information about the Certificate provider, see [about_Certificate_Provider](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md). ### Example 7: Get dynamic parameters The command in the example uses the `Get-DynamicParameters` function to get the dynamic parameters that the Certificate provider adds to the `Get-ChildItem` cmdlet when it's used in the Cert: drive. ```powershell function Get-DynamicParameters { param ($Cmdlet, $PSDrive) (Get-Command -Name $Cmdlet -ArgumentList $PSDrive).ParameterSets | ForEach-Object {$_.Parameters} | Where-Object { $_.IsDynamic } | Select-Object -Property Name -Unique } Get-DynamicParameters -Cmdlet Get-ChildItem -PSDrive Cert: ``` ```Output Name ---- CodeSigningCert ``` The `Get-DynamicParameters` function in this example gets the dynamic parameters of a cmdlet. This is an alternative to the method used in the previous example. Dynamic parameter can be added to a cmdlet by another cmdlet or a provider. ### Example 8: Get all commands of all types This command gets all commands of all types on the local computer, including executable files in the paths of the **PATH** environment variable (`$Env:PATH`). ```powershell Get-Command * ``` It returns an **ApplicationInfo** object (System.Management.Automation.ApplicationInfo) for each file, not a **FileInfo** object (System.IO.FileInfo). ### Example 9: Get cmdlets by using a parameter name and type This command gets cmdlets that have a parameter whose name includes Auth and whose type is **AuthenticationMechanism**. ```powershell Get-Command -ParameterName *Auth* -ParameterType AuthenticationMechanism ``` You can use a command like this one to find cmdlets that let you specify the method that's used to authenticate the user. The **ParameterType** parameter distinguishes parameters that take an **AuthenticationMechanism** value from those that take an **AuthenticationLevel** parameter, even when they have similar names. ### Example 10: Get an alias This example shows how to use the `Get-Command` cmdlet with an alias. ```powershell Get-Command -Name dir ``` ```Output CommandType Name ModuleName ----------- ---- ---------- Alias dir -> Get-ChildItem ``` Although it's typically used on cmdlets and functions, `Get-Command` also gets scripts, functions, aliases, and executable files. The output of the command shows the special view of the **Name** property value for aliases. The view shows the alias and the full command name. ### Example 11: Get Syntax from an alias This example shows how to get the syntax along with the standard name of an alias. The output of the command shows the labeled alias with the standard name, followed by the syntax. ```powershell Get-Command -Name dir -Syntax ``` ```Output dir (alias) -> Get-ChildItem dir [[-Path] <string[]>] [[-Filter] <string>] [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-Depth <uint>] [-Force] [-Name] [-Attributes <FlagsExpression[FileAttributes]>] [-FollowSymlink] [-Directory] [-File] [-Hidden] [-ReadOnly] [-System] [<CommonParameters>] dir [[-Filter] <string>] -LiteralPath <string[]> [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-Depth <uint>] [-Force] [-Name] [-Attributes <FlagsExpression[FileAttributes]>] [-FollowSymlink] [-Directory] [-File] [-Hidden] [-ReadOnly] [-System] [<CommonParameters>] ``` ### Example 12: Get all instances of the Notepad command This example uses the **All** parameter of the `Get-Command` cmdlet to show all instances of the `Notepad` command on the local computer. ```powershell Get-Command Notepad -All | Format-Table CommandType, Name, Definition ``` ```Output CommandType Name Definition ----------- ---- ---------- Application notepad.exe C:\WINDOWS\system32\notepad.exe Application NOTEPAD.EXE C:\WINDOWS\NOTEPAD.EXE ``` The **All** parameter is useful when there is more than one command with the same name in the session. Beginning in Windows PowerShell 3.0, by default, when the session includes multiple commands with the same name, `Get-Command` gets only the command that runs when you type the command name. With the **All** parameter, `Get-Command` gets all commands with the specified name and returns them in execution precedence order. To run a command other than the first one in the list, type the fully qualified path to the command. For more information about command precedence, see [about_Command_Precedence](About/about_Command_Precedence.md). ### Example 13: Get the name of a module that contains a cmdlet This command gets the name of the module in which the `Get-Date` cmdlet originated. The command uses the **ModuleName** property of all commands. ```powershell (Get-Command Get-Date).ModuleName ``` ```Output Microsoft.PowerShell.Utility ``` This command format works on commands in PowerShell modules, even if they're not imported into the session. ### Example 14: Get cmdlets and functions that have an output type ```powershell Get-Command -Type Cmdlet | Where-Object OutputType | Format-List -Property Name, OutputType ``` This command gets the cmdlets and functions that have an output type and the type of objects that they return. The first part of the command gets all cmdlets. A pipeline operator (`|`) sends the cmdlets to the `Where-Object` cmdlet, which selects only the ones in which the **OutputType** property is populated. Another pipeline operator sends the selected cmdlet objects to the `Format-List` cmdlet, which displays the name and output type of each cmdlet in a list. The **OutputType** property of a **CommandInfo** object has a non-null value only when the cmdlet code defines the **OutputType** attribute for the cmdlet. ### Example 15: Get cmdlets that take a specific object type as input ```powershell Get-Command -ParameterType (((Get-NetAdapter)[0]).pstypenames) ``` ```Output CommandType Name ModuleName ----------- ---- ---------- Function Disable-NetAdapter NetAdapter Function Enable-NetAdapter NetAdapter Function Rename-NetAdapter NetAdapter Function Restart-NetAdapter NetAdapter Function Set-NetAdapter NetAdapter ``` This command finds cmdlets that take net adapter objects as input. You can use this command format to find the cmdlets that accept the type of objects that any command returns. The command uses the **pstypenames** intrinsic property of all objects, which gets the types that describe the object. To get the **pstypenames** property of a net adapter, and not the **pstypenames** property of a collection of net adapters, the command uses array notation to get the first net adapter that the cmdlet returns. ### Example 16: Get commands using a fuzzy match In this example, the name of the command deliberately has a typo as 'get-commnd'. Using the `-UseFuzzyMatching` switch, the cmdlet determined that the best match was `Get-Command` followed by other native commands on the system that were a similar match. ```powershell Get-Command get-commnd -UseFuzzyMatching ``` ```Output CommandType Name Version Source ----------- ---- ------- ------ Cmdlet Get-Command 6.2.0.0 Microsoft.PowerShell.Core Application getconf 0.0.0.0 /usr/bin/getconf Application command 0.0.0.0 /usr/bin/command ``` ### Example 17: Exclude modules from the search for commands The following example shows the difference in results of searching for commands in all modules and when you exclude a specific module. ```powershell PS> (Get-Command *-*Disk*).Count 73 PS> (Get-Command *-*Disk* -ExcludeModule Storage).Count 35 ``` ## PARAMETERS ### -All Indicates that this cmdlet gets all commands, including commands of the same type that have the same name. By default, `Get-Command` gets only the commands that run when you type the command name. For more information about the order that PowerShell searches for commands, see [about_Command_Precedence](About/about_Command_Precedence.md). For information about module-qualified command names and running commands that don't run by default because of a name conflict, see [about_Modules](About/about_Modules.md). This parameter was introduced in Windows PowerShell 3.0. In Windows PowerShell 2.0, `Get-Command` gets all commands by default. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ArgumentList Specifies an array of arguments. This cmdlet gets information about a cmdlet or function when it's used with the specified parameters ("arguments"). The alias for **ArgumentList** is **Args**. To detect dynamic parameters that are available only when certain other parameters are used, set the value of **ArgumentList** to the parameters that trigger the dynamic parameters. To detect the dynamic parameters that a provider adds to a cmdlet, set the value of the **ArgumentList** parameter to a path in the provider drive, such as `WSMan:`, `HKLM:`, or `Cert:`. When the command is a PowerShell provider cmdlet, enter only one path in each command. The provider cmdlets return only the dynamic parameters for the first path the value of **ArgumentList**. For information about the provider cmdlets, see [about_Providers](About/about_Providers.md). ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Args Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CommandType Specifies the types of commands that this cmdlet gets. Enter one or more command types. Use **CommandType** or its alias, **Type**. By default, `Get-Command` gets all cmdlets, functions, and aliases. The acceptable values for this parameter are: - `Alias`: Gets the aliases of all PowerShell commands. For more information, see [about_Aliases](About/about_Aliases.md). - `All`: Gets all command types. This parameter value is the equivalent of `Get-Command *`. - `Application`: Searches folders in the `$Env:PATH` environment variable for non-PowerShell executable files. On Windows, executable files have a file extension that is listed in the `$Env:PATHEXT` environment variable. For more information, see [about_Environment_Variables](About/about_Environment_Variables.md). - `Cmdlet`: Gets all cmdlets. - `ExternalScript`: Gets all `.ps1` files in the paths listed in the **PATH** environment variable (`$Env:PATH`). - `Filter` and `Function`: Gets all PowerShell advanced and simple functions and filters. - `Script`: Gets all script blocks. To get PowerShell scripts (`.ps1` files), use the `ExternalScript` value. These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **CommandType** parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. ```yaml Type: System.Management.Automation.CommandTypes Parameter Sets: AllCommandSet Aliases: Type Accepted values: Alias, Function, Filter, Cmdlet, ExternalScript, Application, Script, Workflow, Configuration, All Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### ExcludeModule Specify the name of one or more modules to be excluded from the search. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: ByValue (False), ByName (False) Accept wildcard characters: False ``` ### -FullyQualifiedModule The value can be a module name, a full module specification, or a path to a module file. When the value is a path, the path can be fully qualified or relative. A relative path is resolved relative to the script that contains the using statement. When the value is a name or module specification, PowerShell searches the **PSModulePath** for the specified module. A module specification is a hashtable that has the following keys. - `ModuleName` - **Required** Specifies the module name. - `GUID` - **Optional** Specifies the GUID of the module. - It's also **Required** to specify at least one of the three below keys. - `ModuleVersion` - Specifies a minimum acceptable version of the module. - `MaximumVersion` - Specifies the maximum acceptable version of the module. - `RequiredVersion` - Specifies an exact, required version of the module. This can't be used with the other Version keys. You can't specify the **FullyQualifiedModule** parameter in the same command as a **Module** parameter. The two parameters are mutually exclusive. ```yaml Type: Microsoft.PowerShell.Commands.ModuleSpecification[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -FuzzyMinimumDistance This parameter allows filtering fuzzy results to be more or less accurate. The distance is calculated using the Damerau Levenshtein Distance algorithm, which indicates how many steps is the match from the original value. A lower distance is more accurate. A distance of zero is an exact match. ```yaml Type: UInt32 Parameter Sets: AllCommandSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ListImported Indicates that this cmdlet gets only commands in the current session. Starting in PowerShell 3.0, by default, `Get-Command` gets all installed commands, including, but not limited to, the commands in the current session. In PowerShell 2.0, it gets only commands in the current session. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Module Specifies an array of modules. This cmdlet gets the commands that came from the specified modules. Enter the names of modules or module objects. This parameter takes string values, but the value of this parameter can also be a **PSModuleInfo** object, such as the objects that the `Get-Module` and `Import-PSSession` cmdlets return. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: PSSnapin Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Name Specifies an array of names. This cmdlet gets only commands that have the specified name. Enter a name or name pattern. Wildcard characters are permitted. To get commands that have the same name, use the **All** parameter. When two commands have the same name, by default, `Get-Command` gets the command that runs when you type the command name. ```yaml Type: System.String[] Parameter Sets: AllCommandSet Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Noun Specifies an array of command nouns. This cmdlet gets commands, which include cmdlets, functions, and aliases, that have names that include the specified noun. Enter one or more nouns or noun patterns. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: CmdletSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -ParameterName Specifies an array of parameter names. This cmdlet gets commands in the session that have the specified parameters. Enter parameter names or parameter aliases. Wildcard characters are supported. The **ParameterName** and **ParameterType** parameters search only commands in the current session. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -ParameterType Specifies an array of parameter names. This cmdlet gets commands in the session that have parameters of the specified type. Enter the full name or partial name of a parameter type. Wildcard characters are supported. The **ParameterName** and **ParameterType** parameters search only commands in the current session. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.PSTypeName[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -ShowCommandInfo Indicates that this cmdlet displays command information. This parameter was introduced in Windows PowerShell 5.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Syntax Indicates that this cmdlet gets only the following specified data about the command: - Aliases. Gets the standard name. - Cmdlets. Gets the syntax. - Functions and filters. Gets the function definition. - Scripts and applications or files. Gets the path and filename. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -TotalCount Specifies the number of commands to get. You can use this parameter to limit the output of a command. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -UseAbbreviationExpansion Indicates using matching of the characters in the command to find with uppercase characters in a command. For example, `i-psdf` would match `Import-PowerShellDataFile` as each of the characters to find matches an uppercase character in the result. When using this type of match, any wildcards will result in no matches. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: AllCommandSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -UseFuzzyMatching Indicates using a fuzzy matching algorithm when finding commands. The order of the output is from closest match to least likely match. Wildcards shouldn't be used with fuzzy matching as it will attempt to match commands that may contain those wildcard characters. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: AllCommandSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Verb Specifies an array of command verbs. This cmdlet gets commands, which include cmdlets, functions, and aliases, that have names that include the specified verb. Enter one or more verbs or verb patterns. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: CmdletSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe command names to this cmdlet. ## OUTPUTS ### System.Management.Automation.CommandInfo This cmdlet returns objects derived from the **CommandInfo** class. The type of object that's returned depends on the type of command that `Get-Command` gets. ### System.Management.Automation.AliasInfo Represents aliases. ### System.Management.Automation.ApplicationInfo Represents applications and files. ### System.Management.Automation.CmdletInfo Represents cmdlets. ### System.Management.Automation.FunctionInfo Represents functions and filters. ## NOTES PowerShell includes the following aliases for `Get-Command`: - All platforms: - `gcm` - When more than one command that has the same name is available to the session, `Get-Command` returns the command that runs when you type the command name. To get commands that have the same name, listed in run order, use the **All** parameter. For more information, see [about_Command_Precedence](../Microsoft.PowerShell.Core/About/about_Command_Precedence.md). - When a module is imported automatically, the effect is the same as using the `Import-Module` cmdlet. The module can add commands, types and formatting files, and run scripts in the session. To enable, disable, and configuration automatic importing of modules, use the `$PSModuleAutoLoadingPreference` preference variable. For more information, see [about_Preference_Variables](../Microsoft.PowerShell.Core/About/about_Preference_Variables.md). ## RELATED LINKS [Export-PSSession](../Microsoft.PowerShell.Utility/Export-PSSession.md) [Get-Help](Get-Help.md) [Get-Member](../Microsoft.PowerShell.Utility/Get-Member.md) [Get-PSDrive](../Microsoft.PowerShell.Management/Get-PSDrive.md) [Import-PSSession](../Microsoft.PowerShell.Utility/Import-PSSession.md) [about_Command_Precedence](About/about_Command_Precedence.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Get-ExperimentalFeature.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/04/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/get-experimentalfeature?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-ExperimentalFeature --- # Get-ExperimentalFeature ## SYNOPSIS Gets experimental features. ## SYNTAX ``` Get-ExperimentalFeature [[-Name] <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-ExperimentalFeature` cmdlet returns all experimental features discovered by PowerShell. Experimental features can come from modules or the PowerShell engine. Experimental features allow users to safely test new features and provide feedback (typically via GitHub) before the design is considered complete and any changes can become a breaking change. ## EXAMPLES ### Example 1 Gets the list of currently registered experimental features and their current state. ```powershell Get-ExperimentalFeature ``` ```Output Name Enabled Source Description ---- ------- ------ ----------- PSImplicitRemotingBatching False PSEngine Batch implicit remoting proxy commands to improve performance ``` ## PARAMETERS ### -Name Name or names of specific experimental features to return. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String[] You can pipe a string containing the name of an experimental feature to this cmdlet. ## OUTPUTS ### System.Management.Automation.ExperimentalFeature This cmdlet returns instances that match the requested names or all experimental features if no name is specified. ## RELATED LINKS [Disable-ExperimentalFeature](Disable-ExperimentalFeature.md) [Enable-ExperimentalFeature](Enable-ExperimentalFeature.md) [about_Experimental_Features](/powershell/module/microsoft.powershell.core/about/about_experimental_features) [Using Experimental Features](/powershell/scripting/learn/experimental-features)

#File: reference/7.6/Microsoft.PowerShell.Core/Get-Help.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 01/10/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/get-help?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Help --- # Get-Help ## SYNOPSIS Displays information about PowerShell commands and concepts. ## SYNTAX ### AllUsersView (Default) ``` Get-Help [[-Name] <String>] [-Path <String>] [-Category <String[]>] [-Full] [-Component <String[]>] [-Functionality <String[]>] [-Role <String[]>] [<CommonParameters>] ``` ### DetailedView ``` Get-Help [[-Name] <String>] [-Path <String>] [-Category <String[]>] -Detailed [-Component <String[]>] [-Functionality <String[]>] [-Role <String[]>] [<CommonParameters>] ``` ### EXAMPLES ``` Get-Help [[-Name] <String>] [-Path <String>] [-Category <String[]>] -Examples [-Component <String[]>] [-Functionality <String[]>] [-Role <String[]>] [<CommonParameters>] ``` ### PARAMETERS ``` Get-Help [[-Name] <String>] [-Path <String>] [-Category <String[]>] -Parameter <String[]> [-Component <String[]>] [-Functionality <String[]>] [-Role <String[]>] [<CommonParameters>] ``` ### Online ``` Get-Help [[-Name] <String>] [-Path <String>] [-Category <String[]>] [-Component <String[]>] [-Functionality <String[]>] [-Role <String[]>] -Online [<CommonParameters>] ``` ### ShowWindow ``` Get-Help [[-Name] <String>] [-Path <String>] [-Category <String[]>] [-Component <String[]>] [-Functionality <String[]>] [-Role <String[]>] -ShowWindow [<CommonParameters>] ``` ## DESCRIPTION The `Get-Help` cmdlet displays information about PowerShell concepts and commands, including cmdlets, functions, Common Information Model (CIM) commands, workflows, providers, aliases, and scripts. To get help for a PowerShell cmdlet, type `Get-Help` followed by the cmdlet name, such as: `Get-Help Get-Process`. Conceptual help articles in PowerShell begin with **about_**, such as **about_Comparison_Operators**. To see all **about_** articles, type `Get-Help about_*`. To see a particular article, type `Get-Help about_<article-name>`, such as `Get-Help about_Comparison_Operators`. To get help for a PowerShell provider, type `Get-Help` followed by the provider name. For example, to get help for the Certificate provider, type `Get-Help Certificate`. You can also type `help` or `man`, which displays one screen of text at a time. Or, `<cmdlet-name> -?`, that's identical to `Get-Help`, but only works for cmdlets. `Get-Help` gets the help content that it displays from help files on your computer. Without the help files, `Get-Help` displays only basic information about cmdlets. Some PowerShell modules include help files. Beginning in PowerShell 3.0, the modules that come with the Windows operating system don't include help files. To download or update the help files for a module in PowerShell 3.0, use the `Update-Help` cmdlet. You can also view the PowerShell help documents online. To get the online version of a help file, use the **Online** parameter, such as: `Get-Help Get-Process -Online`. If you type `Get-Help` followed by the exact name of a help article, or by a word unique to a help article, `Get-Help` displays the article's content. If you specify the exact name of a command alias, `Get-Help` displays the help for the original command. If you enter a word or word pattern that appears in several help article titles, `Get-Help` displays a list of the matching titles. If you enter any text that doesn't appear in any help article titles, `Get-Help` displays a list of articles that include that text in their contents. `Get-Help` can get help articles for all supported languages and locales. `Get-Help` first looks for help files in the locale set for Windows, then in the parent locale, such as **pt** for **pt-BR**, and then in a fallback locale. Beginning in PowerShell 3.0, if `Get-Help` doesn't find help in the fallback locale, it looks for help articles in English, **en-US**, before it returns an error message or displaying autogenerated help. For information about the symbols that `Get-Help` displays in the command syntax diagram, see [about_Command_Syntax](./About/about_Command_Syntax.md). For information about parameter attributes, such as **Required** and **Position**, see [about_Parameters](./About/about_Parameters.md). > [!NOTE] > In PowerShell 3.0 and PowerShell 4.0, `Get-Help` can't find **About** articles in modules unless > the module is imported into the current session. To get **About** articles in a module, import the > module using the `Import-Module` cmdlet or by running a cmdlet that's included in the module. Beginning with **PSReadLine** v2.2.2, the module ships with two functions that provide quick access to help while you are typing a command on the command line. The help is displayed in the terminal in an alternate screen buffer with paging. When you hit the <kbd>F1</kbd> key, the **PSReadLine** `ShowCommandHelp` function invokes `Get-Help -Full` for the cmdlet name closest to the left of the cursor. When the cursor is immediately to the left of a parameter, the function jumps to that parameter's description in the full help topic. When you hit <kbd>Q</kbd> to exit the help view, you are returned to the command line at the same cursor position so you can continue typing the command. When you use the key combination <kbd>Alt</kbd>+<kbd>h</kbd>, the **PSReadLine** `ShowParameterHelp` function displays help information for the parameter immediately to the left of the cursor. The help text is displayed below the command line. This allows you to see the description of the parameter and continue typing your command. For more information, see [Using dynamic help](/powershell/scripting/learn/shell/dynamic-help). ## EXAMPLES ### Example 1: Display basic help information about a cmdlet These examples display basic help information about the `Format-Table` cmdlet. ```powershell Get-Help Format-Table Get-Help -Name Format-Table Format-Table -? ``` `Get-Help <cmdlet-name>` is the simplest and default syntax of `Get-Help` cmdlet. You can omit the **Name** parameter. The syntax `<cmdlet-name> -?` works only for cmdlets. ### Example 2: Display basic information one page at a time These examples display basic help information about the `Format-Table` cmdlet one page at a time. ```powershell help Format-Table man Format-Table Get-Help Format-Table | Out-Host -Paging ``` `help` is a function that runs `Get-Help` cmdlet internally and displays the result one page at a time. `man` is an alias for the `help` function. `Get-Help Format-Table` sends the object down the pipeline. `Out-Host -Paging` receives the output from the pipeline and displays it one page at a time. For more information, see [Out-Host](Out-Host.md). ### Example 3: Display more information for a cmdlet These examples display more detailed help information about the `Format-Table` cmdlet. ```powershell Get-Help Format-Table -Detailed Get-Help Format-Table -Full ``` The **Detailed** parameter displays the help article's detailed view that includes parameter descriptions and examples. The **Full** parameter displays the help article's full view that includes parameter descriptions, examples, input and output object types, and additional notes. The **Detailed** and **Full** parameters are effective only for the commands that have help files installed on the computer. The parameters aren't effective for the conceptual (**about_**) help articles. ### Example 4: Display selected parts of a cmdlet by using parameters These examples display selected portions of the `Format-Table` cmdlet help. ```powershell Get-Help Format-Table -Examples Get-Help Format-Table -Parameter * Get-Help Format-Table -Parameter GroupBy ``` The **Examples** parameter displays the help file's **NAME** and **SYNOPSIS** sections, and all the Examples. You can't specify an Example number because the **Examples** parameter is a switch parameter. The **Parameter** parameter displays only the descriptions of the specified parameters. If you specify only the asterisk (`*`) wildcard character, it displays the descriptions of all parameters. When **Parameter** specifies a parameter name such as **GroupBy**, information about that parameter is shown. These parameters aren't effective for the conceptual (**about_**) help articles. ### Example 5: Display online version of help This example displays the online version of the help article for the `Format-Table` cmdlet in your default web browser. ```powershell Get-Help Format-Table -Online ``` ### Example 6: Display help about the help system The `Get-Help` cmdlet without parameters displays information about the PowerShell help system. ```powershell Get-Help ``` ### Example 7: Display available help articles This example displays a list of all help articles available on your computer. ```powershell Get-Help * ``` ### Example 8: Display a list of conceptual articles This example displays a list of the conceptual articles included in PowerShell help. All these articles begin with the characters **about_**. To display a particular help file, type `Get-Help \<about_article-name\>`, for example, `Get-Help about_Signing`. Only the conceptual articles that have help files installed on your computer are displayed. For information about downloading and installing help files in PowerShell 3.0, see [Update-Help](Update-Help.md). ```powershell Get-Help about_* ``` ### Example 9: Search for a word in cmdlet help This example shows how to search for a word in a cmdlet help article. ```powershell Get-Help Add-Member -Full | Out-String -Stream | Select-String -Pattern Clixml ``` ```Output the Export-Clixml cmdlet to save the instance of the object, including the additional members... can use the Import-Clixml cmdlet to re-create the instance of the object from the information... Export-Clixml Import-Clixml ``` `Get-Help` uses the **Full** parameter to get help information for `Add-Member`. The **MamlCommandHelpInfo** object is sent down the pipeline. `Out-String` uses the **Stream** parameter to convert the object into a string. `Select-String` uses the **Pattern** parameter to search the string for **Clixml**. ### Example 10: Display a list of articles that include a word This example displays a list of articles that include the word **remoting**. When you enter a word that doesn't appear in any article title, `Get-Help` displays a list of articles that include that word. ```powershell Get-Help -Name remoting ``` ```Output Name Category Module Synopsis ---- -------- ------ -------- Install-PowerShellRemoting.ps1 External Install-PowerShellRemoting.ps1 Disable-PSRemoting Cmdlet Microsoft.PowerShell.Core Prevents remote users... Enable-PSRemoting Cmdlet Microsoft.PowerShell.Core Configures the computer... ``` ### Example 11: Display provider-specific help This example shows two ways of getting the provider-specific help for `Get-Item`. These commands get help that explains how to use the `Get-Item` cmdlet in the PowerShell SQL Server provider's **DataCollection** node. The first example uses the `Get-Help` **Path** parameter to specify the SQL Server provider's path. Because the provider's path is specified, you can run the command from any path location. The second example uses `Set-Location` to navigate to the SQL Server provider's path. From that location, the **Path** parameter isn't needed for `Get-Help` to get the provider-specific help. ```powershell Get-Help Get-Item -Path SQLSERVER:\DataCollection ``` ```Output NAME Get-Item SYNOPSIS Gets a collection of Server objects for the local computer and any computers to which you have made a SQL Server PowerShell connection. ... ``` ```powershell Set-Location SQLSERVER:\DataCollection SQLSERVER:\DataCollection> Get-Help Get-Item ``` ```Output NAME Get-Item SYNOPSIS Gets a collection of Server objects for the local computer and any computers to which you have made a SQL Server PowerShell connection. ... ``` ### Example 12: Display help for a script This example gets help for the `MyScript.ps1 script`. For information about how to write help for your functions and scripts, see [about_Comment_Based_Help](./About/about_Comment_Based_Help.md). ```powershell Get-Help -Name C:\PS-Test\MyScript.ps1 ``` ## PARAMETERS ### -Category Displays help only for items in the specified category and their aliases. Conceptual articles are in the **HelpFile** category. The acceptable values for this parameter are as follows: - Alias - Cmdlet - Provider - General - FAQ - Glossary - HelpFile - ScriptCommand - Function - Filter - ExternalScript - All - DefaultHelp - Workflow - DscResource - Class - Configuration ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Accepted values: Alias, Cmdlet, Provider, General, FAQ, Glossary, HelpFile, ScriptCommand, Function, Filter, ExternalScript, All, DefaultHelp, Workflow, DscResource, Class, Configuration Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Component Displays commands with the specified component value, such as **Exchange**. Enter a component name. Wildcard characters are permitted. This parameter has no effect on displays of conceptual (**About_**) help. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Detailed Adds parameter descriptions and examples to the basic help display. This parameter is effective only when the help files are installed on the computer. It has no effect on displays of conceptual (**About_**) help. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: DetailedView Aliases: Required: True Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Examples Displays only the name, synopsis, and examples. This parameter is effective only when the help files are installed on the computer. It has no effect on displays of conceptual (**About_**) help. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Examples Aliases: Required: True Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Full Displays the entire help article for a cmdlet. **Full** includes parameter descriptions and attributes, examples, input and output object types, and additional notes. This parameter is effective only when the help files are installed on the computer. It has no effect on displays of conceptual (**About_**) help. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: AllUsersView Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Functionality Displays help for items with the specified functionality. Enter the functionality. Wildcard characters are permitted. This parameter has no effect on displays of conceptual (**About_**) help. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Name Gets help about the specified command or concept. Enter the name of a cmdlet, function, provider, script, or workflow, such as `Get-Member`, a conceptual article name, such as `about_Objects`, or an alias, such as `ls`. Wildcard characters are permitted in cmdlet and provider names, but you can't use wildcard characters to find the names of function help and script help articles. To get help for a script that isn't located in a path that's listed in the `$Env:PATH` environment variable, type the script's path and file name. If you enter the exact name of a help article, `Get-Help` displays the article contents. If you enter a word or word pattern that appears in several help article titles, `Get-Help` displays a list of the matching titles. If you enter any text that doesn't match any help article titles, `Get-Help` displays a list of articles that include that text in their contents. The names of conceptual articles, such as `about_Objects`, must be entered in English, even in non-English versions of PowerShell. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Online Displays the online version of a help article in the default browser. This parameter is valid only for cmdlet, function, workflow, and script help articles. You can't use the **Online** parameter with `Get-Help` in a remote session. For information about supporting this feature in help articles that you write, see [about_Comment_Based_Help](./About/about_Comment_Based_Help.md), and [Supporting Online Help](/powershell/scripting/developer/module/supporting-online-help), and [Writing Help for PowerShell Cmdlets](/powershell/scripting/developer/help/writing-help-for-windows-powershell-cmdlets). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Online Aliases: Required: True Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Parameter Displays only the detailed descriptions of the specified parameters. Wildcards are permitted. This parameter has no effect on displays of conceptual (**About_**) help. ```yaml Type: System.String[] Parameter Sets: Parameters Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Path Gets help that explains how the cmdlet works in the specified provider path. Enter a PowerShell provider path. This parameter gets a customized version of a cmdlet help article that explains how the cmdlet works in the specified PowerShell provider path. This parameter is effective only for help about a provider cmdlet and only when the provider includes a custom version of the provider cmdlet help article in its help file. To use this parameter, install the help file for the module that includes the provider. To see the custom cmdlet help for a provider path, go to the provider path location and enter a `Get-Help` command or, from any path location, use the **Path** parameter of `Get-Help` to specify the provider path. You can also find custom cmdlet help online in the provider help section of the help articles. For more information about PowerShell providers, see [about_Providers](./About/about_Providers.md). > [!NOTE] > The provider for the path specified must have a PowerShell provider help file installed. If no > provider help file is available, no help information is returned. There are no provider help files > available for the providers included with this version of PowerShell. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Role Displays help customized for the specified user role. Enter a role. Wildcard characters are permitted. Enter the role that the user plays in an organization. Some cmdlets display different text in their help files based on the value of this parameter. This parameter has no effect on help for the core cmdlets. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -ShowWindow Displays the help topic in a window for easier reading. The window includes a **Find** search feature and a **Settings** box that lets you set options for the display, including options to display only selected sections of a help topic. The **ShowWindow** parameter supports help topics for commands (cmdlets, functions, CIM commands, scripts) and conceptual **About** articles. It doesn't support provider help. This parameter was reintroduced in PowerShell 7.0. This parameter is only available on Windows. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ShowWindow Aliases: Required: True Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### ExtendedCmdletHelpInfo If you run `Get-Help` on a command that doesn't have a help file, `Get-Help` returns an **ExtendedCmdletHelpInfo** object that represents autogenerated help. ### System.String If you get a conceptual help article, `Get-Help` returns it as a string. ### MamlCommandHelpInfo If you get a command that has a help file, `Get-Help` returns a **MamlCommandHelpInfo** object. ## NOTES PowerShell 3.0 doesn't include help files. To download and install the help files that `Get-Help` reads, use the `Update-Help` cmdlet. You can use the `Update-Help` cmdlet to download and install help files for the core commands that come with PowerShell and for any modules that you install. You can also use it to update the help files so that the help on your computer is never outdated. You can also read the help articles about the commands that come with PowerShell online starting at [Getting Started with Windows PowerShell](/powershell/scripting/getting-started/getting-started-with-windows-powershell). `Get-Help` displays help in the locale set for the Windows operating system or in the fallback language for that locale. If you don't have help files for the primary or fallback locale, `Get-Help` behaves as if there are no help files on the computer. To get help for a different locale, use **Region** and **Language** in Control Panel to change the settings. On Windows 10 or higher, **Settings**, **Time & Language**. The full view of help includes a table of information about the parameters. The table includes the following fields: - **Required**. Indicates whether the parameter is required (true) or optional (false). - **Position**. Indicates whether the parameter is named or positional (numeric). Positional parameters must appear in a specified place in the command. - **Named** indicates that the parameter name is required, but that the parameter can appear anywhere in the command. - **Numeric** indicates that the parameter name is optional, but when the name is omitted, the parameter must be in the place specified by the number. For example, `2` indicates that when the parameter name is omitted, the parameter must be the second or only unnamed parameter in the command. When the parameter name is used, the parameter can appear anywhere in the command. - **Default value**. The parameter value or default behavior that PowerShell uses if you don't include the parameter in the command. - Accepts pipeline input. Indicates whether you can (true) or can't (false) send objects to the parameter through a pipeline. **By Property Name** means that the pipelined object must have a property that has the same name as the parameter name. - **Accepts wildcard characters**. Indicates whether the value of a parameter can include wildcard characters, such as an asterisk (`*`) or question mark (`?`). ## RELATED LINKS [about_Command_Syntax](About/about_Command_Syntax.md) [about_Comment_Based_Help](./About/about_Comment_Based_Help.md) [Get-Command](Get-Command.md) [Supporting Updatable Help](/powershell/scripting/developer/module/supporting-updatable-help) [Update-Help](Update-Help.md) [Writing Comment-Based Help Topics](/powershell/scripting/developer/help/writing-comment-based-help-topics) [Writing Help for PowerShell Cmdlets](/powershell/scripting/developer/help/writing-help-for-windows-powershell-cmdlets)

#File: reference/7.6/Microsoft.PowerShell.Core/Get-History.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 09/15/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/get-history?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-History --- # Get-History ## SYNOPSIS Gets a list of the commands entered during the current session. ## SYNTAX ``` Get-History [[-Id] <Int64[]>] [[-Count] <Int32>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-History` cmdlet gets the session history, that is, the list of commands entered during the current session. PowerShell automatically maintains a history of each session. The number of entries in the session history is determined by the value of the `$MaximumHistoryCount` preference variable. Beginning in Windows PowerShell 3.0, the default value is `4096`. By default, history files are saved in the home directory, but you can save the file in any location. For more information about the history features in PowerShell, see [about_History](About/about_History.md). The session history is managed separately from the history maintained by the **PSReadLine** module. Both histories are available in sessions where **PSReadLine** is loaded. This cmdlet only works with the session history. For more information see, [about_PSReadLine](../PSReadLine/About/about_PSReadLine.md). ## EXAMPLES ### Example 1: Get the session history This example gets the entries in the session history. The default display shows each command and its ID, which indicates the order in which they ran. ```powershell Get-History ``` ### Example 2: Get entries that include a string This example gets entries in the command history that include the string service. The first command gets all entries in the session history. The pipeline operator (`|`) passes the results to the `Where-Object` cmdlet, which selects only the commands that include service. ```powershell Get-History | Where-Object {$_.CommandLine -like "*Service*"} ``` ### Example 3: Export history entries up to a specific ID This example gets the five most recent history entries ending with entry 7. The pipeline operator passes the result to the `Export-Csv` cmdlet, which formats the history as comma-separated text and saves it in the History.csv file. The file includes the data that is displayed when you format the history as a list. This includes the status and start and end times of the command. ```powershell Get-History -Id 7 -Count 5 | Export-Csv -Path History.csv ``` ### Example 4: Display the most recent command This example gets the last command in the command history. The last command is the most recently entered command. This command uses the **Count** parameter to display just one command. By default, `Get-History` gets the most recent commands. This command can be abbreviated to "h -c 1" and is equivalent to pressing the up-arrow key. ```powershell Get-History -Count 1 ``` ### Example 5: Display all the properties of the entries in the history This example displays all of the properties of entries in the session history. The pipeline operator passes the results of a `Get-History` command to the `Format-List` cmdlet, which displays all of the properties of each history entry. This includes the ID, status, and start and end times of the command. ```powershell Get-History | Format-List -Property * ``` ## PARAMETERS ### -Count Specifies the number of the most recent history entries that this cmdlet gets. By, default, `Get-History` gets all entries in the session history. If you use both the **Count** and **Id** parameters in a command, the display ends with the command that is specified by the **Id** parameter. In Windows PowerShell 2.0, by default, `Get-History` gets the 32 most recent entries. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies an array of the IDs of entries in the session history. `Get-History` gets only specified entries. If you use both the **Id** and **Count** parameters in a command, `Get-History` gets the most recent entries ending with the entry specified by the **Id** parameter. ```yaml Type: System.Int64[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Int64 You can pipe a history ID to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.HistoryInfo This cmdlet returns a history object for each history item that it gets. ## NOTES PowerShell includes the following aliases for `Get-History`: - All platforms: - `h` - `history` - `ghy` The session history is a list of the commands entered during the session. The session history represents the run order, the status, and the start and end times of the command. As you enter each command, PowerShell adds it to the history so that you can reuse it. For more information about the command history, see [about_History](About/about_History.md). Starting in Windows PowerShell 3.0, the default value of the `$MaximumHistoryCount` preference variable is `4096`. In Windows PowerShell 2.0, the default value is `64`. For more information about the `$MaximumHistoryCount` variable, see [about_Preference_Variables](About/about_Preference_Variables.md). ## RELATED LINKS [Add-History](Add-History.md) [Clear-History](Clear-History.md) [Invoke-History](Invoke-History.md) [about_History](About/about_History.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Get-Job.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 09/22/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/get-job?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Job --- # Get-Job ## SYNOPSIS Gets PowerShell background jobs that are running in the current session. ## SYNTAX ### SessionIdParameterSet (Default) ``` Get-Job [-IncludeChildJob] [-ChildJobState <JobState>] [-HasMoreData <Boolean>] [-Before <DateTime>] [-After <DateTime>] [-Newest <Int32>] [[-Id] <Int32[]>] [<CommonParameters>] ``` ### InstanceIdParameterSet ``` Get-Job [-IncludeChildJob] [-ChildJobState <JobState>] [-HasMoreData <Boolean>] [-Before <DateTime>] [-After <DateTime>] [-Newest <Int32>] [-InstanceId] <Guid[]> [<CommonParameters>] ``` ### NameParameterSet ``` Get-Job [-IncludeChildJob] [-ChildJobState <JobState>] [-HasMoreData <Boolean>] [-Before <DateTime>] [-After <DateTime>] [-Newest <Int32>] [-Name] <String[]> [<CommonParameters>] ``` ### StateParameterSet ``` Get-Job [-IncludeChildJob] [-ChildJobState <JobState>] [-HasMoreData <Boolean>] [-Before <DateTime>] [-After <DateTime>] [-Newest <Int32>] [-State] <JobState> [<CommonParameters>] ``` ### CommandParameterSet ``` Get-Job [-IncludeChildJob] [-ChildJobState <JobState>] [-HasMoreData <Boolean>] [-Before <DateTime>] [-After <DateTime>] [-Newest <Int32>] [-Command <String[]>] [<CommonParameters>] ``` ### FilterParameterSet ``` Get-Job [-Filter] <Hashtable> [<CommonParameters>] ``` ## DESCRIPTION The `Get-Job` cmdlet gets objects that represent the background jobs that were started in the current session. You can use `Get-Job` to get jobs that were started by using the `Start-Job` cmdlet, or by using the **AsJob** parameter of any cmdlet. Without parameters, a `Get-Job` command gets all jobs in the current session. You can use the parameters of `Get-Job` to get particular jobs. The job object that `Get-Job` returns contains useful information about the job, but it does not contain the job results. To get the results, use the `Receive-Job` cmdlet. A Windows PowerShell background job is a command that runs in the background without interacting with the current session. Typically, you use a background job to run a complex command that takes a long time to finish. For more information about background jobs in Windows PowerShell, see [about_Jobs](./about/about_Jobs.md). Beginning in Windows PowerShell 3.0, the `Get-Job` cmdlet also gets custom job types, such as workflow jobs and instances of scheduled jobs. To find the job type of a job, use the **PSJobTypeName** property of the job. To enable `Get-Job` to get a custom job type, import the module that supports the custom job type into the session before you run a `Get-Job` command, either by using the `Import-Module` cmdlet or by using or getting a cmdlet in the module. For information about a particular custom job type, see the documentation of the custom job type feature. ## EXAMPLES ### Example 1: Get all background jobs started in the current session This command gets all background jobs started in the current session. It does not include jobs created in other sessions, even if the jobs run on the local computer. ```powershell Get-Job ``` ```Output Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 1 Job1 BackgroundJob Completed True localhost $Env:COMPUTERNAME ``` ### Example 2: Stop a job by using an instance ID These commands show how to get the instance ID of a job and then use it to stop a job. Unlike the name of a job, which is not unique, the instance ID is unique. The first command uses the `Get-Job` cmdlet to get a job. It uses the **Name** parameter to identify the job. The command stores the job object that `Get-Job` returns in the `$j` variable. In this example, there is only one job with the specified name. The second command gets the **InstanceId** property of the object in the `$j` variable and stores it in the `$ID` variable. The third command displays the value of the `$ID` variable. The fourth command uses `Stop-Job` cmdlet to stop the job. It uses the **InstanceId** parameter to identify the job and `$ID` variable to represent the instance ID of the job. ```powershell $j = Get-Job -Name Job1 $ID = $j.InstanceId $ID ``` ```Output Guid ---- 03c3232e-1d23-453b-a6f4-ed73c9e29d55 ``` ```powershell Stop-Job -InstanceId $ID ``` ### Example 3: Get jobs that include a specific command This command gets the jobs on the system that include a `Get-Process` command. The command uses the **Command** parameter of `Get-Job` to limit the jobs retrieved. The command uses wildcard characters (`*`) to get jobs that include a `Get-Process` command anywhere in the command string. ```powershell Get-Job -Command "*Get-Process*" ``` ```Output Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 3 Job3 BackgroundJob Running True localhost Get-Process ``` ### Example 4: Get jobs that include a specific command by using the pipeline Like the command in the previous example, this command gets the jobs on the system that include a `Get-Process` command. The command uses a pipeline operator (`|`) to send a PSCustomObject with the NoteProperty **Command**, to the `Get-Job` cmdlet. It is the equivalent of the previous command. ```powershell [pscustomobject]@{Command='*Get-Process*'} | Get-Job ``` ```Output Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 3 Job3 BackgroundJob Running True localhost Get-Process ``` ### Example 5: Get jobs that have not been started This command gets only those jobs that have been created but have not yet been started. This includes jobs that are scheduled to run in the future and those not yet scheduled. ```powershell Get-Job -State NotStarted ``` ### Example 6: Get jobs that have not been assigned a name This command gets all jobs that have job names that begin with job. Because `job<number>` is the default name for a job, this command gets all jobs that do not have an explicitly assigned name. ```powershell Get-Job -Name Job* ``` ```Output Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 1 Job1 BackgroundJob Completed True localhost $Env:COMPUTERNAME ``` ### Example 7: Use a job object to represent the job in a command This example shows how to use `Get-Job` to get a job object, and then it shows how to use the job object to represent the job in a command. The first command uses the `Start-Job` cmdlet to start a background job that runs a `Get-Process` command on the local computer. The command uses the **Name** parameter of `Start-Job` to assign a friendly name to the job. The second command uses `Get-Job` to get the job. It uses the **Name** parameter of `Get-Job` to identify the job. The command saves the resulting job object in the `$j` variable. The third command displays the value of the job object in the `$j` variable. The value of the **State** property shows that the job is completed. The value of the **HasMoreData** property shows that there are results available from the job that have not yet been retrieved. The fourth command uses the `Receive-Job` cmdlet to get the results of the job. It uses the job object in the `$j` variable to represent the job. You can also use a pipeline operator to send a job object to `Receive-Job`. ```powershell Start-Job -ScriptBlock {Get-Process} -Name MyJob $j = Get-Job -Name MyJob $j ``` ```Output Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 6 MyJob BackgroundJob Completed True localhost Get-Process ``` ```powershell Receive-Job -Job $j ``` ```Output Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 124 4 13572 12080 59 1140 audiodg 783 16 11428 13636 100 548 CcmExec 96 4 4252 3764 59 3856 ccmsetup ... ``` ### Example 8: Get all jobs including jobs started by a different method This example demonstrates that the `Get-Job` cmdlet can get all of the jobs that were started in the current session, even if they were started by using different methods. The first command uses the `Start-Job` cmdlet to start a job on the local computer. The second command uses the **AsJob** parameter of the `Invoke-Command` cmdlet to start a job on the S1 computer. Even though the commands in the job run on the remote computer, the job object is created on the local computer, so you use local commands to manage the job. The third command uses the `Invoke-Command` cmdlet to run a `Start-Job` command on the S2 computer. By using this method, the job object is created on the remote computer, so you use remote commands to manage the job. The fourth command uses `Get-Job` to get the jobs stored on the local computer. The **PSJobTypeName** property of jobs, introduced in Windows PowerShell 3.0, shows that the local job started by using the `Start-Job` cmdlet is a background job and the job started in a remote session by using the `Invoke-Command` cmdlet is a remote job. The fifth, sixth and seventh command uses the `New-PSSession` cmdlet to create a PSSession that is connected to the S2 computer, it uses `Invoke-Command` to start a job on the remote computer using the PSSession and the **Session** parameter. It then gets the job using the `Get-Job` command on the S2 computer using the PSSession. The sample output shows the results of the `Get-Job` command. On the S2 computer, the job appears to be a local job. The computer name is localhost and the job type is a background job. For more information about how to run background jobs on remote computers, see [about_Remote_Jobs](./about/about_Remote_Jobs.md). ```powershell Start-Job -ScriptBlock {Get-EventLog -LogName System} Invoke-Command -ComputerName S1 -ScriptBlock {Get-EventLog -LogName System} -AsJob Invoke-Command -ComputerName S2 -ScriptBlock {Start-Job -ScriptBlock {Get-EventLog -LogName System}} Get-Job ``` ```Output Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 1 Job1 BackgroundJob Running True localhost Get-EventLog System 2 Job2 RemoteJob Running True S1 Get-EventLog System ``` ```powershell $Session = New-PSSession -ComputerName S2 Invoke-Command -Session $Session -ScriptBlock {Start-Job -ScriptBlock {Get-EventLog -LogName System}} Invoke-Command -Session $Session -ScriptBlock {Get-Job} ``` ```Output Id Name PSJobTypeName State HasMoreData Location Command PSComputerName -- ---- ------------- ----- ----------- -------- ------- -------------- 1 Job1 BackgroundJob Running True localhost Get-EventLog -LogName Sy… S2 ``` ### Example 9: Investigate a failed job This command shows how to use the job object that `Get-Job` returns to investigate why a job failed. It also shows how to get the child jobs of each job. The first command uses the `Start-Job` cmdlet to start a job on the local computer. The job object that `Start-Job` returns shows that the job failed. The value of the **State** property is Failed. The second command uses the `Get-Job` cmdlet to get the job. The command uses the dot method to get the value of the **JobStateInfo** property of the object. It uses a pipeline operator to send the object in the **JobStateInfo** property to the `Format-List` cmdlet, which formats all of the properties of the object (`*`) in a list.The result of the `Format-List` command shows that the value of the **Reason** property of the job is blank. The third command investigates more. It uses a `Get-Job` command to get the job and then uses a pipeline operator to send the whole job object to the `Format-List` cmdlet, which displays all of the properties of the job in a list.The display of all properties in the job object shows that the job contains a child job named Job2. The fourth command uses `Get-Job` to get the job object that represents the Job2 child job. This is the job in which the command actually ran. It uses the dot method to get the **Reason** property of the **JobStateInfo** property.The result shows that the job failed because of an Access Denied error. In this case, the user forgot to use the Run as administrator option when starting Windows PowerShell.Because background jobs use the remoting features of Windows PowerShell, the computer must be configured for remoting to run a job, even when the job runs on the local computer.For information about requirements for remoting in Windows PowerShell, see [about_Remote_Requirements](./about/about_Remote_Requirements.md). For troubleshooting tips, see [about_Remote_Troubleshooting](./about/about_Remote_Troubleshooting.md). ```powershell PS> Start-Job -ScriptBlock {Get-Process} Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 1 Job1 BackgroundJob Failed False localhost Get-Process PS> (Get-Job).JobStateInfo | Format-List -Property * State : Failed Reason : PS> Get-Job | Format-List -Property * HasMoreData : False StatusMessage : Location : localhost Command : Get-Process JobStateInfo : Failed Finished : System.Threading.ManualReset EventInstanceId : fb792295-1318-4f5d-8ac8-8a89c5261507 Id : 1 Name : Job1 ChildJobs : {Job2} Output : {} Error : {} Progress : {} Verbose : {} Debug : {} Warning : {} StateChanged : PS> (Get-Job -Name Job2).JobStateInfo.Reason Connecting to remote server using WSManCreateShellEx api failed. The async callback gave the following error message: Access is denied. ``` ### Example 10: Get filtered results This example shows how to use the **Filter** parameter to get a workflow job. The **Filter** parameter, introduced in Windows PowerShell 3.0 is valid only on custom job types, such as workflow jobs and scheduled jobs. The first command uses the `workflow` keyword to create the WFProcess workflow. The second command uses the **AsJob** parameter of the WFProcess workflow to run the workflow as a background job. It uses the **JobName** parameter of the workflow to specify a name for the job, and the **PSPrivateMetadata** parameter of the workflow to specify a custom ID. The third command uses the **Filter** parameter of `Get-Job` to get the job by custom ID that was specified in the **PSPrivateMetadata** parameter. ```powershell PS> workflow WFProcess {Get-Process} PS> WFProcess -AsJob -JobName WFProcessJob -PSPrivateMetadata @{MyCustomId = 92107} PS> Get-Job -Filter @{MyCustomId = 92107} Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 1 WFProcessJob Completed True localhost WFProcess ``` ### Example 11: Get information about child jobs This example shows the effect of using the **IncludeChildJob** and **ChildJobState** parameters of the `Get-Job` cmdlet. The first command gets the jobs in the current session. The output includes a background job, a remote job and several instances of a scheduled job. The remote job, Job4, appears to have failed. The second command uses the **IncludeChildJob** parameter of `Get-Job`. The output adds the child jobs of all jobs that have child jobs.In this case, the revised output shows that only the Job5 child job of Job4 failed. The third command uses the **ChildJobState** parameter with a value of Failed.The output includes all parent jobs and only the child jobs that failed. The fifth command uses the **JobStateInfo** property of jobs and its **Reason** property to discover why Job5 failed. ```powershell PS> Get-Job Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 2 Job2 BackgroundJob Completed True localhost .\Get-Archive.ps1 4 Job4 RemoteJob Failed True Server01, Server02 .\Get-Archive.ps1 7 UpdateHelpJob PSScheduledJob Completed True localhost Update-Help 8 UpdateHelpJob PSScheduledJob Completed True localhost Update-Help 9 UpdateHelpJob PSScheduledJob Completed True localhost Update-Help 10 UpdateHelpJob PSScheduledJob Completed True localhost Update-Help PS> Get-Job -IncludeChildJob Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 2 Job2 BackgroundJob Completed True localhost .\Get-Archive.ps1 3 Job3 Completed True localhost .\Get-Archive.ps1 4 Job4 RemoteJob Failed True Server01, Server02 .\Get-Archive.ps1 5 Job5 Failed False Server01 .\Get-Archive.ps1 6 Job6 Completed True Server02 .\Get-Archive.ps1 7 UpdateHelpJob PSScheduledJob Completed True localhost Update-Help 8 UpdateHelpJob PSScheduledJob Completed True localhost Update-Help 9 UpdateHelpJob PSScheduledJob Completed True localhost Update-Help 10 UpdateHelpJob PSScheduledJob Completed True localhost Update-Help PS> Get-Job -Name Job4 -ChildJobState Failed Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 2 Job2 BackgroundJob Completed True localhost .\Get-Archive.ps1 4 Job4 RemoteJob Failed True Server01, Server02 .\Get-Archive.ps1 5 Job5 Failed False Server01 .\Get-Archive.ps1 7 UpdateHelpJob PSScheduledJob Completed True localhost Update-Help 8 UpdateHelpJob PSScheduledJob Completed True localhost Update-Help 9 UpdateHelpJob PSScheduledJob Completed True localhost Update-Help 10 UpdateHelpJob PSScheduledJob Completed True localhost Update-Help PS> (Get-Job -Name Job5).JobStateInfo.Reason Connecting to remote server Server01 failed with the following error message: Access is denied. ``` For more information, see the [about_Remote_Troubleshooting](./about/about_Remote_Troubleshooting.md) Help topic. ## PARAMETERS ### -After Gets completed jobs that ended after the specified date and time. Enter a **DateTime** object, such as one returned by the `Get-Date` cmdlet or a string that can be converted to a **DateTime** object, such as `Dec 1, 2012 2:00 AM` or `11/06`. This parameter works only on custom job types, such as workflow jobs and scheduled jobs, that have an **EndTime** property. It does not work on standard background jobs, such as those created by using the `Start-Job` cmdlet. For information about support for this parameter, see the help topic for the job type. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.DateTime Parameter Sets: SessionIdParameterSet, InstanceIdParameterSet, NameParameterSet, StateParameterSet, CommandParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Before Gets completed jobs that ended before the specified date and time. Enter a **DateTime** object. This parameter works only on custom job types, such as workflow jobs and scheduled jobs, that have an **EndTime** property. It does not work on standard background jobs, such as those created by using the `Start-Job` cmdlet. For information about support for this parameter, see the help topic for the job type. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.DateTime Parameter Sets: SessionIdParameterSet, InstanceIdParameterSet, NameParameterSet, StateParameterSet, CommandParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ChildJobState Gets only the child jobs that have the specified state. The acceptable values for this parameter are: - NotStarted - Running - Completed - Failed - Stopped - Blocked - Suspended - Disconnected - Suspending - Stopping By default, `Get-Job` does not get child jobs. By using the **IncludeChildJob** parameter, `Get-Job` gets all child jobs. If you use the **ChildJobState** parameter, the **IncludeChildJob** parameter has no effect. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.JobState Parameter Sets: SessionIdParameterSet, InstanceIdParameterSet, NameParameterSet, StateParameterSet, CommandParameterSet Aliases: Accepted values: NotStarted, Running, Completed, Failed, Stopped, Blocked, Suspended, Disconnected, Suspending, Stopping, AtBreakpoint Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Command Specifies an array of commands as strings. This cmdlet gets the jobs that include the specified commands. The default is all jobs. You can use wildcard characters to specify a command pattern. ```yaml Type: System.String[] Parameter Sets: CommandParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Filter Specifies a hash table of conditions. This cmdlet gets jobs that satisfy all of the conditions. Enter a hash table where the keys are job properties and the values are job property values. This parameter works only on custom job types, such as workflow jobs and scheduled jobs. It does not work on standard background jobs, such as those created by using the `Start-Job` cmdlet. For information about support for this parameter, see the help topic for the job type. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Collections.Hashtable Parameter Sets: FilterParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -HasMoreData Indicates whether this cmdlet gets only jobs that have the specified **HasMoreData** property value. The **HasMoreData** property indicates whether all job results have been received in the current session. To get jobs that have more results, specify a value of `$true`. To get jobs that do not have more results, specify a value of `$false`. To get the results of a job, use the `Receive-Job` cmdlet. When you use the `Receive-Job` cmdlet, it deletes from its in-memory, session-specific storage the results that it returned. When it has returned all results of the job in the current session, it sets the value of the **HasMoreData** property of the job to `$false`) to indicate that it has no more results for the job in the current session. Use the **Keep** parameter of `Receive-Job` to prevent `Receive-Job` from deleting results and changing the value of the **HasMoreData** property. For more information, type `Get-Help Receive-Job`. The **HasMoreData** property is specific to the current session. If results for a custom job type are saved outside of the session, such as the scheduled job type, which saves job results on disk, you can use the `Receive-Job` cmdlet in a different session to get the job results again, even if the value of **HasMoreData** is `$false`. For more information, see the help topics for the custom job type. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Boolean Parameter Sets: SessionIdParameterSet, InstanceIdParameterSet, NameParameterSet, StateParameterSet, CommandParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies an array of IDs of jobs that this cmdlet gets. The ID is an integer that uniquely identifies the job in the current session. It is easier to remember and to type than the instance ID, but it is unique only in the current session. You can type one or more IDs separated by commas. To find the ID of a job, type `Get-Job` without parameters. ```yaml Type: System.Int32[] Parameter Sets: SessionIdParameterSet Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -IncludeChildJob Indicates that this cmdlet returns child jobs, in addition to parent jobs. This parameter is especially useful for investigating workflow jobs, for which `Get-Job` returns a container parent job, and job failures, because the reason for the failure is saved in a property of the child job. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: SessionIdParameterSet, InstanceIdParameterSet, NameParameterSet, StateParameterSet, CommandParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InstanceId Specifies an array of instance IDs of jobs that this cmdlet gets. The default is all jobs. An instance ID is a GUID that uniquely identifies the job on the computer. To find the instance ID of a job, use `Get-Job`. ```yaml Type: System.Guid[] Parameter Sets: InstanceIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies an array of instance friendly names of jobs that this cmdlet gets. Enter a job name, or use wildcard characters to enter a job name pattern. By default, `Get-Job` gets all jobs in the current session. ```yaml Type: System.String[] Parameter Sets: NameParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Newest Specifies a number of jobs to get. This cmdlet gets the jobs that ended most recently. The **Newest** parameter does not sort or return the newest jobs in end-time order. To sort the output, use the `Sort-Object` cmdlet. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Int32 Parameter Sets: SessionIdParameterSet, InstanceIdParameterSet, NameParameterSet, StateParameterSet, CommandParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -State Specifies a job state. This cmdlet gets only jobs in the specified state. The acceptable values for this parameter are: - NotStarted - Running - Completed - Failed - Stopped - Blocked - Suspended - Disconnected - Suspending - Stopping By default, `Get-Job` gets all the jobs in the current session. For more information about job states, see [JobState Enumeration](/dotnet/api/system.management.automation.jobstate). ```yaml Type: System.Management.Automation.JobState Parameter Sets: StateParameterSet Aliases: Accepted values: NotStarted, Running, Completed, Failed, Stopped, Blocked, Suspended, Disconnected, Suspending, Stopping, AtBreakpoint Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.RemotingJob This cmdlet returns objects that represent the jobs in the session. ## NOTES PowerShell includes the following aliases for `Get-Job`: - All platforms: - `gjb` The **PSJobTypeName** property of jobs indicates the job type of the job. The property value is determined by the job type author. The following list shows common job types. - **BackgroundJob**. Local job started by using `Start-Job`. - **RemoteJob**. Job started in a **PSSession** by using the **AsJob** parameter of the `Invoke-Command` cmdlet. - **PSWorkflowJob**. Job started by using the **AsJob** common parameter of workflows. ## RELATED LINKS [Invoke-Command](Invoke-Command.md) [Receive-Job](Receive-Job.md) [Remove-Job](Remove-Job.md) [Start-Job](Start-Job.md) [Stop-Job](Stop-Job.md) [Wait-Job](Wait-Job.md) [about_Jobs](About/about_Jobs.md) [about_Job_Details](About/about_Job_Details.md) [about_Remote_Jobs](About/about_Remote_Jobs.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Get-Module.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/get-module?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Module --- # Get-Module ## SYNOPSIS List the modules imported in the current session or that can be imported from the PSModulePath. ## SYNTAX ### Loaded (Default) ``` Get-Module [[-Name] <String[]>] [-FullyQualifiedName <ModuleSpecification[]>] [-All] [<CommonParameters>] ``` ### Available ``` Get-Module [[-Name] <String[]>] [-FullyQualifiedName <ModuleSpecification[]>] [-All] [-ListAvailable] [-PSEdition <String>] [-SkipEditionCheck] [-Refresh] [<CommonParameters>] ``` ### PsSession ``` Get-Module [[-Name] <String[]>] [-FullyQualifiedName <ModuleSpecification[]>] [-ListAvailable] [-PSEdition <String>] [-SkipEditionCheck] [-Refresh] -PSSession <PSSession> [<CommonParameters>] ``` ### CimSession ``` Get-Module [[-Name] <String[]>] [-FullyQualifiedName <ModuleSpecification[]>] [-ListAvailable] [-SkipEditionCheck] [-Refresh] -CimSession <CimSession> [-CimResourceUri <Uri>] [-CimNamespace <String>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Module` cmdlet lists the PowerShell modules that have been imported, or that can be imported, into a PowerShell session. Without parameters, `Get-Module` gets modules that have been imported into the current session. The **ListAvailable** parameter is used to list the modules that are available to be imported from the paths specified in the **PSModulePath** environment variable (`$Env:PSModulePath`). The module object that `Get-Module` returns contains valuable information about the module. You can also pipe the module objects to other cmdlets, such as the `Import-Module` and `Remove-Module` cmdlets. `Get-Module` lists modules, but it does not import them. Starting in Windows PowerShell 3.0, modules are automatically imported when you use a command in the module, but a `Get-Module` command does not trigger an automatic import. You can also import the modules into your session using the `Import-Module` cmdlet. Starting in Windows PowerShell 3.0, you can get and then, import modules from remote sessions into the local session. This strategy uses the Implicit Remoting feature of PowerShell and is equivalent to using the `Import-PSSession` cmdlet. When you use commands in modules imported from another session, the commands run implicitly in the remote session. This feature lets you manage the remote computer from the local session. Also, starting in Windows PowerShell 3.0, you can use `Get-Module` and `Import-Module` to get and import Common Information Model (CIM) modules. CIM modules define cmdlets in Cmdlet Definition XML (CDXML) files. This feature lets you use cmdlets that are implemented in non-managed code assemblies, such as those written in C++. Implicit remoting can be used to manage remote computers that have PowerShell remoting enabled. Create a **PSSession** on the remote computer and then use the **PSSession** parameter of `Get-Module` to get the PowerShell modules in the remote session. When you import a module from the remote session the imported commands run in the session on the remote computer. You can use a similar strategy to manage computers that do not have PowerShell remoting enabled. These include computers that are not running the Windows operating system, and computers that have PowerShell but do not have PowerShell remoting enabled. Start by creating a CIM session on the remote computer. A CIM session is a connection to Windows Management Instrumentation (WMI) on the remote computer. Then use the **CimSession** parameter of `Get-Module` to get CIM modules from the CIM session. When you import a CIM module by using the `Import-Module` cmdlet and then run the imported commands, the commands run implicitly on the remote computer. You can use this WMI and CIM strategy to manage the remote computer. ## EXAMPLES ### Example 1: Get modules imported into the current session ```powershell Get-Module ``` This command gets modules that have been imported into the current session. ### Example 2: Get installed modules and available modules ```powershell Get-Module -ListAvailable ``` This command gets the modules that are installed on the computer and can be imported into the current session. `Get-Module` looks for available modules in the path specified by the **$Env:PSModulePath** environment variable. For more information about **PSModulePath**, see [about_Modules](About/about_Modules.md) and [about_Environment_Variables](About/about_Environment_Variables.md). ### Example 3: Get all exported files ```powershell Get-Module -ListAvailable -All ``` This command gets all of the exported files for all available modules. ### Example 4: Get a module by its fully qualified name ```powershell $FullyQualifiedName = @{ModuleName="Microsoft.PowerShell.Management";ModuleVersion="3.1.0.0"} Get-Module -FullyQualifiedName $FullyQualifiedName | Format-Table -Property Name,Version ``` ```Output Name Version ---- ------- Microsoft.PowerShell.Management 3.1.0.0 ``` This example gets the **Microsoft.PowerShell.Management** module by specifying the fully qualified name of the module by using the **FullyQualifiedName** parameter. The command then pipes the results into the `Format-Table` cmdlet to format the results as a table with **Name** and **Version** as the column headings. In a fully qualified name for a module, the value **ModuleVersion** acts as minimum version. So, for this example, it matches any **Microsoft.PowerShell.Management** module that is version `3.1.0.0` or higher. ### Example 5: Get properties of a module ```powershell Get-Module | Get-Member -MemberType Property | Format-Table Name ``` ```Output Name ---- AccessMode Author ClrVersion CompanyName Copyright Definition Description DotNetFrameworkVersion ExportedAliases ExportedCmdlets ExportedCommands ExportedFormatFiles ExportedFunctions ExportedTypeFiles ExportedVariables ExportedWorkflows FileList Guid HelpInfoUri LogPipelineExecutionDetails ModuleBase ModuleList ModuleType Name NestedModules OnRemove Path PowerShellHostName PowerShellHostVersion PowerShellVersion PrivateData ProcessorArchitecture RequiredAssemblies RequiredModules RootModule Scripts SessionState Version ``` This command gets the properties of the **PSModuleInfo** object that `Get-Module` returns. There is one object for each module file. You can use the properties to format and filter the module objects. For more information about the properties, see [PSModuleInfo Properties](/dotnet/api/system.management.automation.psmoduleinfo). The output includes the new properties, such as **Author** and **CompanyName**, that were introduced in Windows PowerShell 3.0. ### Example 6: Group all modules by name ```powershell Get-Module -ListAvailable -All | Format-Table -Property Name, ModuleType, Path -GroupBy Name ``` ```Output Name: AppLocker Name ModuleType Path ---- ---------- ---- AppLocker Manifest C:\Windows\system32\WindowsPowerShell\v1.0\Modules\AppLocker\AppLocker.psd1 Name: Appx Name ModuleType Path ---- ---------- ---- Appx Manifest C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Appx\en-US\Appx.psd1 Appx Manifest C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Appx\Appx.psd1 Appx Script C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Appx\Appx.psm1 Name: BestPractices Name ModuleType Path ---- ---------- ---- BestPractices Manifest C:\Windows\system32\WindowsPowerShell\v1.0\Modules\BestPractices\BestPractices.psd1 Name: BitsTransfer Name ModuleType Path ---- ---------- ---- BitsTransfer Manifest C:\Windows\system32\WindowsPowerShell\v1.0\Modules\BitsTransfer\BitsTransfer.psd1 ``` This command gets all module files, both imported and available, and then groups them by module name. This lets you see the module files that each script is exporting. ### Example 7: Display the contents of a module manifest These commands display the contents of the module manifest for the Windows PowerShell **BitsTransfer** module. Modules are not required to have manifest files. When they do have a manifest file, the manifest file is required only to include a version number. However, manifest files often provide useful information about a module, its requirements, and its contents. ```powershell # First command $m = Get-Module -List -Name BitsTransfer # Second command Get-Content $m.Path ``` ```Output @ { GUID = "{8FA5064B-8479-4c5c-86EA-0D311FE48875}" Author = "Microsoft Corporation" CompanyName = "Microsoft Corporation" Copyright = "Microsoft Corporation. All rights reserved." ModuleVersion = "1.0.0.0" Description = "Windows PowerShell File Transfer Module" PowerShellVersion = "2.0" CLRVersion = "2.0" NestedModules = "Microsoft.BackgroundIntelligentTransfer.Management" FormatsToProcess = "FileTransfer.Format.ps1xml" RequiredAssemblies = Join-Path $PSScriptRoot "Microsoft.BackgroundIntelligentTransfer.Management.Interop.dll" } ``` The first command gets the **PSModuleInfo** object that represents BitsTransfer module. It saves the object in the `$m` variable. The second command uses the `Get-Content` cmdlet to get the content of the manifest file in the specified path. It uses dot notation to get the path to the manifest file, which is stored in the **Path** property of the object. The output shows the contents of the module manifest. ### Example 8: List files in module directory ```powershell dir (Get-Module -ListAvailable FileTransfer).ModuleBase ``` ```Output Directory: C:\Windows\system32\WindowsPowerShell\v1.0\Modules\FileTransfer Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 12/16/2008 12:36 PM en-US -a--- 11/19/2008 11:30 PM 16184 FileTransfer.Format.ps1xml -a--- 11/20/2008 11:30 PM 1044 FileTransfer.psd1 -a--- 12/16/2008 12:20 AM 108544 Microsoft.BackgroundIntelligentTransfer.Management.Interop.dll ``` This command lists the files in the directory of the module. This is another way to determine what is in a module before you import it. Some modules might have help files or ReadMe files that describe the module. ### Example 9: Get modules installed on a computer ```powershell $s = New-PSSession -ComputerName Server01 Get-Module -PSSession $s -ListAvailable ``` These commands get the modules that are installed on the Server01 computer. The first command uses the `New-PSSession` cmdlet to create a **PSSession** on the Server01 computer. The command saves the **PSSession** in the `$s` variable. The second command uses the **PSSession** and **ListAvailable** parameters of `Get-Module` to get the modules in the **PSSession** in the `$s` variable. If you pipe modules from other sessions to the `Import-Module` cmdlet, `Import-Module` imports the module into the current session by using the implicit remoting feature. This is equivalent to using the `Import-PSSession` cmdlet. You can use the cmdlets from the module in the current session, but commands that use these cmdlets actually run the remote session. For more information, see [`Import-Module`](Import-Module.md) and [`Import-PSSession`](../Microsoft.PowerShell.Utility/Import-PSSession.md). ### Example 10: Manage a computer that does not run the Windows operating system The commands in this example enable you to manage the storage systems of a remote computer that is not running the Windows operating system. In this example, because the administrator of the computer has installed the Module Discovery WMI provider, the CIM commands can use the default values, which are designed for the provider. ```powershell $cs = New-CimSession -ComputerName RSDGF03 Get-Module -CimSession $cs -Name Storage | Import-Module Get-Command Get-Disk ``` ```Output CommandType Name ModuleName ----------- ---- ---------- Function Get-Disk Storage ``` ```powershell Get-Disk ``` ```Output Number Friendly Name OperationalStatus Total Size Partition Style ------ ------------- ----------------- ---------- --------------- 0 Virtual HD ATA Device Online 40 GB MBR ``` The first command uses the `New-CimSession` cmdlet to create a session on the RSDGF03 remote computer. The session connects to WMI on the remote computer. The command saves the CIM session in the `$cs` variable. The second command uses the CIM session in the `$cs` variable to run a `Get-Module` command on the RSDGF03 computer. The command uses the **Name** parameter to specify the Storage module. The command uses a pipeline operator (`|`) to send the Storage module to the `Import-Module` cmdlet, which imports it into the local session. The third command runs the `Get-Command` cmdlet on the `Get-Disk` command in the Storage module. When you import a CIM module into the local session, PowerShell converts the CDXML files that represent the CIM module into PowerShell scripts, which appear as functions in the local session. The fourth command runs the `Get-Disk` command. Although the command is typed in the local session, it runs implicitly on the remote computer from which it was imported. The command gets objects from the remote computer and returns them to the local session. ## PARAMETERS ### -All Indicates that this cmdlet gets all modules in each module folder, including nested modules, manifest (`.psd1`) files, script module (`.psm1`) files, and binary module (`.dll`) files. Without this parameter, `Get-Module` gets only the default module in each module folder. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Loaded, Available Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -CimNamespace Specifies the namespace of an alternate CIM provider that exposes CIM modules. The default value is the namespace of the Module Discovery WMI provider. Use this parameter to get CIM modules from computers and devices that are not running the Windows operating system. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String Parameter Sets: CimSession Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CimResourceUri Specifies an alternate location for CIM modules. The default value is the resource URI of the Module Discovery WMI provider on the remote computer. Use this parameter to get CIM modules from computers and devices that are not running the Windows operating system. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Uri Parameter Sets: CimSession Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CimSession Specifies a CIM session on the remote computer. Enter a variable that contains the CIM session or a command that gets the CIM session, such as a [Get-CimSession](/powershell/module/cimcmdlets/get-cimsession) command. `Get-Module` uses the CIM session connection to get modules from the remote computer. When you import the module by using the `Import-Module` cmdlet and use the commands from the imported module in the current session, the commands actually run on the remote computer. You can use this parameter to get modules from computers and devices that are not running the Windows operating system, and computers that have PowerShell, but do not have PowerShell remoting enabled. The **CimSession** parameter gets all modules in the **CIMSession**. However, you can import only CIM-based and Cmdlet Definition XML (CDXML)-based modules. ```yaml Type: Microsoft.Management.Infrastructure.CimSession Parameter Sets: CimSession Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FullyQualifiedName The value can be a module name, a full module specification, or a path to a module file. When the value is a path, the path can be fully qualified or relative. A relative path is resolved relative to the script that contains the using statement. When the value is a name or module specification, PowerShell searches the **PSModulePath** for the specified module. A module specification is a hashtable that has the following keys. - `ModuleName` - **Required** Specifies the module name. - `GUID` - **Optional** Specifies the GUID of the module. - It's also **Required** to specify at least one of the three below keys. - `ModuleVersion` - Specifies a minimum acceptable version of the module. - `MaximumVersion` - Specifies the maximum acceptable version of the module. - `RequiredVersion` - Specifies an exact, required version of the module. This can't be used with the other Version keys. You cannot specify the **FullyQualifiedName** parameter in the same command as a **Name** parameter. ```yaml Type: Microsoft.PowerShell.Commands.ModuleSpecification[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ListAvailable By default, `Get-Module` only returns the modules that have been imported into the current session. With this parameter the command lists modules installed in any path included in the `$env:PSModulePath` environment variable. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Available, PsSession, CimSession Aliases: Required: True (Available), False (PsSession, CimSession) Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies names or name patterns of modules that this cmdlet gets. Wildcard characters are permitted. You can also pipe the names to `Get-Module`. You cannot specify the **FullyQualifiedName** parameter in the same command as a **Name** parameter. **Name** cannot accept a module GUID as a value. To return modules by specifying a GUID, use **FullyQualifiedName** instead. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: True ``` ### -PSEdition Gets the modules that support specified edition of PowerShell. The acceptable values for this parameter are: - `Desktop` - `Core` The `Get-Module` cmdlet checks **CompatiblePSEditions** property of **PSModuleInfo** object for the specified value and returns only those modules that have it set. > [!NOTE] > - **Desktop Edition:** Built on .NET Framework and provides compatibility with scripts and modules > targeting versions of PowerShell running on full footprint editions of Windows such as Server > Core and Windows Desktop. > - **Core Edition:** Built on .NET Core and provides compatibility with scripts and modules > targeting versions of PowerShell running on reduced footprint editions of Windows such as Nano > Server and Windows IoT. ```yaml Type: System.String Parameter Sets: PsSession, Available Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PSSession Gets the modules in the specified user-managed PowerShell session (**PSSession**). Enter a variable that contains the session, a command that gets the session, such as a `Get-PSSession` command, or a command that creates the session, such as a `New-PSSession` command. When the session is connected to a remote computer, you must specify the **ListAvailable** parameter. A `Get-Module` command that uses the **PSSession** parameter is equivalent to using the `Invoke-Command` cmdlet to run a `Get-Module -ListAvailable` command in a **PSSession**. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.Runspaces.PSSession Parameter Sets: PsSession Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Refresh Indicates that this cmdlet refreshes the cache of installed commands. The command cache is created when the session starts. It enables the `Get-Command` cmdlet to get commands from modules that are not imported into the session. This parameter is designed for development and testing scenarios in which the contents of modules have changed since the session started. When you specify the **Refresh** parameter in a command, you must specify **ListAvailable**. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Available, PsSession, CimSession Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipEditionCheck Skips the check of the **CompatiblePSEditions** field. By default, `Get-Module` omits modules in the `%windir%\System32\WindowsPowerShell\v1.0\Modules` directory that do not specify `Core` in the **CompatiblePSEditions** field. When this switch is set, modules without `Core` are included, so that modules under the Windows PowerShell module path that are incompatible with PowerShell v6 and higher are returned. On macOS and Linux, this parameter does nothing. See [about_PowerShell_Editions](About/about_PowerShell_Editions.md) for more information. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Available, PsSession, CimSession Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe module names to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSModuleInfo This cmdlet returns objects that represent modules. When you specify the **ListAvailable** parameter, `Get-Module` returns a **ModuleInfoGrouping** object, which is a type of **PSModuleInfo** object that has the same properties and methods. ## NOTES PowerShell includes the following aliases for `Get-Module`: - All platforms: - `gmo` - Beginning in Windows PowerShell 3.0, the core commands that are included in PowerShell are packaged in modules. The exception is **Microsoft.PowerShell.Core**, which is a snap-in (**PSSnapin**). By default, only the **Microsoft.PowerShell.Core** snap-in is added to the session. Modules are imported automatically on first use and you can use the `Import-Module` cmdlet to import them. - In Windows PowerShell 2.0, and in host programs that create older-style sessions in later versions of PowerShell, the core commands are packaged in snap-ins (**PSSnapins**). The exception is **Microsoft.PowerShell.Core**, which is always a snap-in. Also, remote sessions, such as those started by the `New-PSSession` cmdlet, are older-style sessions that include core snap-ins. For information about the **CreateDefault2** method that creates newer-style sessions with core modules, see [CreateDefault2 Method](/dotnet/api/system.management.automation.runspaces.initialsessionstate.createdefault2). - `Get-Module` only gets modules in locations that are stored in the value of the **PSModulePath** environment variable (`$Env:PSModulePath`). The `Import-Module` cmdlet can import modules in other locations, but you cannot use the `Get-Module` cmdlet to get them. - Also, starting in PowerShell 3.0, new properties have been added to the object that `Get-Module` returns that make it easier to learn about modules even before they are imported. All properties are populated before importing. These include the **ExportedCommands**, **ExportedCmdlets** and **ExportedFunctions** properties that list the commands that the module exports. - The **ListAvailable** parameter gets only well-formed modules, that is, folders that contain at least one file whose base name is the same as the name of the module folder. The base name is the name without the file name extension. Folders that contain files that have different names are considered to be containers, but not modules. To get modules that are implemented as DLL files, but are not enclosed in a module folder, specify both the **ListAvailable** and **All** parameters. - To use the CIM session feature, the remote computer must have WS-Management remoting and Windows Management Instrumentation (WMI), which is the Microsoft implementation of the Common Information Model (CIM) standard. The computer must also have the Module Discovery WMI provider or an alternate WMI provider that has the same basic features. You can use the CIM session feature on computers that are not running the Windows operating system and on Windows computers that have PowerShell, but do not have PowerShell remoting enabled. You can also use the CIM parameters to get CIM modules from computers that have PowerShell remoting enabled. This includes the local computer. When you create a CIM session on the local computer, PowerShell uses DCOM, instead of WMI, to create the session. ## RELATED LINKS [Get-CimSession](../CimCmdlets/Get-CimSession.md) [New-CimSession](../CimCmdlets/New-CimSession.md) [about_Modules](About/about_Modules.md) [Get-PSSession](Get-PSSession.md) [Import-Module](Import-Module.md) [Import-PSSession](../Microsoft.PowerShell.Utility/Import-PSSession.md) [New-PSSession](New-PSSession.md) [Remove-Module](Remove-Module.md) [about_PowerShell_Editions](About/about_PowerShell_Editions.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Get-PSHostProcessInfo.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 06/09/2017 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/get-pshostprocessinfo?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-PSHostProcessInfo --- # Get-PSHostProcessInfo ## SYNOPSIS Gets process information about the PowerShell host. ## SYNTAX ### ProcessNameParameterSet (Default) ``` Get-PSHostProcessInfo [[-Name] <String[]>] [<CommonParameters>] ``` ### ProcessParameterSet ``` Get-PSHostProcessInfo [-Process] <Process[]> [<CommonParameters>] ``` ### ProcessIdParameterSet ``` Get-PSHostProcessInfo [-Id] <Int32[]> [<CommonParameters>] ``` ## DESCRIPTION The `Get-PSHostProcessInfo` cmdlet gets information about PowerShell host processes running on the local computer. Beginning in PowerShell 6.2, this cmdlet is supported on non-Windows platforms. ## EXAMPLES ### 1: Get a list of PowerShell hosts running on the system ```powershell Get-PSHostProcessInfo ``` ```Output ProcessName ProcessId AppDomainName ----------- --------- ------------- powershell 11204 DefaultAppDomain pwsh 13912 DefaultAppDomain ``` ### 2: Get PowerShell host information for a specific process name ```powershell Get-PSHostProcessInfo -Name pwsh ``` ```Output ProcessName ProcessId AppDomainName ----------- --------- ------------- pwsh 13912 DefaultAppDomain ``` ## PARAMETERS ### -Id Specifies a process by the process ID. To get a process ID, run the `Get-Process` cmdlet. ```yaml Type: System.Int32[] Parameter Sets: ProcessIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies a process by the process name. To get a process name, run the `Get-Process` cmdlet. ```yaml Type: System.String[] Parameter Sets: ProcessNameParameterSet Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Process Specifies a process by the process object. The simplest way to use this parameter is to save the results of a `Get-Process` command that returns process that you want to enter in a variable, and then specify the variable as the value of this parameter. ```yaml Type: System.Diagnostics.Process[] Parameter Sets: ProcessParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Diagnostics.Process You can pipe a **Process** object from `Get-Process` to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.PSHostProcessInfo ## NOTES ## RELATED LINKS [Get-Process](../Microsoft.PowerShell.Management/get-process.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Get-PSSession.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/get-pssession?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-PSSession --- # Get-PSSession ## SYNOPSIS Gets the PowerShell sessions on local and remote computers. ## SYNTAX ### Name (Default) ``` Get-PSSession [-Name <String[]>] [<CommonParameters>] ``` ### ComputerName ``` Get-PSSession [-ComputerName] <String[]> [-ApplicationName <String>] [-ConfigurationName <String>] [-Name <String[]>] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [-Port <Int32>] [-UseSSL] [-ThrottleLimit <Int32>] [-State <SessionFilterState>] [-SessionOption <PSSessionOption>] [<CommonParameters>] ``` ### ComputerInstanceId ``` Get-PSSession [-ComputerName] <String[]> [-ApplicationName <String>] [-ConfigurationName <String>] -InstanceId <Guid[]> [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [-Port <Int32>] [-UseSSL] [-ThrottleLimit <Int32>] [-State <SessionFilterState>] [-SessionOption <PSSessionOption>] [<CommonParameters>] ``` ### ConnectionUri ``` Get-PSSession [-ConnectionUri] <Uri[]> [-ConfigurationName <String>] [-AllowRedirection] [-Name <String[]>] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [-ThrottleLimit <Int32>] [-State <SessionFilterState>] [-SessionOption <PSSessionOption>] [<CommonParameters>] ``` ### ConnectionUriInstanceId ``` Get-PSSession [-ConnectionUri] <Uri[]> [-ConfigurationName <String>] [-AllowRedirection] -InstanceId <Guid[]> [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [-ThrottleLimit <Int32>] [-State <SessionFilterState>] [-SessionOption <PSSessionOption>] [<CommonParameters>] ``` ### VMNameInstanceId ``` Get-PSSession [-ConfigurationName <String>] -InstanceId <Guid[]> [-State <SessionFilterState>] -VMName <String[]> [<CommonParameters>] ``` ### ContainerId ``` Get-PSSession [-ConfigurationName <String>] [-Name <String[]>] [-State <SessionFilterState>] -ContainerId <String[]> [<CommonParameters>] ``` ### ContainerIdInstanceId ``` Get-PSSession [-ConfigurationName <String>] -InstanceId <Guid[]> [-State <SessionFilterState>] -ContainerId <String[]> [<CommonParameters>] ``` ### VMId ``` Get-PSSession [-ConfigurationName <String>] [-Name <String[]>] [-State <SessionFilterState>] -VMId <Guid[]> [<CommonParameters>] ``` ### VMIdInstanceId ``` Get-PSSession [-ConfigurationName <String>] -InstanceId <Guid[]> [-State <SessionFilterState>] -VMId <Guid[]> [<CommonParameters>] ``` ### VMName ``` Get-PSSession [-ConfigurationName <String>] [-Name <String[]>] [-State <SessionFilterState>] -VMName <String[]> [<CommonParameters>] ``` ### InstanceId ``` Get-PSSession [-InstanceId <Guid[]>] [<CommonParameters>] ``` ### Id ``` Get-PSSession [-Id] <Int32[]> [<CommonParameters>] ``` ## DESCRIPTION The `Get-PSSession` cmdlet gets the user-managed PowerShell sessions (**PSSessions**) on local and remote computers. Starting in Windows PowerShell 3.0, sessions are stored on the computers at the remote end of each connection. You can use the **ComputerName** or **ConnectionUri** parameters of `Get-PSSession` to get the sessions that connect to the local computer or remote computers, even if they were not created in the current session. Without parameters, `Get-PSSession` gets all sessions that were created in the current session. Use the filtering parameters, including **Name**, **Id**, **InstanceId**, **State**, **ApplicationName**, and **ConfigurationName** to select from among the sessions that `Get-PSSession` returns. Use the remaining parameters to configure the temporary connection in which the `Get-PSSession` command runs when you use the **ComputerName** or **ConnectionUri** parameters. > [!NOTE] > In Windows PowerShell 2.0, without parameters, `Get-PSSession` gets all sessions that were created > in the current session. The **ComputerName** parameter gets sessions that were created in the > current session and connect to the specified computer. For more information about PowerShell sessions, see [about_PSSessions](about/about_PSSessions.md). ## EXAMPLES ### Example 1: Get sessions created in the current session ```powershell Get-PSSession ``` This command gets all of the **PSSessions** that were created in the current session. It does not get **PSSessions** that were created in other sessions or on other computers, even if they connect to this computer. ### Example 2: Get sessions connected to the local computer ```powershell Get-PSSession -ComputerName "localhost" ``` This command gets the **PSSessions** that are connected to the local computer. To indicate the local computer, type the computer name, localhost, or a dot (`.`) The command returns all of the sessions on the local computer, even if they were created in different sessions or on different computers. ### Example 3: Get sessions connected to a computer ```powershell Get-PSSession -ComputerName "Server02" ``` ```Output Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 2 Session3 Server02 Disconnected ITTasks Busy 1 ScheduledJobs Server02 Opened Microsoft.PowerShell Available 3 Test Server02 Disconnected Microsoft.PowerShell Busy ``` This command gets the **PSSessions** that are connected to the Server02 computer. The command returns all of the sessions on Server02, even if they were created in different sessions or on different computers. The output shows that two of the sessions have a `Disconnected` state and a `Busy` availability. They were created in different sessions and are currently in use. The `ScheduledJobs` session, which is `Opened` and `Available`, was created in the current session. ### Example 4: Save results of this command ```powershell New-PSSession -ComputerName Server01, Server02, Server03 $s1, $s2, $s3 = Get-PSSession ``` This example shows how to save the results of a `Get-PSSession` command in multiple variables. The first command uses the `New-PSSession` cmdlet to create **PSSessions** on three remote computers. The second command uses a `Get-PSSession` cmdlet to get the three **PSSessions**. It then saves each of the **PSSessions** in a separate variable. When PowerShell assigns an array of objects to an array of variables, it assigns the first object to the first variable, the second object to the second variable, and so on. If there are more objects than variables, it assigns all remaining objects to the last variable in the array. If there are more variables than objects, the extra variables are not used. ### Example 5: Delete a session by using an instance ID ```powershell Get-PSSession | Format-Table -Property ComputerName, InstanceId $s = Get-PSSession -InstanceId a786be29-a6bb-40da-80fb-782c67f7db0f Remove-PSSession -Session $s ``` This example shows how to get a **PSSession** by using its instance ID, and then to delete the **PSSession**. The first command gets all of the **PSSessions** that were created in the current session. It sends the **PSSessions** to the `Format-Table` cmdlet, which displays the **ComputerName** and **InstanceId** properties of each **PSSession**. The second command uses the `Get-PSSession` cmdlet to get a particular **PSSession** and to save it in the `$s` variable. The command uses the **InstanceId** parameter to identify the **PSSession**. The third command uses the Remove-PSSession cmdlet to delete the **PSSession** in the `$s` variable. ### Example 6: Get a session that has a particular name The commands in this example find a session that has a particular name format and uses a particular session configuration and then connect to the session. You can use a command like this one to find a session in which a colleague started a task and connect to finish the task. ```powershell Get-PSSession -ComputerName Server02, Server12 -Name BackupJob* -ConfigurationName ITTasks -SessionOption @{OperationTimeout=240000} ``` ```Output Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 3 BackupJob04 Server02 Disconnected ITTasks None ``` ```powershell $s = Get-PSSession -ComputerName Server02 -Name BackupJob04 -ConfigurationName ITTasks | Connect-PSSession $s ``` ```Output Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 5 BackupJob04 Server02 Opened ITTasks Available ``` The first command gets sessions on the Server02 and Server12 remote computers that have names that begin with `BackupJob` and use the `ITTasks` session configuration.The command uses the **Name** parameter to specify the name pattern and the **ConfigurationName** parameter to specify the session configuration. The value of the **SessionOption** parameter is a hash table that sets the value of the **OperationTimeout** to `240000` milliseconds (4 minutes). This setting gives the command more time to complete.The **ConfigurationName** and **SessionOption** parameters are used to configure the temporary sessions in which the `Get-PSSession` cmdlet runs on each computer.The output shows that the command returns the `BackupJob04` session. The session is disconnected and the **Availability** is `None`, which indicates that it is not in use. The second command uses the `Get-PSSession` cmdlet to get to the `BackupJob04` session and the `Connect-PSSession` cmdlet to connect to the session. The command saves the session in the `$s` variable. The third command gets the session in the `$s` variable. The output shows that the `Connect-PSSession` command was successful. The session is in the **Opened** state and is available for use. ### Example 7: Get a session by using its ID ```powershell Get-PSSession -Id 2 ``` This command gets the **PSSession** with ID `2`. Because the value of the **Id** property is unique only in the current session, the **Id** parameter is valid only for local commands. ## PARAMETERS ### -AllowRedirection Indicates that this cmdlet allows redirection of this connection to an alternate Uniform Resource Identifier (URI). By default, PowerShell does not redirect connections. This parameter configures the temporary connection that is created to run a `Get-PSSession` command with the **ConnectionUri** parameter. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ConnectionUriInstanceId, ConnectionUri Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ApplicationName Specifies the name of an application. This cmdlet connects only to sessions that use the specified application. Enter the application name segment of the connection URI. For example, in the following connection URI, the application name is WSMan: `http://localhost:5985/WSMAN`. The application name of a session is stored in the **Runspace.ConnectionInfo.AppName** property of the session. The value of this parameter is used to select and filter sessions. It does not change the application that the session uses. ```yaml Type: System.String Parameter Sets: ComputerInstanceId, ComputerName Aliases: Required: False Position: Named Default value: All sessions Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Authentication Specifies the mechanism that is used to authenticate credentials for the session in which the `Get-PSSession` command runs. This parameter configures the temporary connection that is created to run a `Get-PSSession` command with the **ComputerName** or **ConnectionUri** parameter. The acceptable values for this parameter are: - `Default` - `Basic` - `CredSSP` - `Digest` - `Kerberos` - `Negotiate` - `NegotiateWithImplicitCredential`. The default value is `Default`. For more information about the values of this parameter, see [AuthenticationMechanism Enumeration](/dotnet/api/system.management.automation.runspaces.authenticationmechanism). > [!CAUTION] > Credential Security Support Provider (CredSSP) authentication, in which the user's credentials are > passed to a remote computer to be authenticated, is designed for commands that require > authentication on more than one resource, such as accessing a remote network share. This mechanism > increases the security risk of the remote operation. If the remote computer is compromised, the > credentials that are passed to it can be used to control the network session. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.Runspaces.AuthenticationMechanism Parameter Sets: ComputerInstanceId, ComputerName, ConnectionUriInstanceId, ConnectionUri Aliases: Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential, Credssp, Digest, Kerberos Required: False Position: Named Default value: Default Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to create the session in which the `Get-PSSession` command runs. Enter the certificate thumbprint of the certificate. This parameter configures the temporary connection that is created to run a `Get-PSSession` command with the **ComputerName** or **ConnectionUri** parameter. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they do not work with domain accounts. To get a certificate thumbprint, use a `Get-Item` or `Get-ChildItem` command in the PowerShell `Cert:` drive. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String Parameter Sets: ComputerInstanceId, ComputerName, ConnectionUriInstanceId, ConnectionUri Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies an array of names of computers. Gets the sessions that connect to the specified computers. Wildcard characters are not permitted. There is no default value. Beginning in Windows PowerShell 3.0, **PSSession** objects are stored on the computers at the remote end of each connection. To get the sessions on the specified computers, PowerShell creates a temporary connection to each computer and runs a `Get-PSSession` command. Type the NetBIOS name, an IP address, or a fully-qualified domain name of one or more computers. To specify the local computer, type the computer name, `localhost`, or a dot (`.`). > [!NOTE] > This parameter gets sessions only from computers that run Windows PowerShell 3.0 or later versions > of PowerShell. Earlier versions do not store sessions. ```yaml Type: System.String[] Parameter Sets: ComputerInstanceId, ComputerName Aliases: Cn Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ConfigurationName Specifies the name of a configuration. This cmdlet gets only to sessions that use the specified session configuration. Enter a configuration name or the fully qualified resource URI for a session configuration. If you specify only the configuration name, the following schema URI is prepended: `http://schemas.microsoft.com/powershell`. The configuration name of a session is stored in the **ConfigurationName** property of the session. The value of this parameter is used to select and filter sessions. It does not change the session configuration that the session uses. For more information about session configurations, see [about_Session_Configurations](About/about_Session_Configurations.md). ```yaml Type: System.String Parameter Sets: ComputerInstanceId, ComputerName, ConnectionUriInstanceId, ConnectionUri, ContainerId, ContainerIdInstanceId, VMId, VMIdInstanceId, VMName, VMNameInstanceId Aliases: Required: False Position: Named Default value: All sessions Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ConnectionUri Specifies a URI that defines the connection endpoint for the temporary session in which the `Get-PSSession` command runs. The URI must be fully qualified. This parameter configures the temporary connection that is created to run a `Get-PSSession` command with the **ConnectionUri** parameter. The format of this string is: `<Transport>://<ComputerName>:<Port\>/<ApplicationName>` The default value is: `http://localhost:5985/WSMAN`. If you do not specify a **ConnectionUri**, you can use the **UseSSL**, **ComputerName**, **Port**, and **ApplicationName** parameters to specify the **ConnectionURI** values. Valid values for the Transport segment of the URI are HTTP and HTTPS. If you specify a connection URI with a Transport segment, but do not specify a port, the session is created with standards ports: `80` for HTTP and `443` for HTTPS. To use the default ports for PowerShell remoting, specify port `5985` for HTTP or `5986` for HTTPS. If the destination computer redirects the connection to a different URI, PowerShell prevents the redirection unless you use the **AllowRedirection** parameter in the command. This parameter was introduced in Windows PowerShell 3.0. This parameter gets sessions only from computers that run Windows PowerShell 3.0 or later versions of Windows PowerShell. Earlier versions do not store sessions. ```yaml Type: System.Uri[] Parameter Sets: ConnectionUriInstanceId, ConnectionUri Aliases: URI, CU Required: True Position: 0 Default value: Http://localhost:5985/WSMAN Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ContainerId Specifies an array of IDs of containers. This cmdlet starts an interactive session with each of the specified containers. Use the `docker ps` command to get a list of container IDs. For more information, see the help for the [docker ps](https://docs.docker.com/engine/reference/commandline/ps/) command. ```yaml Type: System.String[] Parameter Sets: ContainerId, ContainerIdInstanceId Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Credential Specifies a user credential. This cmdlet runs the command with the permissions of the specified user. Specify a user account that has permission to connect to the remote computer and run a `Get-PSSession` command. The default is the current user. Type a user name, such as `User01` or `Domain01\User01`, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. If you type a user name, you're prompted to enter the password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). This parameter configures to the temporary connection that is created to run a `Get-PSSession` command with the **ComputerName** or **ConnectionUri** parameter. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: ComputerInstanceId, ComputerName, ConnectionUriInstanceId, ConnectionUri Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies an array of session IDs. This cmdlet gets only the sessions with the specified IDs. Type one or more IDs, separated by commas, or use the range operator (`..`) to specify a range of IDs. You cannot use the **Id** parameter together with the **ComputerName** parameter. An ID is an integer that uniquely identifies the user-managed sessions in the current session. It is easier to remember and type than the **InstanceId**, but it is unique only within the current session. The ID of a session is stored in the **Id** property of the session. ```yaml Type: System.Int32[] Parameter Sets: Id Aliases: Required: True Position: 0 Default value: All sessions Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InstanceId Specifies an array of instance IDs of sessions. This cmdlet gets only the sessions with the specified instance IDs. The instance ID is a GUID that uniquely identifies a session on a local or remote computer. The **InstanceId** is unique, even when you have multiple sessions running in PowerShell. The instance ID of a session is stored in the **InstanceId** property of the session. ```yaml Type: System.Guid[] Parameter Sets: ComputerInstanceId, ConnectionUriInstanceId, ContainerIdInstanceId, VMIdInstanceId, VMNameInstanceId, InstanceId Aliases: Required: True (ComputerInstanceId, ConnectionUriInstanceId, ContainerIdInstanceId, VMIdInstanceId, VMNameInstanceId), False (InstanceId) Position: Named Default value: All sessions Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies an array of session names. This cmdlet gets only the sessions that have the specified friendly names. Wildcard characters are permitted. The friendly name of a session is stored in the **Name** property of the session. ```yaml Type: System.String[] Parameter Sets: Name, ComputerName, ConnectionUri, ContainerId, VMId, VMName Aliases: Required: False Position: Named Default value: All sessions Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Port Specifies the specified network port that is used for the temporary connection in which the `Get-PSSession` command runs. To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are `5985`, which is the WinRM port for HTTP, and `5986`, which is the WinRM port for HTTPS. Before using an alternate port, you must configure the WinRM listener on the remote computer to listen at that port. To configure the listener, type the following two commands at the PowerShell prompt: `Remove-Item -Path WSMan:\Localhost\listener\listener* -Recurse` `New-Item -Path WSMan:\Localhost\listener -Transport http -Address * -Port \<port-number\>` This parameter configures to the temporary connection that is created to run a `Get-PSSession` command with the **ComputerName** or **ConnectionUri** parameter. Do not use the **Port** parameter unless you must. The **Port** set in the command applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on all computers. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Int32 Parameter Sets: ComputerInstanceId, ComputerName Aliases: Required: False Position: Named Default value: 5985, 5986 Accept pipeline input: False Accept wildcard characters: False ``` ### -SessionOption Specifies advanced options for the session. Enter a **SessionOption** object, such as one that you create by using the `New-PSSessionOption` cmdlet, or a hash table in which the keys are session option names and the values are session option values. The default values for the options are determined by the value of the `$PSSessionOption` preference variable, if it is set. Otherwise, the default values are established by options set in the session configuration. The session option values take precedence over default values for sessions set in the `$PSSessionOption` preference variable and in the session configuration. However, they do not take precedence over maximum values, quotas or limits set in the session configuration. For a description of the session options, including the default values, see `New-PSSessionOption`. For information about the `$PSSessionOption` preference variable, see [about_Preference_Variables](About/about_Preference_Variables.md). For more information about session configurations, see [about_Session_Configurations](About/about_Session_Configurations.md). ```yaml Type: System.Management.Automation.Remoting.PSSessionOption Parameter Sets: ComputerInstanceId, ComputerName, ConnectionUriInstanceId, ConnectionUri Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -State Specifies a session state. This cmdlet gets only sessions in the specified state. The acceptable values for this parameter are: `All`, `Opened`, `Disconnected`, `Closed`, and `Broken`. The default value is `All`. The session state value is relative to the current sessions. Sessions that were not created in the current sessions and are not connected to the current session have a state of `Disconnected` even when they are connected to a different session. The state of a session is stored in the **State** property of the session. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: Microsoft.PowerShell.Commands.SessionFilterState Parameter Sets: ComputerInstanceId, ComputerName, ConnectionUriInstanceId, ConnectionUri, ContainerId, ContainerIdInstanceId, VMId, VMIdInstanceId, VMName, VMNameInstanceId Aliases: Accepted values: All, Opened, Disconnected, Closed, Broken Required: False Position: Named Default value: All Accept pipeline input: False Accept wildcard characters: False ``` ### -ThrottleLimit Specifies the maximum number of concurrent connections that can be established to run the `Get-PSSession` command. If you omit this parameter or enter a value of `0` (zero), the default value, `32`, is used. The throttle limit applies only to the current command, not to the session or to the computer. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Int32 Parameter Sets: ComputerInstanceId, ComputerName, ConnectionUriInstanceId, ConnectionUri Aliases: Required: False Position: Named Default value: 32 Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to establish the connection in which the `Get-PSSession` command runs. By default, SSL is not used. If you use this parameter, but SSL is not available on the port used for the command, the command fails. This parameter configures the temporary connection that is created to run a `Get-PSSession` command with the **ComputerName** parameter. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerInstanceId, ComputerName Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -VMId Specifies an array of ID of virtual machines. This cmdlet starts an interactive session with each of the specified virtual machines. To see the virtual machines that are available to you, use the following command: `Get-VM | Select-Object -Property Name, ID` ```yaml Type: System.Guid[] Parameter Sets: VMId, VMIdInstanceId Aliases: VMGuid Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -VMName Specifies an array of names of virtual machines. This cmdlet starts an interactive session with each of the specified virtual machines. To see the virtual machines that are available to you, use the `Get-VM` cmdlet. ```yaml Type: System.String[] Parameter Sets: VMName, VMNameInstanceId Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.Runspaces.PSSession ## NOTES PowerShell includes the following aliases for `Get-PSSession`: - All platforms: - `gsn` - This cmdlet gets user-managed sessions **PSSession** objects" such as those that are created by using the `New-PSSession`, `Enter-PSSession`, and `Invoke-Command` cmdlets. It does not get the system-managed session that is created when you start PowerShell. - Starting in Windows PowerShell 3.0, **PSSession** objects are stored on the computer that is at the server-side or receiving end of a connection. To get the sessions that are stored on the local computer or a remote computer, PowerShell establishes a temporary session to the specified computer and runs query commands in the session. - To get sessions that connect to a remote computer, use the **ComputerName** or **ConnectionUri** parameters to specify the remote computer. To filter the sessions that `Get-PSSession` gets, use the **Name**, **Id**, **InstanceId**, and **State** parameters. Use the remaining parameters to configure the temporary session that `Get-PSSession` uses. - When you use the **ComputerName** or **ConnectionUri** parameters, `Get-PSSession` gets only sessions from computers running Windows PowerShell 3.0 and later versions of PowerShell. - The value of the **State** property of a **PSSession** is relative to the current session. Therefore, a value of **Disconnected** means that the **PSSession** is not connected to the current session. However, it does not mean that the **PSSession** is disconnected from all sessions. It might be connected to a different session. To determine whether you can connect or reconnect to the **PSSession** from the current session, use the **Availability** property. An **Availability** value of **None** indicates that you can connect to the session. A value of **Busy** indicates that you cannot connect to the **PSSession** because it is connected to another session. For more information about the values of the **State** property of sessions, see [RunspaceState Enumeration](/dotnet/api/system.management.automation.runspaces.runspacestate). For more information about the values of the **Availability** property of sessions, see [RunspaceAvailability Enumeration](/dotnet/api/system.management.automation.runspaces.runspaceavailability). ## RELATED LINKS [Connect-PSSession](Connect-PSSession.md) [Disconnect-PSSession](Disconnect-PSSession.md) [Receive-PSSession](Receive-PSSession.md) [Enter-PSSession](Enter-PSSession.md) [Exit-PSSession](Exit-PSSession.md) [Invoke-Command](Invoke-Command.md) [New-PSSession](New-PSSession.md) [Remove-PSSession](Remove-PSSession.md) [about_PSSessions](About/about_PSSessions.md) [about_Remote](About/about_Remote.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Get-PSSessionCapability.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 09/28/2021 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/get-pssessioncapability?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-PSSessionCapability --- # Get-PSSessionCapability ## SYNOPSIS Gets the capabilities of a specific user on a constrained session configuration. ## SYNTAX ``` Get-PSSessionCapability [-ConfigurationName] <String> [-Username] <String> [-Full] [<CommonParameters>] ``` ## DESCRIPTION The `Get-PSSessionCapability` cmdlet gets the capabilities of a specific user on a constrained session configuration. Use this cmdlet to audit customized session configurations for users. Starting in Windows PowerShell 5.0, you can use the **RoleDefinitions** property in a session configuration (`.pssc`) file. Using this property lets you grant users different capabilities on a single constrained endpoint based on group membership. The `Get-PSSessionCapability` cmdlet reduces complexity when auditing these endpoints by letting you determine the exact capabilities granted to a user. By default, the `Get-PSSessionCapability` cmdlet returns a list of commands the specified user can run in the specified endpoint. This is equivalent to the user running `Get-Command` in the specified endpoint. When run with the **Full** parameter, this cmdlet returns an **InitialSessionState** object. This object contains details about the PowerShell runspace the specified user would interact with for the specified endpoint. It includes information such as Language Mode, Execution Policy, and Environmental Variables. ## EXAMPLES ### Example 1: Get commands available for a user ```powershell Get-PSSessionCapability -ConfigurationName Endpoint1 -Username 'CONTOSO\User' ``` This example returns the commands available to the user CONTOSO\User when connecting to the Endpoint1 constrained endpoint on the local computer. ### Example 2: Get details about a runspace for a user ```powershell Get-PSSessionCapability -ConfigurationName Endpoint1 -Username 'CONTOSO\User' -Full ``` This example returns details about the runspace the user CONTOSO\User would interact with when connecting to the Endpoint1 constrained endpoint. ## PARAMETERS ### -ConfigurationName Specifies the constrained session configuration (endpoint) that you are inspecting. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Full Indicates that this cmdlet returns the entire initial session state for the specified user at the specified constrained endpoint. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Username Specifies the user whose capabilities you are inspecting. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ### System.Management.Automation.AliasInfo ### System.Management.Automation.FunctionInfo ### System.Management.Automation.Runspaces.InitialSessionState ## NOTES ## RELATED LINKS [New-PSRoleCapabilityFile](New-PSRoleCapabilityFile.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Get-PSSessionConfiguration.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/get-pssessionconfiguration?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-PSSessionConfiguration --- # Get-PSSessionConfiguration ## SYNOPSIS Gets the registered session configurations on the computer. ## SYNTAX ``` Get-PSSessionConfiguration [[-Name] <String[]>] [-Force] [<CommonParameters>] ``` ## DESCRIPTION The `Get-PSSessionConfiguration` cmdlet gets the session configurations that have been registered on the local computer. This is an advanced cmdlet that is designed to be used by system administrators to manage customized session configurations for their users. Beginning in PowerShell 3.0, you can define the properties of a session configuration by using a session configuration (.pssc) file. This feature lets you create customized and restricted sessions without writing a computer program. For more information about session configuration files, see [about_Session_Configuration_Files](About/about_Session_Configuration_Files.md). Also, beginning in PowerShell 3.0, new note properties have been added to the session configuration object that `Get-PSSessionConfiguration` returns. These properties make it easier for users and session configuration authors to examine and compare session configurations. To create and register a session configuration, use the `Register-PSSessionConfiguration` cmdlet. For more information about session configurations, see [about_Session_Configurations](About/about_Session_Configurations.md). ## EXAMPLES ### Example 1 - Get session configurations on the local computer ```powershell Get-PSSessionConfiguration ``` ### Example 2 - Get the two default session configurations The command uses the **Name** parameter of `Get-PSSessionConfiguration` to get only the session configurations with names that begin with "Microsoft". ```powershell Get-PSSessionConfiguration -Name Microsoft* ``` ```Output Name PSVersion StartupScript Permission ---- --------- ------------- ---------- microsoft.powershell 5.1 BUILTIN\Administrators AccessAll... microsoft.powershell32 5.1 BUILTIN\Administrators AccessAll... ``` ### Example 3 - Get the properties and values of a session configuration This example shows the properties and property values of a session configuration that was created by using a session configuration file. ```powershell Get-PSSessionConfiguration -Name Full | Format-List -Property * ``` ```Output Copyright : (c) 2011 User01. All rights reserved. AliasDefinitions : {System.Collections.Hashtable} SessionType : Default CompanyName : Unknown GUID : 1e9cb265-dae0-4bd3-89a9-8338a47698a1 Author : User01 ExecutionPolicy : Restricted SchemaVersion : 1.0.0.0 LanguageMode : FullLanguage Architecture : 64 Filename : %windir%\system32\pwrshplugin.dll ResourceUri : http://schemas.microsoft.com/powershell/Full MaxConcurrentCommandsPerShell : 1500 UseSharedProcess : false ProcessIdleTimeoutSec : 0 xmlns : http://schemas.microsoft.com/wbem/wsman/1/config/PluginConfiguration MaxConcurrentUsers : 10 lang : en-US SupportsOptions : true ExactMatch : true configfilepath : C:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\Full_1e9cb265-dae0-4bd3-89a9-8338a47698a1.pssc RunAsUser : IdleTimeoutms : 7200000 PSVersion : 3.0 OutputBufferingMode : Block AutoRestart : false MaxShells : 300 MaxMemoryPerShellMB : 1024 MaxIdleTimeoutMs : 43200000 SDKVersion : 1 Name : Full XmlRenderingType : text Capability : {Shell} RunAsPassword : MaxProcessesPerShell : 25 Enabled : True MaxShellsPerUser : 30 Permission : ``` The example uses the `Get-PSSessionConfiguration` cmdlet to get the full session configuration. A pipeline operator sends the Full session configuration to the `Format-List` cmdlet. The **Property** parameter with a value of `*` (all) directs `Format-List` to display all the properties and values of the object in a list. The output includes useful information, including the author of the session configuration, the session type, language mode, and execution policy of sessions that are created with this session configuration, session quotas, and the full path to the session configuration file. This view of a session configuration is used for sessions that include a session configuration file. For more information about session configuration files, see [about_Session_Configuration_Files](About/about_Session_Configuration_Files.md). ### Example 4 - Another way to look at the session configurations This example uses the `Get-ChildItem` cmdlet (alias `dir`) in the WSMan: provider drive to look at the content of the Plugin node. This is another way to look at the session configurations on the computer. ```powershell dir WSMan:\localhost\plugin ``` ```Output Type Keys Name ---- ---- ---- Container {Name=Event Forwarding Plugin} Event Forwarding Plugin Container {Name=Full} Full Container {Name=microsoft.powershell} microsoft.powershell Container {Name=microsoft.powershell.workf... microsoft.powershell.workflow Container {Name=microsoft.powershell32} microsoft.powershell32 Container {Name=microsoft.ServerManager} microsoft.ServerManager Container {Name=WMI Provider} WMI Provider ``` The **PlugIn** node contains **ContainerElement** objects (Microsoft.WSMan.Management.WSManConfigContainerElement) that represent the registered PowerShell session configurations, along with other plug-ins for WS-Management. ### Example 6 - View session configurations on a remote computer This example shows how to use the WSMan provider to view the session configurations on a remote computer. This method does not provide as much information as a `Get-PSSessionConfiguration` command, but the user does not need to be a member of the Administrators group to run this cmdlet. ```powershell Connect-WSMan -ComputerName Server01 dir WSMan:\Server01\Plugin ``` ```Output WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin Type Keys Name ---- ---- ---- Container {Name=Empty} Empty Container {Name=Event Forwarding Plugin} Event Forwarding Plugin Container {Name=Full} Full Container {Name=microsoft.powershell} microsoft.powershell Container {Name=microsoft.powershell.workf... microsoft.powershell.workflow Container {Name=microsoft.powershell32} microsoft.powershell32 Container {Name=microsoft.ServerManager} microsoft.ServerManager Container {Name=NoLanguage} NoLanguage Container {Name=RestrictedLang} RestrictedLang Container {Name=RRS} RRS Container {Name=SEL Plugin} SEL Plugin Container {Name=WithProfile} WithProfile Container {Name=WMI Provider} WMI Provider ``` The `Connect-WSMan` cmdlet connects to the WinRM service on the Server01 remote computer. The `Get-ChildItem` cmdlet (alias `dir`) of the WSMan: drive gets the items in the **Server01\Plugin** path. The output shows the items in the Plugin directory on the Server01 computer. The items include the session configurations, which are a type of WSMan plug-in, along with other types of plug-ins on the computer. ### Example 7 - Get detailed session configurations from a remote computer This example shows how to run a `Get-PSSessionConfiguration` command on a remote computer. The command requires that CredSSP delegation be enabled in the client settings on the local computer and in the service settings on the remote computer. To run the commands in this example, you must be a member of the Administrators group on the local and remote computers and you must start PowerShell with the **Run as administrator** option. ```powershell Enable-WSManCredSSP -Delegate Server02 Connect-WSMan Server02 Set-Item WSMan:\Server02*\Service\Auth\CredSSP -Value $true Invoke-Command -ScriptBlock {Get-PSSessionConfiguration} -ComputerName Server02 -Authentication CredSSP -Credential Domain01\Admin01 ``` ```Output Name PSVersion StartupScript Permission PSComputerName ---- --------- ------------- ---------- -------------- microsoft.powershell 5.1 BUILTIN\Administrators AccessAll... server02.corp.fabrikam.com microsoft.powershell32 5.1 BUILTIN\Administrators AccessAll... server02.corp.fabrikam.com MyX86Shell 5.1 C:\test\x86Shell.ps1 BUILTIN\Administrators AccessAll... server02.corp.fabrikam.com ``` The `Enable-WSManCredSSP` cmdlet enables **CredSSP** delegation on Server01, the local computer. The `Connect-WSMan` cmdlet connects to Server02 computer. This action adds a node for Server02 to the WSMan: drive on the local computer, allowing you to view and change the WS-Management settings on the Server02 computer. The `Set-Item` cmdlet changes the value of the **CredSSP** item in the Service node of the Server02 computer to **True**. This configures the service settings on the remote computer. The `Invoke-Command` cmdlet runs the`Get-PSSessionConfiguration` command on the Server02 computer. The command uses the **Credential** parameter, and it uses the **Authentication** parameter with a value of **CredSSP**. The output shows the session configurations on the Server02 remote computer. ### Example 8 - Get the resource URI of a session configuration This example is useful for setting the value of the `$PSSessionConfigurationName` preference variable, which takes a resource URI. ```powershell (Get-PSSessionConfiguration -Name CustomShell).ResourceUri ``` ```Output http://schemas.microsoft.com/powershell/microsoft.CustomShell ``` The `$PSSessionConfigurationName` variable specifies the default configuration that is used when you create a session. This variable is set on the local computer, but it specifies a configuration on the remote computer. For more information about the `$PSSessionConfiguration` variable, see [about_Preference_Variables](About/about_Preference_Variables.md). ## PARAMETERS ### -Force Suppresses the prompt to restart the WinRM service, if the service is not already running. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Gets only the session configurations with the specified name or name pattern. Enter one or more session configuration names. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: All session configurations on the local computer Accept pipeline input: False Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](./About/about_CommonParameters.md). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#PSSessionConfiguration ## NOTES - To run this cmdlet, start PowerShell with the **Run as administrator** option. - To view the session configurations on the computer, you must be a member of the Administrators group on the computer. - To run a `Get-PSSessionConfiguration` command on a remote computer, Credential Security Service Provider (CredSSP) authentication must be enabled in the client settings on the local computer (by using the `Enable-WSManCredSSP` cmdlet) and in the service settings on the remote computer. Also, you must use the **CredSSP** value of the **Authentication** parameter when establishing the remote session. Otherwise, access is denied. - The note properties of the object that `Get-PSSessionConfiguration` returns appear on the object only when they have a value. Only session configurations that were created by using a session configuration file have all the defined properties. - The properties of a session configuration object vary with the options set for the session configuration and the values of those options. Also, session configurations that use a session configuration file have additional properties. - You can use commands in the WSMan: drive to change the properties of session configurations. However, you cannot use the WSMan: drive in PowerShell 2.0 to change session configuration properties that are introduced in PowerShell 3.0, such as **OutputBufferingMode**. PowerShell 2.0 commands do not generate an error, but they are ineffective. To change properties introduced in PowerShell 3.0, use the WSMan: drive in PowerShell 3.0. ## RELATED LINKS [Disable-PSSessionConfiguration](Disable-PSSessionConfiguration.md) [Enable-PSSessionConfiguration](Enable-PSSessionConfiguration.md) [Get-PSSessionConfiguration](Get-PSSessionConfiguration.md) [New-PSSessionConfigurationFile](New-PSSessionConfigurationFile.md) [New-PSSessionOption](New-PSSessionOption.md) [Register-PSSessionConfiguration](Register-PSSessionConfiguration.md) [Set-PSSessionConfiguration](Set-PSSessionConfiguration.md) [Test-PSSessionConfigurationFile](Test-PSSessionConfigurationFile.md) [Unregister-PSSessionConfiguration](Unregister-PSSessionConfiguration.md) [WSMan Provider](../microsoft.wsman.management/about/about_WSMan_Provider.md) [about_Session_Configurations](About/about_Session_Configurations.md) [about_Session_Configuration_Files](About/about_Session_Configuration_Files.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Get-PSSubsystem.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 10/15/2020 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/get-pssubsystem?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-PSSubsystem --- # Get-PSSubsystem ## SYNOPSIS Retrieves information about the subsystems registered in PowerShell. ## SYNTAX ### GetAllSet (Default) ``` Get-PSSubsystem [<CommonParameters>] ``` ### GetByKindSet ``` Get-PSSubsystem -Kind <SubsystemKind> [<CommonParameters>] ``` ### GetByTypeSet ``` Get-PSSubsystem -SubsystemType <Type> [<CommonParameters>] ``` ## DESCRIPTION Retrieves information about the subsystems registered in PowerShell. > [!NOTE] > This is an experimental feature. This cmdlet is only available when the `PSSubsystemPluginModel` > feature is enabled. For more information, see > [Using Experimental Features](/powershell/scripting/learn/experimental-features). The feature makes it possible to separate components of `System.Management.Automation.dll` into individual subsystems that reside in their own assembly. This separation reduces the disk footprint of the core PowerShell engine and allows these components to become optional features for a minimal PowerShell installation. Currently, only the **CommandPredictor** subsystem is supported. This subsystem is used along with the PSReadLine module to provide custom prediction plugins. In future, **Job**, **CommandCompleter**, **Remoting** and other components could be separated into subsystem assemblies outside of `System.Management.Automation.dll`. ## EXAMPLES ### Example 1 - Display all available subsystems ```powershell Get-PSSubsystem ``` ```Output Kind SubsystemType IsRegistered Implementations ---- ------------- ------------ --------------- CommandPredictor ICommandPredictor False {} ``` ### Example 2 - Display all available subsystems of a specific kind ```powershell PS> Get-PSSubsystem -Kind CommandPredictor | Format-List ``` ```Output Kind : CommandPredictor SubsystemType : System.Management.Automation.Subsystem.ICommandPredictor AllowUnregistration : True AllowMultipleRegistration : True RequiredCmdlets : {} RequiredFunctions : {} IsRegistered : False Implementations : {} ``` ## PARAMETERS ### -Kind Specifies the kind of subsystem to be returned. Valid values are: `CommandPredictor`. ```yaml Type: System.Management.Automation.Subsystem.SubsystemKind Parameter Sets: GetByKindSet Aliases: Accepted values: CommandPredictor Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -SubsystemType Specifies the type of subsystem to be returned. ```yaml Type: System.Type Parameter Sets: GetByTypeSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.Subsystem.SubsystemKind ### System.Type ## OUTPUTS ### System.Management.Automation.Subsystem.SubsystemInfo ## NOTES ## RELATED LINKS [about_Experimental_Features](about/about_experimental_features.md) [Disable-ExperimentalFeature](Disable-ExperimentalFeature.md) [Enable-ExperimentalFeature](Get-ExperimentalFeature.md) [Get-ExperimentalFeature](Get-ExperimentalFeature.md) [Using Experimental Features](/powershell/scripting/learn/experimental-features)

#File: reference/7.6/Microsoft.PowerShell.Core/Import-Module.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 06/07/2024 no-loc: [Import-Module, -Scope] online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/import-module?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Import-Module --- # Import-Module ## SYNOPSIS Adds modules to the current session. ## SYNTAX ### Name (Default) ``` Import-Module [-Global] [-Prefix <String>] [-Name] <String[]> [-Function <String[]>] [-Cmdlet <String[]>] [-Variable <String[]>] [-Alias <String[]>] [-Force] [-SkipEditionCheck] [-PassThru] [-AsCustomObject] [-MinimumVersion <Version>] [-MaximumVersion <String>] [-RequiredVersion <Version>] [-ArgumentList <Object[]>] [-DisableNameChecking] [-NoClobber] [-Scope <String>] [<CommonParameters>] ``` ### PSSession ``` Import-Module [-Global] [-Prefix <String>] [-Name] <String[]> [-Function <String[]>] [-Cmdlet <String[]>] [-Variable <String[]>] [-Alias <String[]>] [-Force] [-SkipEditionCheck] [-PassThru] [-AsCustomObject] [-MinimumVersion <Version>] [-MaximumVersion <String>] [-RequiredVersion <Version>] [-ArgumentList <Object[]>] [-DisableNameChecking] [-NoClobber] [-Scope <String>] -PSSession <PSSession> [<CommonParameters>] ``` ### CimSession ``` Import-Module [-Global] [-Prefix <String>] [-Name] <String[]> [-Function <String[]>] [-Cmdlet <String[]>] [-Variable <String[]>] [-Alias <String[]>] [-Force] [-SkipEditionCheck] [-PassThru] [-AsCustomObject] [-MinimumVersion <Version>] [-MaximumVersion <String>] [-RequiredVersion <Version>] [-ArgumentList <Object[]>] [-DisableNameChecking] [-NoClobber] [-Scope <String>] -CimSession <CimSession> [-CimResourceUri <Uri>] [-CimNamespace <String>] [<CommonParameters>] ``` ### UseWindowsPowerShell ``` Import-Module [-Name] <string[]> -UseWindowsPowerShell [-Global] [-Prefix <string>] [-Function <string[]>] [-Cmdlet <string[]>] [-Variable <string[]>] [-Alias <string[]>] [-Force] [-PassThru] [-AsCustomObject] [-MinimumVersion <version>] [-MaximumVersion <string>] [-RequiredVersion <version>] [-ArgumentList <Object[]>] [-DisableNameChecking] [-NoClobber] [-Scope <string>] [<CommonParameters>] ``` ### FullyQualifiedName ``` Import-Module [-Global] [-Prefix <String>] [-FullyQualifiedName] <ModuleSpecification[]> [-Function <String[]>] [-Cmdlet <String[]>] [-Variable <String[]>] [-Alias <String[]>] [-Force] [-SkipEditionCheck] [-PassThru] [-AsCustomObject] [-ArgumentList <Object[]>] [-DisableNameChecking] [-NoClobber] [-Scope <String>] [<CommonParameters>] ``` ### FullyQualifiedNameAndPSSession ``` Import-Module [-Global] [-Prefix <String>] [-FullyQualifiedName] <ModuleSpecification[]> [-Function <String[]>] [-Cmdlet <String[]>] [-Variable <String[]>] [-Alias <String[]>] [-Force] [-SkipEditionCheck] [-PassThru] [-AsCustomObject] [-ArgumentList <Object[]>] [-DisableNameChecking] [-NoClobber] [-Scope <String>] -PSSession <PSSession> [<CommonParameters>] ``` ### FullyQualifiedNameAndUseWindowsPowerShell ``` Import-Module [-FullyQualifiedName] <ModuleSpecification[]> -UseWindowsPowerShell [-Global] [-Prefix <string>] [-Function <string[]>] [-Cmdlet <string[]>] [-Variable <string[]>] [-Alias <string[]>] [-Force] [-PassThru] [-AsCustomObject] [-ArgumentList <Object[]>] [-DisableNameChecking] [-NoClobber] [-Scope <string>] [<CommonParameters>] ``` ### Assembly ``` Import-Module [-Global] [-Prefix <String>] [-Assembly] <Assembly[]> [-Function <String[]>] [-Cmdlet <String[]>] [-Variable <String[]>] [-Alias <String[]>] [-Force] [-SkipEditionCheck] [-PassThru] [-AsCustomObject] [-ArgumentList <Object[]>] [-DisableNameChecking] [-NoClobber] [-Scope <String>] [<CommonParameters>] ``` ### ModuleInfo ``` Import-Module [-Global] [-Prefix <String>] [-Function <String[]>] [-Cmdlet <String[]>] [-Variable <String[]>] [-Alias <String[]>] [-Force] [-SkipEditionCheck] [-PassThru] [-AsCustomObject] [-ModuleInfo] <PSModuleInfo[]> [-ArgumentList <Object[]>] [-DisableNameChecking] [-NoClobber] [-Scope <String>] [<CommonParameters>] ``` ## DESCRIPTION The `Import-Module` cmdlet adds one or more modules to the current session. Starting in PowerShell 3.0, installed modules are automatically imported to the session when you use any commands or providers in the module. However, you can still use the `Import-Module` command to import a module. You can disable automatic module importing using the `$PSModuleAutoLoadingPreference` preference variable. For more information about the `$PSModuleAutoLoadingPreference` variable, see [about_Preference_Variables](About/about_Preference_Variables.md). A module is a package that contains members that can be used in PowerShell. Members include cmdlets, providers, scripts, functions, variables, and other tools and files. After a module is imported, you can use the module members in your session. For more information about modules, see [about_Modules](About/about_Modules.md). By default, `Import-Module` imports all members that the module exports, but you can use the **Alias**, **Function**, **Cmdlet**, and **Variable** parameters to restrict which members are imported. The **NoClobber** parameter prevents `Import-Module` from importing members that have the same names as members in the current session. `Import-Module` imports a module only into the current session. To import the module into every new session, add an `Import-Module` command to your PowerShell profile. For more information about profiles, see [about_Profiles](About/about_Profiles.md). You can manage remote Windows computers that have PowerShell remoting enabled by creating a **PSSession** on the remote computer. Then use the **PSSession** parameter of `Import-Module` to import the modules that are installed on the remote computer. When you use the imported commands in the current session the commands implicitly run on the remote computer. Starting in Windows PowerShell 3.0, you can use `Import-Module` to import Common Information Model (CIM) modules. CIM modules define cmdlets in Cmdlet Definition XML (CDXML) files. This feature lets you use cmdlets that are implemented in non-managed code assemblies, such as those written in C++. For remote computers that don't have PowerShell remoting enabled, including computers that aren't running the Windows operating system, you can use the **CimSession** parameter of `Import-Module` to import CIM modules from the remote computer. The imported commands run implicitly on the remote computer. A **CIMSession** is a connection to Windows Management Instrumentation (WMI) on the remote computer. ## EXAMPLES ### Example 1: Import the members of a module into the current session This example imports the members of the **PSDiagnostics** module into the current session. ```powershell Import-Module -Name PSDiagnostics ``` ### Example 2: Import all modules specified by the module path This example imports all available modules in the path specified by the `$Env:PSModulePath` environment variable into the current session. ```powershell Get-Module -ListAvailable | Import-Module ``` ### Example 3: Import the members of several modules into the current session This example imports the members of the **PSDiagnostics** and **Dism** modules into the current session. ```powershell $m = Get-Module -ListAvailable PSDiagnostics, Dism Import-Module -ModuleInfo $m ``` The `Get-Module` cmdlet gets the **PSDiagnostics** and **Dism** modules and saves the objects in the `$m` variable. The **ListAvailable** parameter is required when you're getting modules that aren't yet imported into the session. The **ModuleInfo** parameter of `Import-Module` is used to import the modules into the current session. ### Example 4: Import all modules specified by a path This example uses an explicit path to identify the module to import. ```powershell Import-Module -Name C:\ps-test\modules\test -Verbose ``` ```Output VERBOSE: Loading module from path 'C:\ps-test\modules\Test\Test.psm1'. VERBOSE: Exporting function 'my-parm'. VERBOSE: Exporting function 'Get-Parameter'. VERBOSE: Exporting function 'Get-Specification'. VERBOSE: Exporting function 'Get-SpecDetails'. ``` Using the **Verbose** parameter causes `Import-Module` to report progress as it loads the module. Without the **Verbose**, **PassThru**, or **AsCustomObject** parameter, `Import-Module` doesn't generate any output when it imports a module. ### Example 5: Restrict module members imported into a session This example shows how to restrict which module members are imported into the session and the effect of this command on the session. The **Function** parameter limits the members that are imported from the module. You can also use the **Alias**, **Variable**, and **Cmdlet** parameters to restrict other members that a module imports. The `Get-Module` cmdlet gets the object that represents the **PSDiagnostics** module. The **ExportedCmdlets** property lists all the cmdlets that the module exports, even though they were not all imported. ```powershell Import-Module PSDiagnostics -Function Disable-PSTrace, Enable-PSTrace (Get-Module PSDiagnostics).ExportedCommands ``` ```Output Key Value --- ----- Disable-PSTrace Disable-PSTrace Disable-PSWSManCombinedTrace Disable-PSWSManCombinedTrace Disable-WSManTrace Disable-WSManTrace Enable-PSTrace Enable-PSTrace Enable-PSWSManCombinedTrace Enable-PSWSManCombinedTrace Enable-WSManTrace Enable-WSManTrace Get-LogProperties Get-LogProperties Set-LogProperties Set-LogProperties Start-Trace Start-Trace Stop-Trace Stop-Trace ``` ```powershell Get-Command -Module PSDiagnostics ``` ```Output CommandType Name Version Source ----------- ---- ------- ------ Function Disable-PSTrace 6.1.0.0 PSDiagnostics Function Enable-PSTrace 6.1.0.0 PSDiagnostics ``` Using the **Module** parameter of the `Get-Command` cmdlet shows the commands that were imported from the **PSDiagnostics** module. The results confirm that only the `Disable-PSTrace` and `Enable-PSTrace` cmdlets were imported. ### Example 6: Import the members of a module and add a prefix This example imports the **PSDiagnostics** module into the current session, adds a prefix to the member names, and then displays the prefixed member names. The **Prefix** parameter of `Import-Module` adds the `x` prefix to all members that are imported from the module. The prefix applies only to the members in the current session. It doesn't change the module. The **PassThru** parameter returns a module object that represents the imported module. ```powershell Import-Module PSDiagnostics -Prefix x -PassThru ``` ```Output ModuleType Version Name ExportedCommands ---------- ------- ---- ---------------- Script 6.1.0.0 PSDiagnostics {Disable-xPSTrace, Disable-xPSWSManCombinedTrace, Disable-xW... ``` ```powershell Get-Command -Module PSDiagnostics ``` ```Output CommandType Name Version Source ----------- ---- ------- ------ Function Disable-xPSTrace 6.1.0.0 PSDiagnostics Function Disable-xPSWSManCombinedTrace 6.1.0.0 PSDiagnostics Function Disable-xWSManTrace 6.1.0.0 PSDiagnostics Function Enable-xPSTrace 6.1.0.0 PSDiagnostics Function Enable-xPSWSManCombinedTrace 6.1.0.0 PSDiagnostics Function Enable-xWSManTrace 6.1.0.0 PSDiagnostics Function Get-xLogProperties 6.1.0.0 PSDiagnostics Function Set-xLogProperties 6.1.0.0 PSDiagnostics Function Start-xTrace 6.1.0.0 PSDiagnostics Function Stop-xTrace 6.1.0.0 PSDiagnostics ``` `Get-Command` gets the members that have been imported from the module. The output shows that the module members were correctly prefixed. ### Example 7: Get and use a custom object This example demonstrates how to get and use the custom object returned by `Import-Module`. Custom objects include synthetic members that represent each of the imported module members. For example, the cmdlets and functions in a module are converted to script methods of the custom object. Custom objects are useful in scripting. They're also useful when several imported objects have the same names. Using the script method of an object is equivalent to specifying the fully qualified name of an imported member, including its module name. The **AsCustomObject** parameter is only usable when importing a script module. Use `Get-Module` to determine which of the available modules is a script module. ```powershell Get-Module -List | Format-Table -Property Name, ModuleType -AutoSize ``` ```Output Name ModuleType ---- ---------- Show-Calendar Script BitsTransfer Manifest PSDiagnostics Manifest TestCmdlets Script ... ``` ```powershell $a = Import-Module -Name Show-Calendar -AsCustomObject -PassThru $a | Get-Member ``` ```Output 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() Show-Calendar ScriptMethod System.Object Show-Calendar(); ``` ```powershell $a."Show-Calendar"() ``` The `Show-Calendar` script module is imported using the **AsCustomObject** parameter to request a custom object and the **PassThru** parameter to return the object. The resulting custom object is saved in the `$a` variable. The `$a` variable is piped to the `Get-Member` cmdlet to show the properties and methods of the saved object. The output shows a `Show-Calendar` script method. To call the `Show-Calendar` script method, the method name must be enclosed in quotation marks because the name includes a hyphen. ### Example 8: Reimport a module into the same session This example shows how to use the **Force** parameter of `Import-Module` when you're reimporting a module into the same session. The **Force** parameter removes the loaded module and then imports it again. ```powershell Import-Module PSDiagnostics Import-Module PSDiagnostics -Force -Prefix PS ``` The first command imports the **PSDiagnostics** module. The second command imports the module again, this time using the **Prefix** parameter. Without the **Force** parameter, the session would include two copies of each **PSDiagnostics** cmdlet, one with the standard name and one with the prefixed name. ### Example 9: Run commands that have been hidden by imported commands This example shows how to run commands that have been hidden by imported commands. The **TestModule** module includes a function named `Get-Date` that returns the year and day of the year. ```powershell Get-Date ``` ```Output Thursday, August 15, 2019 2:26:12 PM ``` ```powershell Import-Module TestModule Get-Date ``` ```Output 19227 ``` ```powershell Get-Command Get-Date -All | Format-Table -Property CommandType, Name, ModuleName -AutoSize ``` ```Output CommandType Name ModuleName ----------- ---- ---------- Function Get-Date TestModule Cmdlet Get-Date Microsoft.PowerShell.Utility ``` ```powershell Microsoft.PowerShell.Utility\Get-Date ``` ```Output Thursday, August 15, 2019 2:28:31 PM ``` The first `Get-Date` cmdlet returns a **DateTime** object with the current date. After importing the **TestModule** module, `Get-Date` returns the year and day of the year. Using the **All** parameter of `Get-Command` show all the `Get-Date` commands in the session. The results show that there are two `Get-Date` commands in the session, a function from the **TestModule** module and a cmdlet from the **Microsoft.PowerShell.Utility** module. Because functions take precedence over cmdlets, the `Get-Date` function from the **TestModule** module runs, instead of the `Get-Date` cmdlet. To run the original version of `Get-Date`, you must qualify the command name with the module name. For more information about command precedence in PowerShell, see [about_Command_Precedence](about/about_Command_Precedence.md). ### Example 10: Import a minimum version of a module This example imports the **PowerShellGet** module. It uses the **MinimumVersion** parameter of `Import-Module` to import only version `2.0.0` or greater of the module. ```powershell Import-Module -Name PowerShellGet -MinimumVersion 2.0.0 ``` You can also use the **RequiredVersion** parameter to import a particular version of a module, or use the **Module** and **Version** parameters of the `#Requires` keyword to require a particular version of a module in a script. ### Example 11: Import using a fully qualified name This example imports a specific version of a module using the **FullyQualifiedName**. ```powershell PS> Get-Module -ListAvailable PowerShellGet | Select-Object Name, Version Name Version ---- ------- PowerShellGet 2.2.1 PowerShellGet 2.1.3 PowerShellGet 2.1.2 PowerShellGet 1.0.0.1 PS> Import-Module -FullyQualifiedName @{ModuleName = 'PowerShellGet'; ModuleVersion = '2.1.3' } ``` ### Example 12: Import using a fully qualified path This example imports a specific version of a module using the fully qualified path. ```powershell PS> Get-Module -ListAvailable PowerShellGet | Select-Object Path Path ---- C:\Program Files\PowerShell\Modules\PowerShellGet\2.2.1\PowerShellGet.psd1 C:\Program Files\PowerShell\6\Modules\PowerShellGet\PowerShellGet.psd1 C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\2.1.2\PowerShellGet.psd1 C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PowerShellGet.psd1 PS> Import-Module -Name 'C:\Program Files\PowerShell\Modules\PowerShellGet\2.2.1\PowerShellGet.psd1' ``` ### Example 13: Import a module from a remote computer This example shows how to use the `Import-Module` cmdlet to import a module from a remote computer. This command uses the Implicit Remoting feature of PowerShell. When you import modules from another session, you can use the cmdlets in the current session. However, commands that use the cmdlets run in the remote session. ```powershell $s = New-PSSession -ComputerName Server01 Get-Module -PSSession $s -ListAvailable -Name NetSecurity ``` ```Output ModuleType Name ExportedCommands ---------- ---- ---------------- Manifest NetSecurity {New-NetIPsecAuthProposal, New-NetIPsecMainModeCryptoProposal, New-Ne... ``` ```powershell Import-Module -PSSession $s -Name NetSecurity Get-Command -Module NetSecurity -Name Get-*Firewall* ``` ```Output CommandType Name ModuleName ----------- ---- ---------- Function Get-NetFirewallAddressFilter NetSecurity Function Get-NetFirewallApplicationFilter NetSecurity Function Get-NetFirewallInterfaceFilter NetSecurity Function Get-NetFirewallInterfaceTypeFilter NetSecurity Function Get-NetFirewallPortFilter NetSecurity Function Get-NetFirewallProfile NetSecurity Function Get-NetFirewallRule NetSecurity Function Get-NetFirewallSecurityFilter NetSecurity Function Get-NetFirewallServiceFilter NetSecurity Function Get-NetFirewallSetting NetSecurity ``` ```powershell Get-NetFirewallRule -DisplayName "Windows Remote Management*" | Format-Table -Property DisplayName, Name -AutoSize ``` ```Output DisplayName Name ----------- ---- Windows Remote Management (HTTP-In) WINRM-HTTP-In-TCP Windows Remote Management (HTTP-In) WINRM-HTTP-In-TCP-PUBLIC Windows Remote Management - Compatibility Mode (HTTP-In) WINRM-HTTP-Compat-In-TCP ``` `New-PSSession` creates a remote session (**PSSession**) to the `Server01` computer. The **PSSession** is saved in the `$s` variable. Running `Get-Module` with the **PSSession** parameter shows that the **NetSecurity** module is installed and available on the remote computer. This command is equivalent to using the `Invoke-Command` cmdlet to run `Get-Module` command in the remote session. For example: `Invoke-Command $s {Get-Module -ListAvailable -Name NetSecurity` Running `Import-Module` with the **PSSession** parameter imports the **NetSecurity** module from the remote computer into the current session. The `Get-Command` cmdlet retrieves commands that begin with `Get` and include `Firewall` from the **NetSecurity** module. The output confirms that the module and its cmdlets were imported into the current session. Next, the `Get-NetFirewallRule` cmdlet gets Windows Remote Management firewall rules on the `Server01` computer. This is equivalent to using the `Invoke-Command` cmdlet to run `Get-NetFirewallRule` on the remote session. ### Example 14: Manage storage on a remote computer without the Windows operating system In this example, the administrator of the computer has installed the Module Discovery WMI provider, which allows you to use CIM commands that are designed for the provider. The `New-CimSession` cmdlet creates a session on the remote computer named RSDGF03. The session connects to the WMI service on the remote computer. The CIM session is saved in the `$cs` variable. `Import-Module` uses the **CimSession** in `$cs` to import the **Storage** CIM module from the `RSDGF03` computer. The `Get-Command` cmdlet shows the `Get-Disk` command in the **Storage** module. When you import a CIM module into the local session, PowerShell converts the CDXML files for each command into PowerShell scripts, which appear as functions in the local session. Although `Get-Disk` is typed in the local session, the cmdlet implicitly runs on the remote computer from which it was imported. The command returns objects from the remote computer to the local session. ```powershell $cs = New-CimSession -ComputerName RSDGF03 Import-Module -CimSession $cs -Name Storage # Importing a CIM module, converts the CDXML files for each command into # PowerShell scripts. These appear as functions in the local session. Get-Command Get-Disk ``` ```Output CommandType Name ModuleName ----------- ---- ---------- Function Get-Disk Storage ``` ```powershell # Use implicit remoting to query disks on the remote computer from which the # module was imported. Get-Disk ``` ```Output Number Friendly Name OperationalStatus Total Size Partition Style ------ ------------- ----------------- ---------- --------------- 0 Virtual HD ATA Device Online 40 GB MBR ``` ## PARAMETERS ### -Alias Specifies the aliases that this cmdlet imports from the module into the current session. Enter a comma-separated list of aliases. Wildcard characters are permitted. Some modules automatically export selected aliases into your session when you import the module. This parameter lets you select from among the exported aliases. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -ArgumentList Specifies an array of arguments, or parameter values, that are passed to a script module during the `Import-Module` command. This parameter is valid only when you're importing a script module. You can also refer to the **ArgumentList** parameter by its alias, **args**. For more information about the behavior of **ArgumentList**, see [about_Splatting](about/about_Splatting.md#splatting-with-arrays). ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Args Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -AsCustomObject Indicates that this cmdlet returns a custom object with members that represent the imported module members. This parameter is valid only for script modules. When you use the **AsCustomObject** parameter, `Import-Module` imports the module members into the session and then returns a **PSCustomObject** object instead of a **PSModuleInfo** object. You can save the custom object in a variable and use member-access enumeration to invoke the members. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Assembly Specifies an array of assembly objects. This cmdlet imports the cmdlets and providers implemented in the specified assembly objects. Enter a variable that contains assembly objects or a command that creates assembly objects. You can also pipe an assembly object to `Import-Module`. When you use this parameter, only the cmdlets and providers implemented by the specified assemblies are imported. If the module contains other files, they aren't imported, and you might be missing important members of the module. Use this parameter for debugging and testing the module, or when you're instructed to use it by the module author. ```yaml Type: System.Reflection.Assembly[] Parameter Sets: Assembly Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -CimNamespace Specifies the namespace of an alternate CIM provider that exposes CIM modules. The default value is the namespace of the Module Discovery WMI provider. Use this parameter to import CIM modules from computers and devices that aren't running a Windows operating system. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String Parameter Sets: CimSession Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CimResourceUri Specifies an alternate location for CIM modules. The default value is the resource URI of the Module Discovery WMI provider on the remote computer. Use this parameter to import CIM modules from computers and devices that aren't running a Windows operating system. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Uri Parameter Sets: CimSession Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CimSession Specifies a CIM session on the remote computer. Enter a variable that contains the CIM session or a command that gets the CIM session, such as a [Get-CimSession](../CimCmdlets/Get-CimSession.md) command. `Import-Module` uses the CIM session connection to import modules from the remote computer into the current session. When you use the commands from the imported module in the current session, the commands run on the remote computer. You can use this parameter to import modules from computers and devices that aren't running the Windows operating system, and Windows computers that have PowerShell, but don't have PowerShell remoting enabled. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: Microsoft.Management.Infrastructure.CimSession Parameter Sets: CimSession Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Cmdlet Specifies an array of cmdlets that this cmdlet imports from the module into the current session. Wildcard characters are permitted. Some modules automatically export selected cmdlets into your session when you import the module. This parameter lets you select from among the exported cmdlets. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -DisableNameChecking Indicates that this cmdlet suppresses the message that warns you when you import a cmdlet or function whose name includes an unapproved verb or a prohibited character. By default, when a module that you import exports cmdlets or functions that have unapproved verbs in their names, PowerShell displays the following warning message: > WARNING: Some imported command names include unapproved verbs which might make them less > discoverable. Use the Verbose parameter for more detail or type Get-Verb to see the list of > approved verbs. This message is only a warning. The complete module is still imported, including the non-conforming commands. Although the message is displayed to module users, the naming problem should be fixed by the module author. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Force This parameter causes a module to be loaded, or reloaded, over top of the current one. Some modules load external assemblies. The import fails if you are importing a module that loads a newer version of an assembly. The **Force** parameter can't override the error. You must start a new session to load the new version. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -FullyQualifiedName The value can be a module name, a full module specification, or a path to a module file. When the value is a path, the path can be fully qualified or relative. A relative path is resolved relative to the script that contains the using statement. When the value is a name or module specification, PowerShell searches the **PSModulePath** for the specified module. A module specification is a hashtable that has the following keys. - `ModuleName` - **Required** Specifies the module name. - `GUID` - **Optional** Specifies the GUID of the module. - It's also **Required** to specify at least one of the three below keys. - `ModuleVersion` - Specifies a minimum acceptable version of the module. - `MaximumVersion` - Specifies the maximum acceptable version of the module. - `RequiredVersion` - Specifies an exact, required version of the module. This can't be used with the other Version keys. ```yaml Type: Microsoft.PowerShell.Commands.ModuleSpecification[] Parameter Sets: FullyQualifiedName, FullyQualifiedNameAndPSSession, FullyQualifiedNameAndWinCompat Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Function Specifies an array of functions that this cmdlet imports from the module into the current session. Wildcard characters are permitted. Some modules automatically export selected functions into your session when you import the module. This parameter lets you select from among the exported functions. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Global Indicates that this cmdlet imports modules into the global session state so they're available to all commands in the session. By default, when `Import-Module` cmdlet is called from the command prompt, script file, or scriptblock, all the commands are imported into the global session state. When invoked from another module, `Import-Module` cmdlet imports the commands in a module, including commands from nested modules, into the calling module's session state. > [!TIP] > You should avoid calling `Import-Module` from within a module. Instead, declare the target module > as a nested module in the parent module's manifest. Declaring nested modules improves the > discoverability of dependencies. The **Global** parameter is equivalent to the **Scope** parameter with a value of **Global**. To restrict the commands that a module exports, use an `Export-ModuleMember` command in the script module. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumVersion Specifies a maximum version. This cmdlet imports only a version of the module that's less than or equal to the specified value. If no version qualifies, `Import-Module` returns an error. ```yaml Type: System.String Parameter Sets: Name, PSSession, CimSession, WinCompat Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MinimumVersion Specifies a minimum version. This cmdlet imports only a version of the module that's greater than or equal to the specified value. Use the **MinimumVersion** parameter name or its alias, **Version**. If no version qualifies, `Import-Module` generates an error. To specify an exact version, use the **RequiredVersion** parameter. You can also use the **Module** and **Version** parameters of the **#Requires** keyword to require a specific version of a module in a script. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Version Parameter Sets: Name, PSSession, CimSession, WinCompat Aliases: Version Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ModuleInfo Specifies an array of module objects to import. Enter a variable that contains the module objects, or a command that gets the module objects, such as the following command: `Get-Module -ListAvailable`. You can also pipe module objects to `Import-Module`. ```yaml Type: System.Management.Automation.PSModuleInfo[] Parameter Sets: ModuleInfo Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies the names of the modules to import. Enter the name of the module or the name of a file in the module, such as a `.psd1`, `.psm1`, `.dll`, or `.ps1` file. File paths are optional. Wildcard characters aren't permitted. You can also pipe module names and filenames to `Import-Module`. If you omit a path, `Import-Module` looks for the module in the paths saved in the `$Env:PSModulePath` environment variable. Specify only the module name whenever possible. When you specify a filename, only the members that are implemented in that file are imported. If the module contains other files, they aren't imported, and you might be missing important members of the module. > [!NOTE] > While it's possible to import a script (`.ps1`) file as a module, script files are usually not > structured like script modules file (`.psm1`) file. Importing a script file doesn't guarantee > that it's usable as a module. For more information, see [about_Modules](about/about_Modules.md). ```yaml Type: System.String[] Parameter Sets: Name, PSSession, CimSession, WinCompat Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: True ``` ### -NoClobber Prevents importing commands that have the same names as existing commands in the current session. By default, `Import-Module` imports all exported module commands. Commands that have the same names can hide or replace commands in the session. To avoid command name conflicts in a session, use the **Prefix** or **NoClobber** parameters. For more information about name conflicts and command precedence, see "Modules and Name Conflicts" in [about_Modules](about/about_Modules.md) and [about_Command_Precedence](about/about_Command_Precedence.md). This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: NoOverwrite Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns an object representing the imported module. By default, this cmdlet doesn't generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Prefix Specifies a prefix that this cmdlet adds to the nouns in the names of imported module members. Use this parameter to avoid name conflicts that might occur when different members in the session have the same name. This parameter doesn't change the module, and it doesn't affect files that the module imports for its own use. These are known as nested modules. This cmdlet affects only the names of members in the current session. For example, if you specify the prefix UTC and then import a `Get-Date` cmdlet, the cmdlet is known in the session as `Get-UTCDate`, and it's not confused with the original `Get-Date` cmdlet. The value of this parameter takes precedence over the **DefaultCommandPrefix** property of the module, which specifies the default prefix. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PSSession Specifies a PowerShell user-managed session (**PSSession**) from which this cmdlet imports modules into the current session. Enter a variable that contains a **PSSession** or a command that gets a **PSSession**, such as a `Get-PSSession` command. When you import a module from a different session into the current session, you can use the cmdlets from the module in the current session, just as you would use cmdlets from a local module. Commands that use the remote cmdlets run in the remote session, but the remoting details are managed in the background by PowerShell. This parameter uses the Implicit Remoting feature of PowerShell. It's equivalent to using the `Import-PSSession` cmdlet to import particular modules from a session. `Import-Module` can't import core PowerShell modules from another session. The core PowerShell modules have names that begin with Microsoft.PowerShell. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.Runspaces.PSSession Parameter Sets: PSSession, FullyQualifiedNameAndPSSession Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RequiredVersion Specifies a version of the module that this cmdlet imports. If the version isn't installed, `Import-Module` generates an error. By default, `Import-Module` imports the module without checking the version number. To specify a minimum version, use the **MinimumVersion** parameter. You can also use the **Module** and **Version** parameters of the **#Requires** keyword to require a specific version of a module in a script. This parameter was introduced in Windows PowerShell 3.0. Scripts that use **RequiredVersion** to import modules that are included with existing releases of the Windows operating system don't automatically run in future releases of the Windows operating system. This is because PowerShell module version numbers in future releases of the Windows operating system are higher than module version numbers in existing releases of the Windows operating system. ```yaml Type: System.Version Parameter Sets: Name, PSSession, CimSession, WinCompat Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Scope Specifies a scope to import the module in. The acceptable values for this parameter are: - **Global**. Available to all commands in the session. Equivalent to the **Global** parameter. - **Local**. Available only in the current scope. By default, when `Import-Module` cmdlet is called from the command prompt, script file, or scriptblock, all the commands are imported into the global session state. You can use the `-Scope Local` parameter to import module content into the script or scriptblock scope. When invoked from another module, `Import-Module` cmdlet imports the commands in a module, including commands from nested modules, into the caller's session state. Specifying `-Scope Global` or `-Global` indicates that this cmdlet imports modules into the global session state so they're available to all commands in the session. The **Global** parameter is equivalent to the **Scope** parameter with a value of **Global**. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: Local, Global Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipEditionCheck Skips the check on the `CompatiblePSEditions` field. Allows loading a module from the `"$($Env:windir)\System32\WindowsPowerShell\v1.0\Modules"` module directory into PowerShell Core when that module doesn't specify `Core` in the `CompatiblePSEditions` manifest field. When importing a module from another path, this switch does nothing, since the check isn't performed. On Linux and macOS, this switch does nothing. For more information, see [about_PowerShell_Editions](About/about_PowerShell_Editions.md). > [!WARNING] > `Import-Module -SkipEditionCheck` is still likely to fail to import a module. Even if it does > succeed, invoking a command from the module may later fail when it tries to use an > incompatible API. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Name, PSSession, CimSession, FullyQualifiedName, FullyQualifiedNameAndPSSession, Assembly, ModuleInfo Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -UseWindowsPowerShell Loads module using Windows PowerShell Compatibility functionality. See [about_Windows_PowerShell_Compatibility](About/about_Windows_PowerShell_Compatibility.md) for more information. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: WinCompat, FullyQualifiedNameAndWinCompat Aliases: UseWinPS Required: True Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Variable Specifies an array of variables that this cmdlet imports from the module into the current session. Enter a list of variables. Wildcard characters are permitted. Some modules automatically export selected variables into your session when you import the module. This parameter lets you select from among the exported variables. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a module name to this cmdlet. ### System.Management.Automation.PSModuleInfo You can pipe a module object to this cmdlet. ### System.Reflection.Assembly You can pipe an assembly object to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSModuleInfo If you specify the **PassThru** parameter, the cmdlet generates a **System.Management.Automation.PSModuleInfo** object that represents the imported module. ### System.Management.Automation.PSCustomObject If you specify the **AsCustomObject** and **PassThru** parameters together, the cmdlet generates a **PSCustomObject** object that represents the module. ## NOTES PowerShell includes the following aliases for `Import-Module`: - All platforms: - `ipmo` - Before you can import a module, the module must be accessible to your local computer and included in the `PSModulePath` environmental variable. For more information, see [about_Modules](About/about_Modules.md). You can also use the **PSSession** and **CimSession** parameters to import modules that are installed on remote computers. However, commands that use the cmdlets in these modules run in the remote session on the remote computer. - If you import members with the same name and the same type into your session, PowerShell uses the member imported last by default. Variables and aliases are replaced, and the originals aren't accessible. Functions, cmdlets, and providers are merely shadowed by the new members. They can be accessed by qualifying the command name with the name of its snap-in, module, or function path. - To update the formatting data for commands imported from a module, use the `Update-FormatData` cmdlet. If the formatting file for a module changes, use the `Update-FormatData` cmdlet to update the formatting data for imported commands. You don't need to import the module again. - Starting in Windows PowerShell 3.0, the core commands installed with PowerShell are packaged in modules. In Windows PowerShell 2.0, and in host programs that create older-style sessions in later versions of PowerShell, the core commands are packaged in snap-ins (**PSSnapins**). The exception is **Microsoft.PowerShell.Core**, which is always a snap-in. Also, remote sessions, such as those started by the `New-PSSession` cmdlet, are older-style sessions that include core snap-ins. For information about the **CreateDefault2** method that creates newer-style sessions with core modules, see the [CreateDefault2 Method](/dotnet/api/system.management.automation.runspaces.initialsessionstate.createdefault2). - In Windows PowerShell 2.0, some property values of the module object, such as the **ExportedCmdlets** and **NestedModules** property values, weren't populated until the module was imported. - If you attempt to import a module that contains mixed-mode assemblies that aren't compatible with Windows PowerShell 3.0+, `Import-Module` returns an error message like the following one. > Import-Module : Mixed mode assembly is built against version 'v2.0.50727' of the runtime and > cannot be loaded in the 4.0 runtime without additional configuration information. This error occurs when a module that's designed for Windows PowerShell 2.0 contains at least one mixed-module assembly. A mixed-module assembly that includes both managed and non-managed code, such as C++ and C#. To import a module that contains mixed-mode assemblies, start Windows PowerShell 2.0 by using the following command, and then try the `Import-Module` command again. `powershell.exe -Version 2.0` - To use the CIM session feature, the remote computer must have WS-Management remoting and Windows Management Instrumentation (WMI), which is the Microsoft implementation of the Common Information Model (CIM) standard. The computer must also have the Module Discovery WMI provider or an alternate CIM provider that has the same basic features. You can use the CIM session feature on computers that aren't running a Windows operating system and on Windows computers that have PowerShell, but don't have PowerShell remoting enabled. You can also use the CIM parameters to get CIM modules from computers that have PowerShell remoting enabled, including the local computer. When you create a CIM session on the local computer, PowerShell uses DCOM, instead of WMI, to create the session. - By default, `Import-Module` imports modules in the global scope even when called from a descendant scope. The top-level scope and all descendant scopes have access to the module's exported elements. In a descendant scope, `-Scope Local` limits the import to that scope and all its descendant scopes. Parent scopes then don't see the imported members. > [!NOTE] > `Get-Module` shows all modules loaded in the current session. This includes modules loaded > locally in a descendant scope. Use `Get-Command -Module modulename` to see which members are > loaded in the current scope. - `Import-Module` doesn't load class and enumeration definitions in the module. Use the `using module` statement at the beginning of your script. This imports the module, including the class and enumeration definitions. For more information, see [about_Using](About/about_Using.md). - During development of a script module, it's common to make changes to the code then load the new version of the module using `Import-Module` with the **Force** parameter. This works for changes to functions in the root module only. `Import-Module` doesn't reload any nested modules. Also, there's no way to load any updated classes or enumerations. To get updated module members defined in nested modules, remove the module with `Remove-Module`, then import the module again. If the module was loaded with a `using` statement, you must start a new session to import updated definitions for the classes and enumerations. Classes and enumerations defined in PowerShell and imported with a `using` statement can't be unloaded. ## RELATED LINKS [about_Modules](about/about_Modules.md) [Export-ModuleMember](Export-ModuleMember.md) [Get-Module](Get-Module.md) [New-Module](New-Module.md) [Remove-Module](Remove-Module.md) [about_PowerShell_Editions](About/about_PowerShell_Editions.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Invoke-Command.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 01/21/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/invoke-command?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Invoke-Command --- # Invoke-Command ## SYNOPSIS Runs commands on local and remote computers. ## SYNTAX ### InProcess (Default) ``` Invoke-Command [-StrictMode <Version>] [-ScriptBlock] <ScriptBlock> [-NoNewScope] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>] ``` ### FilePathRunspace ``` Invoke-Command [[-Session] <PSSession[]>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-JobName <String>] [-FilePath] <String> [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>] ``` ### Session ``` Invoke-Command [[-Session] <PSSession[]>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-JobName <String>] [-ScriptBlock] <ScriptBlock> [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>] ``` ### FilePathComputerName ``` Invoke-Command [[-ComputerName] <String[]>] [-Credential <PSCredential>] [-Port <Int32>] [-UseSSL] [-ConfigurationName <String>] [-ApplicationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-InDisconnectedSession] [-SessionName <String[]>] [-HideComputerName] [-JobName <String>] [-FilePath] <String> [-SessionOption <PSSessionOption>] [-Authentication <AuthenticationMechanism>] [-EnableNetworkAccess] [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>] ``` ### ComputerName ``` Invoke-Command [[-ComputerName] <String[]>] [-Credential <PSCredential>] [-Port <Int32>] [-UseSSL] [-ConfigurationName <String>] [-ApplicationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-InDisconnectedSession] [-SessionName <String[]>] [-HideComputerName] [-JobName <String>] [-ScriptBlock] <ScriptBlock> [-SessionOption <PSSessionOption>] [-Authentication <AuthenticationMechanism>] [-EnableNetworkAccess] [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ### Uri ``` Invoke-Command [-Credential <PSCredential>] [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [[-ConnectionUri] <Uri[]>] [-AsJob] [-InDisconnectedSession] [-HideComputerName] [-JobName <String>] [-ScriptBlock] <ScriptBlock> [-AllowRedirection] [-SessionOption <PSSessionOption>] [-Authentication <AuthenticationMechanism>] [-EnableNetworkAccess] [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ### FilePathUri ``` Invoke-Command [-Credential <PSCredential>] [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [[-ConnectionUri] <Uri[]>] [-AsJob] [-InDisconnectedSession] [-HideComputerName] [-JobName <String>] [-FilePath] <String> [-AllowRedirection] [-SessionOption <PSSessionOption>] [-Authentication <AuthenticationMechanism>] [-EnableNetworkAccess] [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>] ``` ### VMId ``` Invoke-Command -Credential <PSCredential> [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-ScriptBlock] <ScriptBlock> [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [-VMId] <Guid[]> [<CommonParameters>] ``` ### VMName ``` Invoke-Command -Credential <PSCredential> [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-ScriptBlock] <ScriptBlock> [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] -VMName <String[]> [<CommonParameters>] ``` ### FilePathVMId ``` Invoke-Command -Credential <PSCredential> [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-FilePath] <String> [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [-VMId] <Guid[]> [<CommonParameters>] ``` ### FilePathVMName ``` Invoke-Command -Credential <PSCredential> [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-FilePath] <String> [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] -VMName <String[]> [<CommonParameters>] ``` ### SSHHost ``` Invoke-Command [-Port <Int32>] [-AsJob] [-HideComputerName] [-JobName <String>] [-ScriptBlock] <ScriptBlock> -HostName <String[]> [-UserName <String>] [-KeyFilePath <String>] [-Subsystem <String>] [-ConnectingTimeout <Int32>] [-SSHTransport] [-Options <Hashtable>] [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>] ``` ### ContainerId ``` Invoke-Command [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-JobName <String>] [-ScriptBlock] <ScriptBlock> [-RunAsAdministrator] [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] -ContainerId <String[]> [<CommonParameters>] ``` ### FilePathContainerId ``` Invoke-Command [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [-AsJob] [-HideComputerName] [-JobName <String>] [-FilePath] <String> [-RunAsAdministrator] [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] -ContainerId <String[]> [<CommonParameters>] ``` ### SSHHostHashParam ``` Invoke-Command [-AsJob] [-HideComputerName] [-JobName <String>] [-ScriptBlock] <ScriptBlock> -SSHConnection <Hashtable[]> [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>] ``` ### FilePathSSHHost ``` Invoke-Command [-AsJob] [-HideComputerName] [-FilePath] <String> -HostName <String[]> [-UserName <String>] [-KeyFilePath <String>] [-Subsystem <String>] [-ConnectingTimeout <Int32>] [-SSHTransport] [-Options <Hashtable>] [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>] ``` ### FilePathSSHHostHash ``` Invoke-Command [-AsJob] [-HideComputerName] [-FilePath] <String> -SSHConnection <Hashtable[]> [-RemoteDebug] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Invoke-Command` cmdlet runs commands on a local or remote computer and returns all output from the commands, including errors. Using a single `Invoke-Command` command, you can run commands on multiple computers. To run a single command on a remote computer, use the **ComputerName** parameter. To run a series of related commands that share data, use the `New-PSSession` cmdlet to create a **PSSession** (a persistent connection) on the remote computer, and then use the **Session** parameter of `Invoke-Command` to run the command in the **PSSession**. To run a command in a disconnected session, use the **InDisconnectedSession** parameter. To run a command in a background job, use the **AsJob** parameter. You can also use `Invoke-Command` on a local computer to a run script block as a command. PowerShell runs the script block immediately in a child scope of the current scope. Before using `Invoke-Command` to run commands on a remote computer, read [about_Remote](./About/about_Remote.md). Starting with PowerShell 6.0 you can use Secure Shell (SSH) to establish a connection to and invoke commands on remote computers. SSH must be installed on the local computer and the remote computer must be configured with a PowerShell SSH endpoint. The benefit of an SSH based PowerShell remote session is that it works across multiple platforms (Windows, Linux, macOS). For SSH based session you use the **HostName** or **SSHConnection** parameters to specify the remote computer and relevant connection information. For more information about how to set up PowerShell SSH remoting, see [PowerShell Remoting Over SSH](/powershell/scripting/learn/remoting/ssh-remoting-in-powershell-core). Some code samples use splatting to reduce the line length. For more information, see [about_Splatting](./About/about_Splatting.md). ## EXAMPLES ### Example 1: Run a script on a server This example runs the `Test.ps1` script on the Server01 computer. ```powershell Invoke-Command -FilePath C:\scripts\test.ps1 -ComputerName Server01 ``` The **FilePath** parameter specifies a script that is located on the local computer. The script runs on the remote computer and the results are returned to the local computer. ### Example 2: Run a command on a remote server This example runs a `Get-Culture` command on the Server01 remote computer. ```powershell Invoke-Command -ComputerName Server01 -Credential Domain01\User01 -ScriptBlock { Get-Culture } ``` The **ComputerName** parameter specifies the name of the remote computer. The **Credential** parameter is used to run the command in the security context of Domain01\User01, a user who has permission to run commands. The **ScriptBlock** parameter specifies the command to be run on the remote computer. In response, PowerShell requests the password and an authentication method for the User01 account. It then runs the command on the Server01 computer and returns the result. ### Example 3: Run a command in a persistent connection This example runs the same `Get-Culture` command in a session, using a persistent connection, on the remote computer named Server02. ```powershell $s = New-PSSession -ComputerName Server02 -Credential Domain01\User01 Invoke-Command -Session $s -ScriptBlock { Get-Culture } ``` The `New-PSSession` cmdlet creates a session on the Server02 remote computer and saves it in the `$s` variable. Typically, you create a session only when you run a series of commands on the remote computer. The `Invoke-Command` cmdlet runs the `Get-Culture` command on Server02. The **Session** parameter specifies the session saved in the `$s` variable. In response, PowerShell runs the command in the session on the Server02 computer. ### Example 4: Use a session to run a series of commands that share data This example compares the effects of using **ComputerName** and **Session** parameters of `Invoke-Command`. It shows how to use a session to run a series of commands that share the same data. ```powershell Invoke-Command -ComputerName Server02 -ScriptBlock { $p = Get-Process powershell } Invoke-Command -ComputerName Server02 -ScriptBlock { $p.VirtualMemorySize } $s = New-PSSession -ComputerName Server02 Invoke-Command -Session $s -ScriptBlock { $p = Get-Process powershell } Invoke-Command -Session $s -ScriptBlock { $p.VirtualMemorySize } ``` ```Output 17930240 ``` The first two commands use the **ComputerName** parameter of `Invoke-Command` to run commands on the Server02 remote computer. The first command uses the `Get-Process` cmdlet to get the PowerShell process on the remote computer and to save it in the `$p` variable. The second command gets the value of the **VirtualMemorySize** property of the PowerShell process. When you use the **ComputerName** parameter, PowerShell creates a new session to run the command. The session is closed when the command completes. The `$p` variable was created in one connection, but it doesn't exist in the connection created for the second command. The problem is solved by creating a persistent session on the remote computer, then running both of the commands in the same session. The `New-PSSession` cmdlet creates a persistent session on the computer Server02 and saves the session in the `$s` variable. The `Invoke-Command` lines that follow use the **Session** parameter to run both of the commands in the same session. Since both commands run in the same session, the `$p` value remains active. ### Example 5: Invoke a command with a script block stored in a variable This example shows how to run a command that is stored as a script block in a variable. When the script block is saved in a variable, you can specify the variable as the value of the **ScriptBlock** parameter. ```powershell $command = { Get-WinEvent -LogName PowerShellCore/Operational | Where-Object -FilterScript { $_.Message -like '*certificate*' } } Invoke-Command -ComputerName S1, S2 -ScriptBlock $command ``` The `$command` variable stores the `Get-WinEvent` command that's formatted as a script block. The `Invoke-Command` runs the command stored in `$command` on the S1 and S2 remote computers. ### Example 6: Run a single command on several computers This example demonstrates how to use `Invoke-Command` to run a single command on multiple computers. ```powershell $parameters = @{ ComputerName = 'Server01', 'Server02', 'TST-0143', 'localhost' ConfigurationName = 'MySession.PowerShell' ScriptBlock = { Get-WinEvent -LogName PowerShellCore/Operational } } Invoke-Command @parameters ``` The **ComputerName** parameter specifies a comma-separated list of computer names. The list of computers includes the localhost value, which represents the local computer. The **ConfigurationName** parameter specifies an alternate session configuration. The **ScriptBlock** parameter runs `Get-WinEvent` to get the PowerShellCore/Operational event logs from each computer. ### Example 7: Get the version of the host program on multiple computers This example gets the version of the PowerShell host program running on 200 remote computers. ```powershell $version = Invoke-Command -ComputerName (Get-Content Machines.txt) -ScriptBlock { (Get-Host).Version } ``` Because only one command is run, you don't have to create persistent connections to each of the computers. Instead, the command uses the **ComputerName** parameter to indicate the computers. To specify the computers, it uses the `Get-Content` cmdlet to get the contents of the Machine.txt file, a file of computer names. The `Invoke-Command` cmdlet runs a `Get-Host` command on the remote computers. It uses dot notation to get the **Version** property of the PowerShell host. These commands run one at a time. When the commands complete, the output of the commands from all of the computers is saved in the `$version` variable. The output includes the name of the computer from which the data originated. ### Example 8: Run a background job on several remote computers This example runs a command on two remote computers. The `Invoke-Command` command uses the **AsJob** parameter so that the command runs as a background job. The commands run on the remote computers, but the job exists on the local computer. The results are transmitted to the local computer. ```powershell $s = New-PSSession -ComputerName Server01, Server02 Invoke-Command -Session $s -ScriptBlock { Get-EventLog System } -AsJob ``` ```Output Id Name State HasMoreData Location Command --- ---- ----- ----- ----------- --------------- 1 Job1 Running True Server01,Server02 Get-EventLog System ``` ```powershell $j = Get-Job $j | Format-List -Property * ``` ```Output HasMoreData : True StatusMessage : Location : Server01,Server02 Command : Get-EventLog System JobStateInfo : Running Finished : System.Threading.ManualResetEvent InstanceId : e124bb59-8cb2-498b-a0d2-2e07d4e030ca Id : 1 Name : Job1 ChildJobs : {Job2, Job3} Output : {} Error : {} Progress : {} Verbose : {} Debug : {} Warning : {} StateChanged : ``` ```powershell $results = $j | Receive-Job ``` The `New-PSSession` cmdlet creates sessions on the Server01 and Server02 remote computers. The `Invoke-Command` cmdlet runs a background job in each of the sessions. The command uses the **AsJob** parameter to run the command as a background job. This command returns a job object that contains two child job objects, one for each of the jobs run on the two remote computers. The `Get-Job` command saves the job object in the `$j` variable. The `$j` variable is then piped to the `Format-List` cmdlet to display all properties of the job object in a list. The last command gets the results of the jobs. It pipes the job object in `$j` to the `Receive-Job` cmdlet and stores the results in the `$results` variable. ### Example 9: Include local variables in a command run on a remote computer This example shows how to include the values of local variables in a command run on a remote computer. The command uses the `Using:` scope modifier to identify a local variable in a remote command. By default, all variables are assumed to be defined in the remote session. The `Using:` scope modifier was introduced in PowerShell 3.0. For more information about the `Using:` scope modifier, see [about_Remote_Variables](./About/about_Remote_Variables.md) and [about_Scopes](./about/about_scopes.md). ```powershell $Log = 'PowerShellCore/Operational' Invoke-Command -ComputerName Server01 -ScriptBlock { Get-WinEvent -LogName $Using:Log -MaxEvents 10 } ``` The `$Log` variable stores the name of the event log, PowerShellCore/Operational. The `Invoke-Command` cmdlet runs `Get-WinEvent` on Server01 to get the ten newest events from the event log. The value of the **LogName** parameter is the `$Log` variable that is prefixed by the `Using:` scope modifier to indicate that it was created in the local session, not in the remote session. ### Example 10: Hide the computer name This example shows the effect of using the **HideComputerName** parameter of `Invoke-Command`. **HideComputerName** doesn't change the object that this cmdlet returns. It changes only the display. You can still use the **Format** cmdlets to display the **PsComputerName** property of any of the affected objects. ```powershell Invoke-Command -ComputerName S1, S2 -ScriptBlock { Get-Process powershell } ``` ```Output PSComputerName Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName -------------- ------- ------ ----- ----- ----- ------ -- ----------- S1 575 15 45100 40988 200 4.68 1392 PowerShell S2 777 14 35100 30988 150 3.68 67 PowerShell ``` ```powershell Invoke-Command -ComputerName S1, S2 -HideComputerName -ScriptBlock { Get-Process powershell } ``` ```Output Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 575 15 45100 40988 200 4.68 1392 PowerShell 777 14 35100 30988 150 3.68 67 PowerShell ``` The first two commands use `Invoke-Command` to run a `Get-Process` command for the PowerShell process. The output of the first command includes the **PsComputerName** property, which contains the name of the computer on which the command ran. The output of the second command, which uses **HideComputerName**, doesn't include the **PsComputerName** column. ### Example 11: Use the `param` keyword in a script block The `param` keyword and the **ArgumentList** parameter are used to pass variable values to named parameters in a script block. This example displays filenames that begin with the letter `a` and have the `.pdf` extension. For more information about the `param` keyword, see [about_Language_Keywords](./about/about_language_keywords.md#param). ```powershell $parameters = @{ ComputerName = 'Server01' ScriptBlock = { param ($Param1, $Param2) Get-ChildItem -Name $Param1 -Include $Param2 } ArgumentList = 'a*', '*.pdf' } Invoke-Command @parameters ``` ```Output aa.pdf ab.pdf ac.pdf az.pdf ``` `Invoke-Command` uses the **ScriptBlock** parameter that defines two variables, `$Param1` and `$Param2`. `Get-ChildItem` uses the named parameters, **Name** and **Include** with the variable names. The **ArgumentList** passes the values to the variables. ### Example 12: Use the $args automatic variable in a script block The `$args` automatic variable and the **ArgumentList** parameter are used to pass array values to parameter positions in a script block. This example displays a server's directory contents of `.txt` files. The `Get-ChildItem` **Path** parameter is position 0 and the **Filter** parameter is position 1. For more information about the `$args` variable, see [about_Automatic_Variables](./about/about_automatic_variables.md#args) ```powershell $parameters = @{ ComputerName = 'Server01' ScriptBlock = { Get-ChildItem $args[0] $args[1] } ArgumentList = 'C:\Test', '*.txt*' } Invoke-Command @parameters ``` ```Output Directory: C:\Test Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 6/12/2019 15:15 128 alog.txt -a--- 7/27/2019 15:16 256 blog.txt -a--- 9/28/2019 17:10 64 zlog.txt ``` `Invoke-Command` uses a **ScriptBlock** parameter and `Get-ChildItem` specifies the `$args[0]` and `$args[1]` array values. The **ArgumentList** passes the `$args` array values to the `Get-ChildItem` parameter positions for **Path** and **Filter**. ### Example 13: Run a script on all the computers listed in a text file This example uses the `Invoke-Command` cmdlet to run the `Sample.ps1` script on all the computers listed in the `Servers.txt` file. The command uses the **FilePath** parameter to specify the script file. This command lets you run the script on the remote computers, even if the script file isn't accessible to the remote computers. ```powershell $parameters = @{ ComputerName = (Get-Content Servers.txt) FilePath = 'C:\Scripts\Sample.ps1' ArgumentList = 'Process', 'Service' } Invoke-Command @parameters ``` When you submit the command, the content of the `Sample.ps1` file is copied into a script block and the script block is run on each of the remote computers. This procedure is equivalent to using the **ScriptBlock** parameter to submit the contents of the script. ### Example 14: Run a command on a remote computer using a URI This example shows how to run a command on a remote computer that's identified by a Uniform Resource Identifier (URI). This particular example runs a `Set-Mailbox` command on a remote Exchange server. ```powershell $LiveCred = Get-Credential $parameters = @{ ConfigurationName = 'Microsoft.Exchange' ConnectionUri = 'https://ps.exchangelabs.com/PowerShell' Credential = $LiveCred Authentication = 'Basic' ScriptBlock = { Set-Mailbox Dan -DisplayName 'Dan Park' } } Invoke-Command @parameters ``` The first line uses the `Get-Credential` cmdlet to store Windows Live ID credentials in the `$LiveCred` variable. PowerShell prompts the user to enter Windows Live ID credentials. The `$parameters` variable is a hash table containing the parameters to be passed to the `Invoke-Command` cmdlet. The `Invoke-Command` cmdlet runs a `Set-Mailbox` command using the **Microsoft.Exchange** session configuration. The **ConnectionURI** parameter specifies the URL of the Exchange server endpoint. The **Credential** parameter specifies the credentials stored in the `$LiveCred` variable. The **AuthenticationMechanism** parameter specifies the use of basic authentication. The **ScriptBlock** parameter specifies a script block that contains the command. ### Example 15: Use a session option This example shows how to create and use a **SessionOption** parameter. ```powershell $so = New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck $parameters = @{ ComputerName = 'server01' UseSSL = $true ScriptBlock = { Get-HotFix } SessionOption = $so Credential = 'server01\user01' } Invoke-Command @parameters ``` The `New-PSSessionOption` cmdlet creates a session option object that causes the remote end not to verify the Certificate Authority, Canonical Name, and Revocation Lists while evaluating the incoming HTTPS connection. The **SessionOption** object is saved in the `$so` variable. > [!NOTE] > Disabling these checks is convenient for troubleshooting, but obviously not secure. The `Invoke-Command` cmdlet runs a `Get-HotFix` command remotely. The **SessionOption** parameter is given the `$so` variable. ### Example 16: Manage URI redirection in a remote command This example shows how to use the **AllowRedirection** and **SessionOption** parameters to manage URI redirection in a remote command. ```powershell $max = New-PSSessionOption -MaximumRedirection 1 $parameters = @{ ConnectionUri = 'https://ps.exchangelabs.com/PowerShell' ScriptBlock = { Get-Mailbox dan } AllowRedirection = $true SessionOption = $max } Invoke-Command @parameters ``` The `New-PSSessionOption` cmdlet creates a **PSSessionOption** object that is saved in the `$max` variable. The command uses the **MaximumRedirection** parameter to set the **MaximumConnectionRedirectionCount** property of the **PSSessionOption** object to 1. The `Invoke-Command` cmdlet runs a `Get-Mailbox` command on a remote Microsoft Exchange Server. The **AllowRedirection** parameter provides explicit permission to redirect the connection to an alternate endpoint. The **SessionOption** parameter uses the session object stored in the `$max` variable. As a result, if the remote computer specified by **ConnectionURI** returns a redirection message, PowerShell redirects the connection, but if the new destination returns another redirection message, the redirection count value of 1 is exceeded, and `Invoke-Command` returns a non-terminating error. ### Example 17: Access a network share in a remote session This example shows how to access a network share from a remote session. Three computers are used to demonstrate the example. Server01 is the local computer, Server02 is the remote computer, and Net03 contains the network share. Server01 connects to Server02, and then Server02 does a second hop to Net03 to access the network share. For more information about how PowerShell Remoting supports hops between computers, see [Making the second hop in PowerShell Remoting](/powershell/scripting/learn/remoting/ps-remoting-second-hop). The required Credential Security Support Provider (CredSSP) delegation is enabled in the client settings on the local computer, and in the service settings on the remote computer. To run the commands in this example, you must be a member of the **Administrators** group on the local computer and the remote computer. ```powershell Enable-WSManCredSSP -Role Client -DelegateComputer Server02 $s = New-PSSession Server02 Invoke-Command -Session $s -ScriptBlock { Enable-WSManCredSSP -Role Server -Force } $parameters = @{ ComputerName = 'Server02' ScriptBlock = { Get-Item \\Net03\Scripts\LogFiles.ps1 } Authentication = 'CredSSP' Credential = 'Domain01\Admin01' } Invoke-Command @parameters ``` The `Enable-WSManCredSSP` cmdlet enables CredSSP delegation from the Server01 local computer to the Server02 remote computer. The **Role** parameter specifies **Client** to configure the CredSSP client setting on the local computer. `New-PSSession` creates a **PSSession** object for Server02 and stores the object in the `$s` variable. The `Invoke-Command` cmdlet uses the `$s` variable to connect to the remote computer, Server02. The **ScriptBlock** parameter runs `Enable-WSManCredSSP` on the remote computer. The **Role** parameter specifies **Server** to configure the CredSSP server setting on the remote computer. The `$parameters` variable contains the parameter values to connect to the network share. The `Invoke-Command` cmdlet runs a `Get-Item` command in the session in `$s`. This command gets a script from the `\\Net03\Scripts` network share. The command uses the **Authentication** parameter with a value of **CredSSP** and the **Credential** parameter with a value of **Domain01\Admin01**. ### Example 18: Start scripts on many remote computers This example runs a script on more than a hundred computers. To minimize the impact on the local computer, it connects to each computer, starts the script, and then disconnects from each computer. The script continues to run in the disconnected sessions. ```powershell $parameters = @{ ComputerName = (Get-Content -Path C:\Test\Servers.txt) InDisconnectedSession = $true FilePath = '\\Scripts\Public\ConfigInventory.ps1' SessionOption = @{ OutputBufferingMode = 'Drop' IdleTimeout = [timespan]::FromHours(12) } } Invoke-Command @parameters ``` The command uses `Invoke-Command` to run the script. The value of the **ComputerName** parameter is a `Get-Content` command that gets the names of the remote computers from a text file. The **InDisconnectedSession** parameter disconnects the sessions as soon as it starts the command. The value of the **FilePath** parameter is the script that `Invoke-Command` runs on each computer. The value of **SessionOption** is a hash table. The **OutputBufferingMode** value is set to `Drop` and the **IdleTimeout** value is set to 12 hours. To get the results of commands and scripts that run in disconnected sessions, use the `Receive-PSSession` cmdlet. ### Example 19: Run a command on a remote computer using SSH This example shows how to run a command on a remote computer using Secure Shell (SSH). If SSH is configured on the remote computer to prompt for passwords, then you'll get a password prompt. Otherwise, you'll have to use SSH key-based user authentication. ```powershell Invoke-Command -HostName UserA@LinuxServer01 -ScriptBlock { Get-MailBox * } ``` ### Example 20: Run a command on a remote computer using SSH and specify a user authentication key This example shows how to run a command on a remote computer using SSH and specifying a key file for user authentication. You won't be prompted for a password unless the key authentication fails and the remote computer is configured to allow basic password authentication. ```powershell $parameters = @{ HostName = 'UserA@LinuxServer01' ScriptBlock = { Get-MailBox * } KeyFilePath = '/UserA/UserAKey_rsa' } Invoke-Command ``` ### Example 21: Run a script file on multiple remote computers using SSH as a job This example shows how to run a script file on multiple remote computers using SSH and the **SSHConnection** parameter set. The **SSHConnection** parameter takes an array of hash tables that contain connection information for each computer. This example requires that the target remote computers have SSH configured to support key-based user authentication. ```powershell $sshConnections = @( @{ HostName = "WinServer1" UserName = "Domain\UserA" KeyFilePath = "C:\Users\UserA\id_rsa" } @{ HostName = "UserB@LinuxServer5" KeyFilePath = "/Users/UserB/id_rsa" } ) $results = Invoke-Command -FilePath C:\Scripts\GetInfo.ps1 -SSHConnection $sshConnections ``` ### Example 22: Connect to a remote SSH session using SSH options This example shows how to run a script file on a remote Linux-based machine using SSH options. The **Options** parameter takes a hashtable of values that are passed as options to the underlying `ssh` command the established the connection to the remote system. ```powershell $options = @{ Port=22 User = 'UserB' Host = 'LinuxServer5' } $results = Invoke-Command -FilePath C:\Scripts\CollectEvents.ps1 -KeyFilePath '/Users/UserB/id_rsa' -Options $options ``` ## PARAMETERS ### -AllowRedirection Allows redirection of this connection to an alternate Uniform Resource Identifier (URI). When you use the **ConnectionURI** parameter, the remote destination can return an instruction to redirect to a different URI. By default, PowerShell doesn't redirect connections, but you can use this parameter to allow it to redirect the connection. You can also limit the number of times the connection is redirected by changing the **MaximumConnectionRedirectionCount** session option value. Use the **MaximumRedirection** parameter of the `New-PSSessionOption` cmdlet or set the **MaximumConnectionRedirectionCount** property of the `$PSSessionOption` preference variable. The default value is 5. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Uri, FilePathUri Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ApplicationName Specifies the application name segment of the connection URI. Use this parameter to specify the application name when you aren't using the **ConnectionURI** parameter in the command. The default value is the value of the `$PSSessionApplicationName` preference variable on the local computer. If this preference variable isn't defined, the default value is WSMAN. This value is appropriate for most uses. For more information, see [about_Preference_Variables](./About/about_Preference_Variables.md). The WinRM service uses the application name to select a listener to service the connection request. The value of this parameter should match the value of the **URLPrefix** property of a listener on the remote computer. ```yaml Type: System.String Parameter Sets: ComputerName, FilePathComputerName Aliases: Required: False Position: Named Default value: $PSSessionApplicationName if set on the local computer, otherwise WSMAN Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ArgumentList Supplies the values of parameters for the scriptblock. The parameters in the script block are passed by position from the array value supplied to **ArgumentList**. This is known as array splatting. For more information about the behavior of **ArgumentList**, see [about_Splatting](about/about_Splatting.md#splatting-with-arrays). ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Args Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -AsJob Indicates that this cmdlet runs the command as a background job on a remote computer. Use this parameter to run commands that take an extensive time to finish. When you use the **AsJob** parameter, the command returns an object that represents the job, and then displays the command prompt. You can continue to work in the session while the job finishes. To manage the job, use the `*-Job` cmdlets. To get the job results, use the `Receive-Job` cmdlet. The **AsJob** parameter resembles using the `Invoke-Command` cmdlet to run a `Start-Job` cmdlet remotely. However, with **AsJob**, the job is created on the local computer, even though the job runs on a remote computer. The results of the remote job are automatically returned to the local computer. For more information about PowerShell background jobs, see [about_Jobs](About/about_Jobs.md) and [about_Remote_Jobs](About/about_Remote_Jobs.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Session, FilePathRunspace, ComputerName, FilePathComputerName, Uri, FilePathUri, VMId, VMName, FilePathVMId, FilePathVMName, SSHHost, ContainerId, FilePathContainerId, SSHHostHashParam, FilePathSSHHost, FilePathSSHHostHash Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Authentication Specifies the mechanism that's used to authenticate the user's credentials. CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of the Windows operating system. The acceptable values for this parameter are as follows: - Default - Basic - Credssp - Digest - Kerberos - Negotiate - NegotiateWithImplicitCredential The default value is Default. For more information about the values of this parameter, see [AuthenticationMechanism Enumeration](/dotnet/api/system.management.automation.runspaces.authenticationmechanism). > [!CAUTION] > Credential Security Support Provider (CredSSP) authentication, in which the user's credentials are > passed to a remote computer to be authenticated, is designed for commands that require > authentication on more than one resource, such as accessing a remote network share. This mechanism > increases the security risk of the remote operation. If the remote computer is compromised, the > credentials that are passed to it can be used to control the network session. For more > information, see > [Credential Security Support Provider](/windows/win32/secauthn/credential-security-support-provider). ```yaml Type: System.Management.Automation.Runspaces.AuthenticationMechanism Parameter Sets: ComputerName, FilePathComputerName, Uri, FilePathUri Aliases: Accepted values: Basic, Default, Credssp, Digest, Kerberos, Negotiate, NegotiateWithImplicitCredential Required: False Position: Named Default value: Default Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to connect to the disconnected session. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts and they don't work with domain accounts. To get a certificate thumbprint, use a `Get-Item` or `Get-ChildItem` command in the PowerShell Cert: drive. ```yaml Type: System.String Parameter Sets: ComputerName, Uri Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies the computers on which the command runs. The default is the local computer. When you use the **ComputerName** parameter, PowerShell creates a temporary connection that's used only to run the specified command and is then closed. If you need a persistent connection, use the **Session** parameter. Type the NETBIOS name, IP address, or fully qualified domain name of one or more computers in a comma-separated list. To specify the local computer, type the computer name, localhost, or a dot (`.`). To use an IP address in the value of **ComputerName**, the command must include the **Credential** parameter. The computer must be configured for the HTTPS transport or the IP address of the remote computer must be included in the local computer's WinRM **TrustedHosts** list. For instructions to add a computer name to the **TrustedHosts** list, see [How to Add a Computer to the Trusted Host List](./about/about_remote_troubleshooting.md#how-to-add-a-computer-to-the-trusted-hosts-list). On Windows Vista and later versions of the Windows operating system, to include the local computer in the value of **ComputerName**, you must run PowerShell using the **Run as administrator** option. ```yaml Type: System.String[] Parameter Sets: ComputerName, FilePathComputerName Aliases: Cn Required: False Position: 0 Default value: Local computer Accept pipeline input: False Accept wildcard characters: False ``` ### -ConfigurationName Specifies the session configuration that is used for the new **PSSession**. Enter a configuration name or the fully qualified resource URI for a session configuration. If you specify only the configuration name, the following schema URI is prepended: `http://schemas.microsoft.com/PowerShell`. When used with SSH, this parameter specifies the subsystem to use on the target as defined in `sshd_config`. The default value for SSH is the `powershell` subsystem. The session configuration for a session is located on the remote computer. If the specified session configuration doesn't exist on the remote computer, the command fails. The default value is the value of the `$PSSessionConfigurationName` preference variable on the local computer. If this preference variable isn't set, the default is **Microsoft.PowerShell**. For more information, see [about_Preference_Variables](about/about_Preference_Variables.md). ```yaml Type: System.String Parameter Sets: ComputerName, FilePathComputerName, Uri, FilePathUri, VMId, VMName, FilePathVMId, FilePathVMName, ContainerId, FilePathContainerId Aliases: Required: False Position: Named Default value: $PSSessionConfigurationName if set on the local computer, otherwise Microsoft.PowerShell Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ConnectingTimeout Specifies the amount of time in milliseconds allowed for the initial SSH connection to complete. If the connection doesn't complete within the specified time, an error is returned. This parameter was introduced in PowerShell 7.2 ```yaml Type: System.Int32 Parameter Sets: SSHHost, FilePathSSHHost Aliases: Required: False Position: Named Default value: Unlimited Accept pipeline input: False Accept wildcard characters: False ``` ### -ConnectionUri Specifies a Uniform Resource Identifier (URI) that defines the connection endpoint of the session. The URI must be fully qualified. The format of this string is as follows: `<Transport>://<ComputerName>:<Port>/<ApplicationName>` The default value is as follows: `http://localhost:5985/WSMAN` If you don't specify a connection URI, you can use the **UseSSL** and **Port** parameters to specify the connection URI values. Valid values for the **Transport** segment of the URI are HTTP and HTTPS. If you specify a connection URI with a Transport segment, but don't specify a port, the session is created with the standards ports: 80 for HTTP and 443 for HTTPS. To use the default ports for PowerShell remoting, specify port 5985 for HTTP or 5986 for HTTPS. If the destination computer redirects the connection to a different URI, PowerShell prevents the redirection unless you use the **AllowRedirection** parameter in the command. ```yaml Type: System.Uri[] Parameter Sets: Uri, FilePathUri Aliases: URI, CU Required: False Position: 0 Default value: http://localhost:5985/WSMAN Accept pipeline input: False Accept wildcard characters: False ``` ### -ContainerId Specifies an array of container IDs. ```yaml Type: System.String[] Parameter Sets: ContainerId, FilePathContainerId Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. If you type a user name, you're prompted to enter the password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: ComputerName, FilePathComputerName, Uri, FilePathUri, VMId, VMName, FilePathVMId, FilePathVMName Aliases: Required: True (VMId, VMName, FilePathVMId, FilePathVMName), False (ComputerName, FilePathComputerName, Uri, FilePathUri) Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -EnableNetworkAccess Indicates that this cmdlet adds an interactive security token to loopback sessions. The interactive token lets you run commands in the loopback session that get data from other computers. For example, you can run a command in the session that copies XML files from a remote computer to the local computer. A loopback session is a **PSSession** that originates and ends on the same computer. To create a loopback session, omit the **ComputerName** parameter or set its value to dot (`.`), localhost, or the name of the local computer. By default, loopback sessions are created using a network token, which might not provide sufficient permission to authenticate to remote computers. The **EnableNetworkAccess** parameter is effective only in loopback sessions. If you use **EnableNetworkAccess** when you create a session on a remote computer, the command succeeds, but the parameter is ignored. You can allow remote access in a loopback session using the **CredSSP** value of the **Authentication** parameter, which delegates the session credentials to other computers. To protect the computer from malicious access, disconnected loopback sessions that have interactive tokens, which are those created using **EnableNetworkAccess**, can be reconnected only from the computer on which the session was created. Disconnected sessions that use CredSSP authentication can be reconnected from other computers. For more information, see `Disconnect-PSSession`. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerName, FilePathComputerName, Uri, FilePathUri Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -FilePath Specifies a local script that this cmdlet runs on one or more remote computers. Enter the path and filename of the script, or pipe a script path to `Invoke-Command`. The script must exist on the local computer or in a directory that the local computer can access. Use **ArgumentList** to specify the values of parameters in the script. When you use this parameter, PowerShell converts the contents of the specified script file to a script block, transmits the script block to the remote computer, and runs it on the remote computer. ```yaml Type: System.String Parameter Sets: FilePathRunspace, FilePathComputerName, FilePathUri, FilePathVMId, FilePathVMName, FilePathContainerId, FilePathSSHHost, FilePathSSHHostHash Aliases: PSPath Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -HideComputerName Indicates that this cmdlet omits the computer name of each object from the output display. By default, the name of the computer that generated the object appears in the display. This parameter affects only the output display. It doesn't change the object. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Session, FilePathRunspace, ComputerName, FilePathComputerName, Uri, FilePathUri, VMId, VMName, FilePathVMId, FilePathVMName, SSHHost, ContainerId, FilePathContainerId, SSHHostHashParam, FilePathSSHHost, FilePathSSHHostHash Aliases: HCN Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -HostName Specifies an array of computer names for a Secure Shell (SSH) based connection. This is similar to the **ComputerName** parameter except that the connection to the remote computer is made using SSH rather than Windows WinRM. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.String[] Parameter Sets: SSHHost, FilePathSSHHost Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InDisconnectedSession Indicates that this cmdlet runs a command or script in a disconnected session. When you use the **InDisconnectedSession** parameter, `Invoke-Command` creates a persistent session on each remote computer, starts the command specified by the **ScriptBlock** or **FilePath** parameter, and then disconnects from the session. The commands continue to run in the disconnected sessions. **InDisconnectedSession** enables you to run commands without maintaining a connection to the remote sessions. And, because the session is disconnected before any results are returned, **InDisconnectedSession** makes sure that all command results are returned to the reconnected session, instead of being split between sessions. You can't use **InDisconnectedSession** with the **Session** parameter or the **AsJob** parameter. Commands that use **InDisconnectedSession** return a **PSSession** object that represents the disconnected session. They don't return the command output. To connect to the disconnected session, use the `Connect-PSSession` or `Receive-PSSession` cmdlets. To get the results of commands that ran in the session, use the `Receive-PSSession` cmdlet. To run commands that generate output in a disconnected session, set the value of the **OutputBufferingMode** session option to **Drop**. If you intend to connect to the disconnected session, set the idle time-out in the session so that it provides sufficient time for you to connect before deleting the session. You can set the output buffering mode and idle time-out in the **SessionOption** parameter or in the `$PSSessionOption` preference variable. For more information about session options, see `New-PSSessionOption` and [about_Preference_Variables](./about/about_preference_variables.md). For more information about the Disconnected Sessions feature, see [about_Remote_Disconnected_Sessions](about/about_Remote_Disconnected_Sessions.md). This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerName, FilePathComputerName, Uri, FilePathUri Aliases: Disconnected Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies input to the command. Enter a variable that contains the objects or type a command or expression that gets the objects. When using the **InputObject** parameter, use the `$input` automatic variable in the value of the **ScriptBlock** parameter to represent the input objects. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -JobName Specifies a friendly name for the background job. By default, jobs are named `Job<n>`, where `<n>` is an ordinal number. If you use the **JobName** parameter in a command, the command is run as a job, and `Invoke-Command` returns a job object, even if you don't include **AsJob** in the command. For more information about PowerShell background jobs, see [about_Jobs](./About/about_Jobs.md). ```yaml Type: System.String Parameter Sets: FilePathRunspace, Session, ComputerName, FilePathComputerName, Uri, FilePathUri, SSHHost, ContainerId, FilePathContainerId, SSHHostHashParam Aliases: Required: False Position: Named Default value: Job<n> Accept pipeline input: False Accept wildcard characters: False ``` ### -KeyFilePath Specifies a key file path used by Secure Shell (SSH) to authenticate a user on a remote computer. SSH allows user authentication to be performed via private and public keys as an alternative to basic password authentication. If the remote computer is configured for key authentication, then this parameter can be used to provide the key that identifies the user. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.String Parameter Sets: SSHHost, FilePathSSHHost Aliases: IdentityFilePath Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NoNewScope Indicates that this cmdlet runs the specified command in the current scope. By default, `Invoke-Command` runs commands in their own scope. This parameter is valid only in commands that are run in the current session, that is, commands that omit both the **ComputerName** and **Session** parameters. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: InProcess Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Options Specifies a hashtable of SSH options used when connecting to a remote SSH-based session. The possible options are any values supported by the Unix-based version of the [ssh](https://man.openbsd.org/ssh#o) command. Any values explicitly passed by parameters take precedence over values passed in the **Options** hashtable. For example, using the **Port** parameter overrides any `Port` key-value pair passed in the **Options** hashtable. This parameter was added in PowerShell 7.3. ```yaml Type: System.Collections.Hashtable Parameter Sets: SSHHost, FilePathSSHHost Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Port Specifies the network port on the remote computer that is used for this command. To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are 5985 (WinRM port for HTTP) and 5986 (WinRM port for HTTPS). Before using an alternate port, configure the WinRM listener on the remote computer to listen at that port. To configure the listener, type the following two commands at the PowerShell prompt: `Remove-Item -Path WSMan:\Localhost\listener\listener* -Recurse` `New-Item -Path WSMan:\Localhost\listener -Transport http -Address * -Port \<port-number\>` Don't use the **Port** parameter unless you must. The port that is set in the command applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on all computers. ```yaml Type: System.Int32 Parameter Sets: ComputerName, FilePathComputerName, SSHHost Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RemoteDebug Used to run the invoked command in debug mode in the remote PowerShell session. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Session, FilePathRunspace, ComputerName, FilePathComputerName, Uri, FilePathUri, VMId, VMName, FilePathVMId, FilePathVMName, SSHHost, ContainerId, FilePathContainerId, SSHHostHashParam, FilePathSSHHost, FilePathSSHHostHash Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -RunAsAdministrator Indicates that this cmdlet invokes a command as an Administrator. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ContainerId, FilePathContainerId Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ScriptBlock Specifies the commands to run. Enclose the commands in braces (`{ }`) to create a script block. When using `Invoke-Command` to run a command remotely, any variables in the command are evaluated on the remote computer. > [!NOTE] > Parameters for the scriptblock can only be passed in from **ArgumentList** by position. Switch > parameters cannot be passed by position. If you need a parameter that behaves like a > **SwitchParameter** type, use a **Boolean** type instead. ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: InProcess, Session, ComputerName, Uri, VMId, VMName, SSHHost, ContainerId, SSHHostHashParam Aliases: Command Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Session Specifies an array of sessions in which this cmdlet runs the command. Enter a variable that contains **PSSession** objects or a command that creates or gets the **PSSession** objects, such as a `New-PSSession` or `Get-PSSession` command. When you create a **PSSession**, PowerShell establishes a persistent connection to the remote computer. Use a **PSSession** to run a series of related commands that share data. To run a single command or a series of unrelated commands, use the **ComputerName** parameter. For more information, see [about_PSSessions](./About/about_PSSessions.md). ```yaml Type: System.Management.Automation.Runspaces.PSSession[] Parameter Sets: Session, FilePathRunspace Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SessionName Specifies a friendly name for a disconnected session. You can use the name to refer to the session in subsequent commands, such as a `Get-PSSession` command. This parameter is valid only with the **InDisconnectedSession** parameter. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.String[] Parameter Sets: ComputerName, FilePathComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SessionOption Specifies advanced options for the session. Enter a **SessionOption** object, such as one that you create using the `New-PSSessionOption` cmdlet, or a hash table in which the keys are session option names and the values are session option values. > [!NOTE] > If you specify a hashtable for **SessionOption**, PowerShell converts the hashtable into a > **System.Management.Automation.Remoting.PSSessionOption** object. The values for keys specified > in the hashtable are cast to the matching property of the object. This behaves differently from > calling `New-PSSessionOption`. For example, the **System.TimeSpan** values for the timeout > properties, like **IdleTimeout**, convert an integer value into ticks instead of milliseconds. > For more information on the **PSSessionOption** object and its properties, see > [PSSessionOption](/dotnet/api/system.management.automation.remoting.pssessionoption) The default values for the options are determined by the value of the `$PSSessionOption` preference variable, if it's set. Otherwise, the default values are established by options set in the session configuration. The session option values take precedence over default values for sessions set in the `$PSSessionOption` preference variable and in the session configuration. However, they don't take precedence over maximum values, quotas, or limits set in the session configuration. For a description of the session options that includes the default values, see `New-PSSessionOption`. For information about the `$PSSessionOption` preference variable, see [about_Preference_Variables](About/about_Preference_Variables.md). For more information about session configurations, see [about_Session_Configurations](About/about_Session_Configurations.md). ```yaml Type: System.Management.Automation.Remoting.PSSessionOption Parameter Sets: ComputerName, FilePathComputerName, Uri, FilePathUri Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SSHConnection This parameter takes an array of hash tables where each hash table contains one or more connection parameters needed to establish a Secure Shell (SSH) connection. The **SSHConnection** parameter is useful for creating multiple sessions where each session requires different connection information. The hashtable has the following members: - **ComputerName** (or **HostName**) - **Port** - **UserName** - **KeyFilePath** (or **IdentityFilePath**) **ComputerName** (or **HostName**) is the only key-value pair that is required. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Collections.Hashtable[] Parameter Sets: SSHHostHashParam, FilePathSSHHostHash Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SSHTransport Indicates that the remote connection is established using Secure Shell (SSH). By default PowerShell uses Windows WinRM to connect to a remote computer. This switch forces PowerShell to use the **HostName** parameter for establishing an SSH based remote connection. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: SSHHost, FilePathSSHHost Aliases: Accepted values: true Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Subsystem Specifies the SSH subsystem used for the new **PSSession**. This specifies the subsystem to use on the target as defined in sshd_config. The subsystem starts a specific version of PowerShell with predefined parameters. If the specified subsystem does not exist on the remote computer, the command fails. If this parameter is not used, the default is the `powershell` subsystem. ```yaml Type: System.String Parameter Sets: SSHHost, FilePathSSHHost Aliases: Required: False Position: Named Default value: powershell Accept pipeline input: False Accept wildcard characters: False ``` ### -ThrottleLimit Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of 0, the default value, 32, is used. The throttle limit applies only to the current command, not to the session or to the computer. ```yaml Type: System.Int32 Parameter Sets: Session, FilePathRunspace, ComputerName, FilePathComputerName, Uri, FilePathUri, VMId, VMName, FilePathVMId, FilePathVMName, ContainerId, FilePathContainerId Aliases: Required: False Position: Named Default value: 32 Accept pipeline input: False Accept wildcard characters: False ``` ### -UserName Specifies the username for the account used to run a command on the remote computer. The user authentication method depends on how Secure Shell (SSH) is configured on the remote computer. If SSH is configured for basic password authentication, then you'll be prompted for the user password. If SSH is configured for key-based user authentication then a key file path can be provided via the **KeyFilePath** parameter and no password prompt occurs. If the client user key file is located in an SSH known location, then the **KeyFilePath** parameter isn't needed for key-based authentication, and user authentication occurs automatically based on the username. For more information, see your platform's SSH documentation about key-based user authentication. This isn't a required parameter. If the **UserName** parameter isn't specified, then the current logged on username is used for the connection. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.String Parameter Sets: SSHHost, FilePathSSHHost Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to establish a connection to the remote computer. By default, SSL isn't used. WS-Management encrypts all PowerShell content transmitted over the network. The **UseSSL** parameter is an additional protection that sends the data across an HTTPS, instead of HTTP. If you use this parameter, but SSL isn't available on the port that's used for the command, the command fails. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerName, FilePathComputerName Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -VMId Specifies an array of IDs of virtual machines. ```yaml Type: System.Guid[] Parameter Sets: VMId, FilePathVMId Aliases: VMGuid Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -VMName Specifies an array of names of virtual machines. ```yaml Type: System.String[] Parameter Sets: VMName, FilePathVMName Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.ScriptBlock You can pipe a command in a script block to `Invoke-Command`. Use the `$input` automatic variable to represent the input objects in the command. ## OUTPUTS ### System.Management.Automation.PSRemotingJob If you use the **AsJob** parameter, this cmdlet returns a job object. ### System.Management.Automation.Runspaces.PSSession If you use the **InDisconnectedSession** parameter, this cmdlet returns a **PSSession** object. ### System.Object By default, this cmdlet returns the output of the invoked command, which is the value of the **ScriptBlock** parameter. ## NOTES PowerShell includes the following aliases for `Invoke-Command`: - All platforms: - `icm` On Windows Vista, and later versions of the Windows operating system, to use the **ComputerName** parameter of `Invoke-Command` to run a command on the local computer, you must run PowerShell using the **Run as administrator** option. When you run commands on multiple computers, PowerShell connects to the computers in the order in which they appear in the list. However, the command output is displayed in the order that it's received from the remote computers, which might be different. Errors that result from the command that `Invoke-Command` runs are included in the command results. Errors that would be terminating errors in a local command are treated as non-terminating errors in a remote command. This strategy makes sure that terminating errors on one computer don't close the command on all computers on which it's run. This practice is used even when a remote command is run on a single computer. If the remote computer isn't in a domain that the local computer trusts, the computer might not be able to authenticate the user's credentials. To add the remote computer to the list of trusted hosts in WS-Management, use the following command in the `WSMan` provider, where `<Remote-Computer-Name>` is the name of the remote computer: `Set-Item -Path WSMan:\Localhost\Client\TrustedHosts -Value \<Remote-Computer-Name\>` When you disconnect a **PSSession** using the **InDisconnectedSession** parameter, the session state is **Disconnected** and the availability is **None**. The value of the **State** property is relative to the current session. A value of **Disconnected** means that the **PSSession** isn't connected to the current session. However, it doesn't mean that the **PSSession** is disconnected from all sessions. It might be connected to a different session. To determine whether you can connect or reconnect to the session, use the **Availability** property. An **Availability** value of **None** indicates that you can connect to the session. A value of **Busy** indicates that you can't connect to the **PSSession** because it's connected to another session. For more information about the values of the **State** property of sessions, see [RunspaceState](/dotnet/api/system.management.automation.runspaces.runspacestate). For more information about the values of the **Availability** property of sessions, see [RunspaceAvailability](/dotnet/api/system.management.automation.runspaces.runspaceavailability). The **HostName** and **SSHConnection** parameters were included starting with PowerShell 6.0. They were added to provide PowerShell remoting based on Secure Shell (SSH). PowerShell and SSH are supported on multiple platforms (Windows, Linux, macOS) and PowerShell remoting works over these platforms where PowerShell and SSH are installed and configured. This is separate from the previous Windows only remoting that is based on WinRM and many of the WinRM specific features and limitations don't apply. For example WinRM based quotas, session options, custom endpoint configuration, and disconnect/reconnect features are currently not supported. For more information about how to set up PowerShell SSH remoting, see [PowerShell Remoting Over SSH](/powershell/scripting/learn/remoting/ssh-remoting-in-powershell-core). The `ssh` executable obtains configuration data from the following sources in the following order: 1. command-line options 1. user's configuration file (~/.ssh/config) 1. system-wide configuration file (/etc/ssh/ssh_config) The following cmdlet parameters get mapped into `ssh` parameters and options: | Cmdlet parameter | ssh parameter | equivalent ssh -o option | | -------------------------- | ------------------------------- | ------------------------------- | | `-KeyFilePath` | `-i <KeyFilePath>` | `-o IdentityFile=<KeyFilePath>` | | `-UserName` | `-l <UserName>` | `-o User=<UserName>` | | `-Port` | `-p <Port>` | `-o Port=<Port>` | | `-ComputerName -Subsystem` | `-s <ComputerName> <Subsystem>` | `-o Host=<ComputerName>` | Any values explicitly passed by parameters take precedence over values passed in the **Options** hashtable. For more information about `ssh_config` files, see [ssh_config(5)](https://man.openbsd.org/ssh_config.5). ## RELATED LINKS [about_PSSessions](./About/about_PSSessions.md) [about_Remote](./About/about_Remote.md) [about_Remote_Disconnected_Sessions](./About/about_Remote_Disconnected_Sessions.md) [about_Remote_Troubleshooting](./About/about_remote_troubleshooting.md) [about_Remote_Variables](./About/about_Remote_Variables.md) [about_Scopes](./About/about_scopes.md) [Enter-PSSession](Enter-PSSession.md) [Exit-PSSession](Exit-PSSession.md) [Get-PSSession](Get-PSSession.md) [Invoke-Item](../Microsoft.PowerShell.Management/Invoke-Item.md) [New-PSSession](New-PSSession.md) [Remove-PSSession](Remove-PSSession.md) [WSMan Provider](../Microsoft.WsMan.Management/About/about_WSMan_Provider.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Invoke-History.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 09/15/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/invoke-history?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Invoke-History --- # Invoke-History ## SYNOPSIS Runs commands from the session history. ## SYNTAX ``` Invoke-History [[-Id] <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Invoke-History` cmdlet runs commands from the session history. You can pass objects representing the commands from Get-History to `Invoke-History`, or you can identify commands in the current history by using their **Id** number. To find the identification number of a command, use the `Get-History` cmdlet. The session history is managed separately from the history maintained by the **PSReadLine** module. Both histories are available in sessions where **PSReadLine** is loaded. This cmdlet only works with the session history. For more information see, [about_PSReadLine](../PSReadLine/About/about_PSReadLine.md). ## EXAMPLES ### Example 1: Run the most recent command in the history This example runs the last, or most recent, command in the session history. You can abbreviate this command as `r`, the alias for `Invoke-History`. ```powershell Invoke-History ``` ### Example 2: Run the command that has a specified ID This example runs the command in the session history with **Id** 132. Because the name of the **Id** parameter is optional, you can abbreviate this command as the following: `Invoke-History 132`, `ihy 132`, or `r 132`. ```powershell Invoke-History -Id 132 ``` ### Example 3: Run the most recent command by using the command text This example runs the most recent `Get-Process` command in the session history. When you type characters for the **Id** parameter, `Invoke-History` runs the first command that it finds that matches the pattern, starting with the most recent commands. ```powershell Invoke-History -Id get-pr ``` > [!NOTE] > Pattern matching is case-insensitive, but the pattern matches the beginning of the line. ### Example 4: Run a sequence of commands from the history This example runs commands 16 through 24. Because you can list only one **Id** value, the command uses the `ForEach-Object` cmdlet to run the `Invoke-History` command one time for each **Id** value. ```powershell 16..24 | ForEach-Object {Invoke-History -Id $_ } ``` ### Example 5 This example runs the seven commands in the history that end with command 255 (249 through 255). It uses the `Get-History` cmdlet to retrieve the commands. Because you can list only one **Id** value, the command uses the `ForEach-Object` cmdlet to run the `Invoke-History` command once for each **Id** value. ```powershell Get-History -Id 255 -Count 7 | ForEach-Object {Invoke-History -Id $_.Id} ``` ## PARAMETERS ### -Id Specifies the **Id** of a command in the history. You can type the **Id** number of the command or the first few characters of the command. If you type characters, `Invoke-History` matches the most recent commands first. If you omit this parameter, `Invoke-History` runs the last, or most recent, command. To find the **Id** number of a command, use the `Get-History` cmdlet. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a history **Id** to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output of its own, but the commands it runs may return their own output. ## NOTES PowerShell includes the following aliases for `Invoke-History`: - All platforms: - `ihy` - `r` The session history is a list of the commands entered during the session. The session history represents the order of execution, the status, and the start and end times of the command. As you enter each command, PowerShell adds it to the history so that you can reuse it. For more information about the session history, see [about_History](About/about_History.md). ## RELATED LINKS [Add-History](Add-History.md) [Clear-History](Clear-History.md) [Get-History](Get-History.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Microsoft.PowerShell.Core.md

--- Download Help Link: https://aka.ms/powershell75-help Help Version: 7.6.0.0 Locale: en-US Module Guid: 00000000-0000-0000-0000-000000000000 Module Name: Microsoft.PowerShell.Core ms.date: 09/02/2024 schema: 2.0.0 title: Microsoft.PowerShell.Core --- # Microsoft.PowerShell.Core Module ## Description The **Microsoft.PowerShell.Core** snap-in contains cmdlets and providers that manage the basic features of PowerShell. PowerShell loads **Microsoft.PowerShell.Core** snap-in automatically at startup. This is not a module. You can't import it using `Import-Module` or remove it using `Remove-Module`. ## Microsoft.PowerShell.Core Cmdlets ### [Add-History](Add-History.md) Appends entries to the session history. ### [Clear-History](Clear-History.md) Deletes entries from the PowerShell session command history. ### [Clear-Host](Clear-Host.md) Clears the display in the host program. ### [Connect-PSSession](Connect-PSSession.md) Reconnects to disconnected sessions. ### [Debug-Job](Debug-Job.md) Debugs a running background or remote job. ### [Disable-ExperimentalFeature](Disable-ExperimentalFeature.md) Disable an experimental feature on startup of new instance of PowerShell. ### [Disable-PSRemoting](Disable-PSRemoting.md) Prevents PowerShell endpoints from receiving remote connections. ### [Disable-PSSessionConfiguration](Disable-PSSessionConfiguration.md) Disables session configurations on the local computer. ### [Disconnect-PSSession](Disconnect-PSSession.md) Disconnects from a session. ### [Enable-ExperimentalFeature](Enable-ExperimentalFeature.md) Enable an experimental feature on startup of new instance of PowerShell. ### [Enable-PSRemoting](Enable-PSRemoting.md) Configures the computer to receive remote commands. ### [Enable-PSSessionConfiguration](Enable-PSSessionConfiguration.md) Enables the session configurations on the local computer. ### [Enter-PSHostProcess](Enter-PSHostProcess.md) Connects to and enters into an interactive session with a local process. ### [Enter-PSSession](Enter-PSSession.md) Starts an interactive session with a remote computer. ### [Exit-PSHostProcess](Exit-PSHostProcess.md) Closes an interactive session with a local process. ### [Exit-PSSession](Exit-PSSession.md) Ends an interactive session with a remote computer. ### [Export-ModuleMember](Export-ModuleMember.md) Specifies the module members that are exported. ### [ForEach-Object](ForEach-Object.md) Performs an operation against each item in a collection of input objects. ### [Get-Command](Get-Command.md) Gets all commands. ### [Get-ExperimentalFeature](Get-ExperimentalFeature.md) Gets experimental features. ### [Get-Help](Get-Help.md) Displays information about PowerShell commands and concepts. ### [Get-History](Get-History.md) Gets a list of the commands entered during the current session. ### [Get-Job](Get-Job.md) Gets PowerShell background jobs that are running in the current session. ### [Get-Module](Get-Module.md) List the modules imported in the current session or that can be imported from the PSModulePath. ### [Get-PSHostProcessInfo](Get-PSHostProcessInfo.md) Gets process information about the PowerShell host. ### [Get-PSSession](Get-PSSession.md) Gets the PowerShell sessions on local and remote computers. ### [Get-PSSessionCapability](Get-PSSessionCapability.md) Gets the capabilities of a specific user on a constrained session configuration. ### [Get-PSSessionConfiguration](Get-PSSessionConfiguration.md) Gets the registered session configurations on the computer. ### [Get-PSSubsystem](Get-PSSubsystem.md) Retrieves information about the subsystems registered in PowerShell. (Experimental Feature) ### [Import-Module](Import-Module.md) Adds modules to the current session. ### [Invoke-Command](Invoke-Command.md) Runs commands on local and remote computers. ### [Invoke-History](Invoke-History.md) Runs commands from the session history. ### [New-Module](New-Module.md) Creates a new dynamic module that exists only in memory. ### [New-ModuleManifest](New-ModuleManifest.md) Creates a new module manifest. ### [New-PSRoleCapabilityFile](New-PSRoleCapabilityFile.md) Creates a file that defines a set of capabilities to be exposed through a session configuration. ### [New-PSSession](New-PSSession.md) Creates a persistent connection to a local or remote computer. ### [New-PSSessionConfigurationFile](New-PSSessionConfigurationFile.md) Creates a file that defines a session configuration. ### [New-PSSessionOption](New-PSSessionOption.md) Creates an object that contains advanced options for a PSSession. ### [New-PSTransportOption](New-PSTransportOption.md) Creates an object that contains advanced options for a session configuration. ### [Out-Default](Out-Default.md) Sends the output to the default formatter and to the default output cmdlet. ### [Out-Host](Out-Host.md) Sends output to the command line. ### [Out-Null](Out-Null.md) Hides the output instead of sending it down the pipeline or displaying it. ### [Receive-Job](Receive-Job.md) Gets the results of the PowerShell background jobs in the current session. ### [Receive-PSSession](Receive-PSSession.md) Gets results of commands in disconnected sessions ### [Register-ArgumentCompleter](Register-ArgumentCompleter.md) Registers a custom argument completer. ### [Register-PSSessionConfiguration](Register-PSSessionConfiguration.md) Creates and registers a new session configuration. ### [Remove-Job](Remove-Job.md) Deletes a PowerShell background job. ### [Remove-Module](Remove-Module.md) Removes modules from the current session. ### [Remove-PSSession](Remove-PSSession.md) Closes one or more PowerShell sessions (PSSessions). ### [Save-Help](Save-Help.md) Downloads and saves the newest help files to a file system directory. ### [Set-PSDebug](Set-PSDebug.md) Turns script debugging features on and off, sets the trace level, and toggles strict mode. ### [Set-PSSessionConfiguration](Set-PSSessionConfiguration.md) Changes the properties of a registered session configuration. ### [Set-StrictMode](Set-StrictMode.md) Establishes and enforces coding rules in expressions, scripts, and script blocks. ### [Start-Job](Start-Job.md) Starts a PowerShell background job. ### [Stop-Job](Stop-Job.md) Stops a PowerShell background job. ### [Switch-Process](Switch-Process.md) On Linux and macOS, the cmdlet calls the `execv()` function to provide similar behavior as POSIX shells. ### [TabExpansion2](TabExpansion2.md) A helper function that wraps the `CompleteInput()` method of the **CommandCompletion** class to provide tab completion for PowerShell scripts. ### [Test-ModuleManifest](Test-ModuleManifest.md) Verifies that a module manifest file accurately describes the contents of a module. ### [Test-PSSessionConfigurationFile](Test-PSSessionConfigurationFile.md) Verifies the keys and values in a session configuration file. ### [Unregister-PSSessionConfiguration](Unregister-PSSessionConfiguration.md) Deletes registered session configurations from the computer. ### [Update-Help](Update-Help.md) Downloads and installs the newest help files on your computer. ### [Wait-Job](Wait-Job.md) Waits until one or all of the PowerShell jobs running in the session are in a terminating state. ### [Where-Object](Where-Object.md) Selects objects from a collection based on their property values.

#File: reference/7.6/Microsoft.PowerShell.Core/New-Module.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/new-module?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-Module --- # New-Module ## SYNOPSIS Creates a new dynamic module that exists only in memory. ## SYNTAX ### ScriptBlock (Default) ``` New-Module [-ScriptBlock] <ScriptBlock> [-Function <String[]>] [-Cmdlet <String[]>] [-ReturnResult] [-AsCustomObject] [-ArgumentList <Object[]>] [<CommonParameters>] ``` ### Name ``` New-Module [-Name] <String> [-ScriptBlock] <ScriptBlock> [-Function <String[]>] [-Cmdlet <String[]>] [-ReturnResult] [-AsCustomObject] [-ArgumentList <Object[]>] [<CommonParameters>] ``` ## DESCRIPTION The `New-Module` cmdlet creates a dynamic module from a script block. The members of the dynamic module, such as functions and variables, are immediately available in the session and remain available until you close the session. Like static modules, by default, the cmdlets and functions in a dynamic module are exported and the variables and aliases are not. However, you can use the Export-ModuleMember cmdlet and the parameters of `New-Module` to override the defaults. You can also use the **AsCustomObject** parameter of `New-Module` to return the dynamic module as a custom object. The members of the modules, such as functions, are implemented as script methods of the custom object instead of being imported into the session. Dynamic modules exist only in memory, not on disk. Like all modules, the members of dynamic modules run in a private module scope that is a child of the global scope. Get-Module cannot get a dynamic module, but Get-Command can get the exported members. To make a dynamic module available to `Get-Module`, pipe a `New-Module` command to Import-Module, or pipe the module object that `New-Module` returns to `Import-Module`. This action adds the dynamic module to the `Get-Module` list, but it does not save the module to disk or make it persistent. ## EXAMPLES ### Example 1: Create a dynamic module This example creates a new dynamic module with a function called `Hello`. The command returns a module object that represents the new dynamic module. ```powershell New-Module -ScriptBlock {function Hello {"Hello!"}} ``` ```Output Name : __DynamicModule_2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5 Path : 2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5 Description : Guid : 00000000-0000-0000-0000-000000000000 Version : 0.0 ModuleBase : ModuleType : Script PrivateData : AccessMode : ReadWrite ExportedAliases : {} ExportedCmdlets : {} ExportedFunctions : {[Hello, Hello]} ExportedVariables : {} NestedModules : {} ``` ### Example 2: Working with dynamic modules and Get-Module and Get-Command This example demonstrates that dynamic modules are not returned by the `Get-Module` cmdlet. The members that they export are returned by the `Get-Command` cmdlet. ```powershell New-Module -ScriptBlock {function Hello {"Hello!"}} ``` ```Output Name : __DynamicModule_2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5 Path : 2ceb1d0a-990f-45e4-9fe4-89f0f6ead0e5 Description : Guid : 00000000-0000-0000-0000-000000000000 Version : 0.0 ModuleBase : ModuleType : Script PrivateData : AccessMode : ReadWrite ExportedAliases : {} ExportedCmdlets : {} ExportedFunctions : {[Hello, Hello]} ExportedVariables : {} NestedModules : {} ``` ```powershell Get-Module Get-Command Hello ``` ```Output CommandType Name Definition ----------- ---- ---------- Function Hello "Hello!" ``` ### Example 3: Export a variable into the current session This example uses the `Export-ModuleMember` cmdlet to export a variable into the current session. Without the `Export-ModuleMember` command, only the function is exported. ```powershell New-Module -ScriptBlock {$SayHelloHelp="Type 'SayHello', a space, and a name."; function SayHello ($Name) { "Hello, $Name" }; Export-ModuleMember -Function SayHello -Variable SayHelloHelp} $SayHelloHelp ``` ```Output Type 'SayHello', a space, and a name. ``` ```powershell SayHello Jeffrey ``` ```Output Hello, Jeffrey ``` The output shows that both the variable and the function were exported into the session. ### Example 4: Make a dynamic module available to Get-Module This example demonstrates that you can make a dynamic module available to `Get-Module` by piping the dynamic module to `Import-Module`. `New-Module` creates a module object that is piped to the `Import-Module` cmdlet. The **Name** parameter of `New-Module` assigns a friendly name to the module. Because `Import-Module` does not return any objects by default, there is no output from this command. `Get-Module` that the **GreetingModule** has been imported into the current session. ```powershell New-Module -ScriptBlock {function Hello {"Hello!"}} -Name GreetingModule | Import-Module Get-Module ``` ```Output Name : GreetingModule Path : d54dfdac-4531-4db2-9dec-0b4b9c57a1e5 Description : Guid : 00000000-0000-0000-0000-000000000000 Version : 0.0 ModuleBase : ModuleType : Script PrivateData : AccessMode : ReadWrite ExportedAliases : {} ExportedCmdlets : {} ExportedFunctions : {[Hello, Hello]} ExportedVariables : {} NestedModules : {} ``` ```powershell Get-Command Hello ``` ```Output CommandType Name Definition ----------- ---- ---------- Function Hello "Hello!" ``` The `Get-Command` cmdlet shows the `Hello` function that the dynamic module exports. ### Example 5: Generate a custom object that has exported functions This example shows how to use the **AsCustomObject** parameter of `New-Module` to generate a custom object that has script methods that represent the exported functions. The `New-Module` cmdlet creates a dynamic module with two functions, `Hello` and `Goodbye`. The **AsCustomObject** parameter creates a custom object instead of the **PSModuleInfo** object that `New-Module` generates by default. This custom object is saved in the `$m` variable. The `$m` variable appears to have no assigned value. ```powershell $m = New-Module -ScriptBlock { function Hello ($Name) {"Hello, $Name"} function Goodbye ($Name) {"Goodbye, $Name"} } -AsCustomObject $m $m | Get-Member ``` ```Output 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() Goodbye ScriptMethod System.Object Goodbye(); Hello ScriptMethod System.Object Hello(); ``` ```powershell $m.Goodbye("Jane") ``` ```Output Goodbye, Jane ``` ```powershell $m.Hello("Manoj") ``` ```Output Hello, Manoj ``` Piping `$m` to the `Get-Member` cmdlet displays the properties and methods of the custom object. The output shows that the object has script methods that represent the `Hello` and `Goodbye` functions. Finally, we call these script methods and display the results. ### Example 6: Get the results of the script block This example uses the **ReturnResult** parameter to request the results of running the script block instead of requesting a module object. The script block in the new module defines the `SayHello` function and then calls the function. ```powershell New-Module -ScriptBlock {function SayHello {"Hello, World!"}; SayHello} -ReturnResult ``` ```Output Hello, World! ``` ## PARAMETERS ### -ArgumentList Specifies an array of arguments which are parameter values that are passed to the script block. For more information about the behavior of **ArgumentList**, see [about_Splatting](about/about_Splatting.md#splatting-with-arrays). ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Args Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -AsCustomObject Indicates that this cmdlet returns a custom object that represents the dynamic module. The module members are implemented as script methods of the custom object, but they are not imported into the session. You can save the custom object in a variable and use dot notation to invoke the members. If the module has multiple members with the same name, such as a function and a variable that are both named A, only one member with each name can be accessed from the custom object. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Cmdlet Specifies an array of cmdlets that this cmdlet exports from the module into the current session. Enter a comma-separated list of cmdlets. Wildcard characters are permitted. By default, all cmdlets in the module are exported. You cannot define cmdlets in a script block, but a dynamic module can include cmdlets if it imports the cmdlets from a binary module. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Function Specifies an array of functions that this cmdlet exports from the module into the current session. Enter a comma-separated list of functions. Wildcard characters are permitted. By default, all functions defined in a module are exported. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Name Specifies a name for the new module. You can also pipe a module name to New-Module. The default value is an autogenerated name that starts with `__DynamicModule_` and is followed by a GUID that specifies the path of the dynamic module. ```yaml Type: System.String Parameter Sets: Name Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -ReturnResult Indicates that this cmdlet runs the script block and returns the script block results instead of returning a module object. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ScriptBlock Specifies the contents of the dynamic module. Enclose the contents in braces (`{}`) to create a script block. This parameter is required. ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a module name to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSModuleInfo This cmdlet generates a **PSModuleInfo** object by default. ### System.Management.Automation.PSCustomObject If you use the **AsCustomObject** parameter, it generates a **PSCustomObject** object. ### System.Object If you use the **ReturnResult** parameter, this cmdlet returns the result of evaluating the script block in the dynamic module. ## NOTES PowerShell includes the following aliases for `New-Module`: - All platforms: - `nmo` ## RELATED LINKS [Export-ModuleMember](Export-ModuleMember.md) [Get-Module](Get-Module.md) [Import-Module](Import-Module.md) [Remove-Module](Remove-Module.md)

#File: reference/7.6/Microsoft.PowerShell.Core/New-ModuleManifest.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/new-modulemanifest?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-ModuleManifest --- # New-ModuleManifest ## SYNOPSIS Creates a new module manifest. ## SYNTAX ### All ``` New-ModuleManifest [-Path] <String> [-NestedModules <Object[]>] [-Guid <Guid>] [-Author <String>] [-CompanyName <String>] [-Copyright <String>] [-RootModule <String>] [-ModuleVersion <Version>] [-Description <String>] [-ProcessorArchitecture <ProcessorArchitecture>] [-PowerShellVersion <Version>] [-CLRVersion <Version>] [-DotNetFrameworkVersion <Version>] [-PowerShellHostName <String>] [-PowerShellHostVersion <Version>] [-RequiredModules <Object[]>] [-TypesToProcess <String[]>] [-FormatsToProcess <String[]>] [-ScriptsToProcess <String[]>] [-RequiredAssemblies <String[]>] [-FileList <String[]>] [-ModuleList <Object[]>] [-FunctionsToExport <String[]>] [-AliasesToExport <String[]>] [-VariablesToExport <String[]>] [-CmdletsToExport <String[]>] [-DscResourcesToExport <String[]>] [-CompatiblePSEditions <String[]>] [-PrivateData <Object>] [-Tags <String[]>] [-ProjectUri <Uri>] [-LicenseUri <Uri>] [-IconUri <Uri>] [-ReleaseNotes <String>] [-Prerelease <String>] [-RequireLicenseAcceptance] [-ExternalModuleDependencies <String[]>] [-HelpInfoUri <String>] [-PassThru] [-DefaultCommandPrefix <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `New-ModuleManifest` cmdlet creates a new module manifest (`.psd1`) file, populates its values, and saves the manifest file in the specified path. Module authors can use this cmdlet to create a manifest for their module. A module manifest is a `.psd1` file that contains a hash table. The keys and values in the hash table describe the contents and attributes of the module, define the prerequisites, and determine how the components are processed. Manifests aren't required for a module. `New-ModuleManifest` creates a manifest that includes all the commonly used manifest keys, so you can use the default output as a manifest template. To add or change values, or to add module keys that this cmdlet doesn't add, open the resulting file in a text editor. Each parameter, except for **Path** and **PassThru**, creates a module manifest key and its value. In a module manifest, only the **ModuleVersion** key is required. Unless specified in the parameter description, if you omit a parameter from the command, `New-ModuleManifest` creates a comment string for the associated value that has no effect. In PowerShell 2.0, `New-ModuleManifest` prompts you for the values of commonly used parameters that aren't specified in the command, in addition to required parameter values. Beginning in PowerShell 3.0, `New-ModuleManifest` prompts only when required parameter values aren't specified. If you are planning to publish your module in the PowerShell Gallery, the manifest must contain values for certain properties. For more information, see [Required metadata for items published to the PowerShell Gallery](/powershell/gallery/how-to/publishing-packages/publishing-a-package#required-metadata-for-items-published-to-the-powershell-gallery) in the Gallery documentation. ## EXAMPLES ### Example 1 - Create a new module manifest This example creates a new module manifest in the file that is specified by the **Path** parameter. The **PassThru** parameter sends the output to the pipeline and to the file. The output shows the default values of all keys in the manifest. ```powershell New-ModuleManifest -Path C:\ps-test\Test-Module\Test-Module.psd1 -PassThru ``` ```Output # # Module manifest for module 'Test-Module' # # Generated by: ContosoAdmin # # Generated on: 7/12/2019 # @{ # Script module or binary module file associated with this manifest. # RootModule = '' # Version number of this module. ModuleVersion = '0.0.1' # Supported PSEditions # CompatiblePSEditions = @() # ID used to uniquely identify this module GUID = 'e1826c6e-c420-4eef-9ac8-185e3669ca6a' # Author of this module Author = 'ContosoAdmin' # Company or vendor of this module CompanyName = 'Unknown' # Copyright statement for this module Copyright = '(c) ContosoAdmin. All rights reserved.' # Description of the functionality provided by this module # Description = '' # Minimum version of the PowerShell engine required by this module # PowerShellVersion = '' # Name of the PowerShell host required by this module # PowerShellHostName = '' # Minimum version of the PowerShell host required by this module # PowerShellHostVersion = '' # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # DotNetFrameworkVersion = '' # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only. # CLRVersion = '' # Processor architecture (None, X86, Amd64) required by this module # ProcessorArchitecture = '' # Modules that must be imported into the global environment prior to importing this module # RequiredModules = @() # Assemblies that must be loaded prior to importing this module # RequiredAssemblies = @() # Script files (.ps1) that are run in the caller's environment prior to importing this module. # ScriptsToProcess = @() # Type files (.ps1xml) to be loaded when importing this module # TypesToProcess = @() # Format files (.ps1xml) to be loaded when importing this module # FormatsToProcess = @() # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess # NestedModules = @() # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. FunctionsToExport = @() # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export. CmdletsToExport = @() # Variables to export from this module VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. AliasesToExport = @() # DSC resources to export from this module # DscResourcesToExport = @() # List of all modules packaged with this module # ModuleList = @() # List of all files packaged with this module # FileList = @() # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. # Tags = @() # A URL to the license for this module. # LicenseUri = '' # A URL to the main website for this project. # ProjectUri = '' # A URL to an icon representing this module. # IconUri = '' # ReleaseNotes of this module # ReleaseNotes = '' # Prerelease string of this module # Prerelease = '' # Flag to indicate whether the module requires explicit user acceptance for install/update/save # RequireLicenseAcceptance = $false # External dependent modules of this module # ExternalModuleDependencies = @() } # End of PSData hashtable } # End of PrivateData hashtable # HelpInfo URI of this module # HelpInfoURI = '' # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix. # DefaultCommandPrefix = '' } ``` ### Example 2 - Create a new manifest with some prepopulated settings This example creates a new module manifest. It uses the **PowerShellVersion** and **AliasesToExport** parameters to add values to the corresponding manifest keys. ```powershell $moduleSettings = @{ PowerShellVersion = 1.0 Path = 'C:\ps-test\ManifestTest.psd1' AliasesToExport = @( 'JKBC' 'DRC' 'TAC' ) } New-ModuleManifest @moduleSettings ``` ### Example 3 - Create a manifest that requires other modules This example uses a string format to specify the name of the **BitsTransfer** module and the hash table format to specify the name, a **GUID**, and a version of the **PSScheduledJob** module. ```powershell $moduleSettings = @{ RequiredModules = ("BitsTransfer", @{ ModuleName="PSScheduledJob" ModuleVersion="1.0.0.0"; GUID="50cdb55f-5ab7-489f-9e94-4ec21ff51e59" }) Path = 'C:\ps-test\ManifestTest.psd1' } New-ModuleManifest @moduleSettings ``` This example shows how to use the string and hash table formats of the **ModuleList**, **RequiredModules**, and **NestedModules** parameter. You can combine strings and hash tables in the same parameter value. ### Example 4 - Create a manifest that supports updateable help This example uses the **HelpInfoUri** parameter to create a **HelpInfoUri** key in the module manifest. The value of the parameter and the key must begin with **http** or **https**. This value tells the Updatable Help system where to find the HelpInfo XML updatable help information file for the module. ```powershell $moduleSettings = @{ HelpInfoUri = 'http://https://go.microsoft.com/fwlink/?LinkID=603' Path = 'C:\ps-test\ManifestTest.psd1' } New-ModuleManifest @moduleSettings ``` For information about Updatable Help, see [about_Updatable_Help](./About/about_Updatable_Help.md). For information about the HelpInfo XML file, see [Supporting Updatable Help](/powershell/scripting/developer/module/supporting-updatable-help). ### Example 5 - Getting module information This example shows how to get the configuration values of a module. The values in the module manifest are reflected in the values of properties of the module object. The `Get-Module` cmdlet is used to get the **Microsoft.PowerShell.Diagnostics** module using the **List** parameter. The command sends the module to the `Format-List` cmdlet to display all properties and values of the module object. ```powershell Get-Module Microsoft.PowerShell.Diagnostics -List | Format-List -Property * ``` ```Output LogPipelineExecutionDetails : False Name : Microsoft.PowerShell.Diagnostics Path : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Diagnostics\Micro soft.PowerShell.Diagnostics.psd1 Definition : Description : Guid : ca046f10-ca64-4740-8ff9-2565dba61a4f HelpInfoUri : https://go.microsoft.com/fwlink/?LinkID=210596 ModuleBase : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Diagnostics PrivateData : Version : 3.0.0.0 ModuleType : Manifest Author : Microsoft Corporation AccessMode : ReadWrite ClrVersion : 4.0 CompanyName : Microsoft Corporation Copyright : Microsoft Corporation. All rights reserved. DotNetFrameworkVersion : ExportedFunctions : {} ExportedCmdlets : {[Get-WinEvent, Get-WinEvent], [Get-Counter, Get-Counter], [Import-Counter, Import-Counter], [Export-Counter, Export-Counter]...} ExportedCommands : {[Get-WinEvent, Get-WinEvent], [Get-Counter, Get-Counter], [Import-Counter, Import-Counter], [Export-Counter, Export-Counter]...} FileList : {} ModuleList : {} NestedModules : {} PowerShellHostName : PowerShellHostVersion : PowerShellVersion : 3.0 ProcessorArchitecture : None Scripts : {} RequiredAssemblies : {} RequiredModules : {} RootModule : ExportedVariables : {} ExportedAliases : {} ExportedWorkflows : {} SessionState : OnRemove : ExportedFormatFiles : {C:\Windows\system32\WindowsPowerShell\v1.0\Event.format.ps1xml, C:\Windows\system32\WindowsPowerShell\v1.0\Diagnostics.format.ps1xml} ExportedTypeFiles : {C:\Windows\system32\WindowsPowerShell\v1.0\GetEvent.types.ps1xml} ``` ## PARAMETERS ### -AliasesToExport Specifies the aliases that the module exports. Wildcards are permitted. You can use this parameter to restrict the aliases that are exported by the module. It can remove aliases from the list of exported aliases, but it can't add aliases to the list. If you omit this parameter, `New-ModuleManifest` creates an **AliasesToExport** key with a value of `*` (all), meaning that all aliases defined in the module are exported by the manifest. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: * (all) Accept pipeline input: False Accept wildcard characters: True ``` ### -Author Specifies the module author. If you omit this parameter, `New-ModuleManifest` creates an **Author** key with the name of the current user. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Name of the current user Accept pipeline input: False Accept wildcard characters: False ``` ### -ClrVersion Specifies the minimum version of the Common Language Runtime (CLR) of the Microsoft .NET Framework that the module requires. > [!NOTE] > This setting is valid for the PowerShell Desktop edition only, such as Windows PowerShell 5.1, > and only applies to .NET Framework versions lower than 4.5. This requirement has no effect for > newer versions of PowerShell or the .NET Framework. ```yaml Type: System.Version Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CmdletsToExport Specifies the cmdlets that the module exports. Wildcards are permitted. You can use this parameter to restrict the cmdlets that are exported by the module. It can remove cmdlets from the list of exported cmdlets, but it can't add cmdlets to the list. If you omit this parameter, `New-ModuleManifest` creates a **CmdletsToExport** key with a value of `*` (all), meaning that all cmdlets defined in the module are exported by the manifest. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: * (all) Accept pipeline input: False Accept wildcard characters: True ``` ### -CompanyName Identifies the company or vendor who created the module. If you omit this parameter, `New-ModuleManifest` creates a **CompanyName** key with a value of "Unknown". ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: "Unknown" Accept pipeline input: False Accept wildcard characters: False ``` ### -CompatiblePSEditions Specifies the module's compatible PSEditions. For information about PSEdition, see [Modules with compatible PowerShell Editions](/powershell/gallery/concepts/module-psedition-support). ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Accepted values: Desktop, Core Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Copyright Specifies a copyright statement for the module. If you omit this parameter, `New-ModuleManifest` creates a **Copyright** key with a value of `(c) <year> <username>. All rights reserved.` where `<year>` is the current year and `<username>` is the value of the **Author** key. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: (c) <year> <username>. All rights reserved. Accept pipeline input: False Accept wildcard characters: False ``` ### -DefaultCommandPrefix Specifies a prefix that is prepended to the nouns of all commands in the module when they're imported into a session. Enter a prefix string. Prefixes prevent command name conflicts in a user's session. Module users can override this prefix by specifying the **Prefix** parameter of the `Import-Module` cmdlet. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Description Describes the contents of the module. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DotNetFrameworkVersion Specifies the minimum version of the Microsoft .NET Framework that the module requires. > [!NOTE] > This setting is valid for the PowerShell Desktop edition only, such as Windows PowerShell 5.1, > and only applies to .NET Framework versions lower than 4.5. This requirement has no effect for > newer versions of PowerShell or the .NET Framework. ```yaml Type: System.Version Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DscResourcesToExport Specifies the Desired State Configuration (DSC) resources that the module exports. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -ExternalModuleDependencies A list of external modules that this module is depends on. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FileList Specifies all items that are included in the module. This key is designed to act as a module inventory. The files listed in the key are included when the module is published, but any functions aren't automatically exported. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FormatsToProcess Specifies the formatting files (`.ps1xml`) that run when the module is imported. When you import a module, PowerShell runs the `Update-FormatData` cmdlet with the specified files. Because formatting files aren't scoped, they affect all session states in the session. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FunctionsToExport Specifies the functions that the module exports. Wildcards are permitted. You can use this parameter to restrict the functions that are exported by the module. It can remove functions from the list of exported aliases, but it can't add functions to the list. If you omit this parameter, `New-ModuleManifest` creates an **FunctionsToExport** key with a value of `*` (all), meaning that all functions defined in the module are exported by the manifest. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: * (all) Accept pipeline input: False Accept wildcard characters: True ``` ### -Guid Specifies a unique identifier for the module. The **GUID** can be used to distinguish among modules with the same name. If you omit this parameter, `New-ModuleManifest` creates a **GUID** key in the manifest and generates a **GUID** for the value. To create a new **GUID** in PowerShell, type `[guid]::NewGuid()`. ```yaml Type: System.Guid Parameter Sets: (All) Aliases: Required: False Position: Named Default value: A GUID generated for the module Accept pipeline input: False Accept wildcard characters: False ``` ### -HelpInfoUri Specifies the internet address of the HelpInfo XML file for the module. Enter a Uniform Resource Identifier (URI) that begins with **http** or **https**. The HelpInfo XML file supports the Updatable Help feature that was introduced in PowerShell 3.0. It contains information about the location of downloadable help files for the module and the version numbers of the newest help files for each supported locale. For information about Updatable Help, see [about_Updatable_Help](./About/about_Updatable_Help.md). For information about the HelpInfo XML file, see [Supporting Updatable Help](/powershell/scripting/developer/module/supporting-updatable-help). This parameter was introduced in PowerShell 3.0. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -IconUri Specifies the URL of an icon for the module. The specified icon is displayed on the gallery web page for the module. ```yaml Type: System.Uri Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LicenseUri Specifies the URL of licensing terms for the module. ```yaml Type: System.Uri Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ModuleList Lists all modules that are included in this module. Enter each module name as a string or as a hash table with **ModuleName** and **ModuleVersion** keys. The hash table can also have an optional **GUID** key. You can combine strings and hash tables in the parameter value. This key is designed to act as a module inventory. The modules that are listed in the value of this key aren't automatically processed. ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ModuleVersion Specifies the module's version. This parameter isn't required, but a **ModuleVersion** key is required in the manifest. If you omit this parameter, `New-ModuleManifest` creates a **ModuleVersion** key with a value of 1.0. ```yaml Type: System.Version Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 1.0 Accept pipeline input: False Accept wildcard characters: False ``` ### -NestedModules Specifies script modules (`.psm1`) and binary modules (`.dll`) that are imported into the module's session state. The files in the **NestedModules** key run in the order in which they're listed in the value. Enter each module name as a string or as a hash table with **ModuleName** and **ModuleVersion** keys. The hash table can also have an optional **GUID** key. You can combine strings and hash tables in the parameter value. Typically, nested modules contain commands that the root module needs for its internal processing. By default, the commands in nested modules are exported from the module's session state into the caller's session state, but the root module can restrict the commands that it exports. For example, by using an `Export-ModuleMember` command. Nested modules in the module session state are available to the root module, but they aren't returned by a `Get-Module` command in the caller's session state. Scripts (`.ps1`) that are listed in the **NestedModules** key are run in the module's session state, not in the caller's session state. To run a script in the caller's session state, list the script file name in the value of the **ScriptsToProcess** key in the manifest. ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Writes the resulting module manifest to the console and creates a `.psd1` file. By default, this cmdlet doesn't generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path and file name of the new module manifest. Enter a path and file name with a `.psd1` file name extension, such as `$PSHOME\Modules\MyModule\MyModule.psd1`. The **Path** parameter is required. If you specify the path to an existing file, `New-ModuleManifest` replaces the file without warning unless the file has the read-only attribute. The manifest should be located in the module's directory, and the manifest file name should be the same as the module directory name, but with a `.psd1` file name extension. > [!NOTE] > You cannot use variables, such as `$PSHOME` or `$HOME`, in response to a prompt for a **Path** > parameter value. To use a variable, include the **Path** parameter in the command. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PowerShellHostName Specifies the name of the PowerShell host program that the module requires. Enter the name of the host program, such as **Windows PowerShell ISE Host** or **ConsoleHost**. Wildcards aren't permitted. To find the name of a host program, in the program, type `$Host.Name`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PowerShellHostVersion Specifies the minimum version of the PowerShell host program that works with the module. Enter a version number, such as 1.1. ```yaml Type: System.Version Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PowerShellVersion Specifies the minimum version of PowerShell that works with this module. For example, you can enter 1.0, 2.0, or 3.0 as the parameter's value. It must be in an X.X format. For example, if you submit `5`, PowerShell will throw an error. ```yaml Type: System.Version Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Prerelease Prerelease string of this module. Adding a Prerelease string identifies the module as a prerelease version. When the module is published to the PowerShell Gallery, this data is used to identify prerelease packages. To acquire prerelease packages from the Gallery, you must use the **AllowPrerelease** parameter with the PowerShellGet commands `Find-Module`, `Install-Module`, `Update-Module`, and `Save-Module`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PrivateData Specifies data that is passed to the module when it's imported. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProcessorArchitecture Specifies the processor architecture that the module requires. Valid values are x86, AMD64, IA64, MSIL, and None (unknown or unspecified). ```yaml Type: System.Reflection.ProcessorArchitecture Parameter Sets: (All) Aliases: Accepted values: None, MSIL, X86, IA64, Amd64, Arm Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProjectUri Specifies the URL of a web page about this project. ```yaml Type: System.Uri Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ReleaseNotes Specifies release notes. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RequiredAssemblies Specifies the assembly (`.dll`) files that the module requires. Enter the assembly file names. PowerShell loads the specified assemblies before updating types or formats, importing nested modules, or importing the module file that is specified in the value of the **RootModule** key. Use this parameter to list all the assemblies that the module requires, including assemblies that must be loaded to update any formatting or type files that are listed in the **FormatsToProcess** or **TypesToProcess** keys, even if those assemblies are also listed as binary modules in the **NestedModules** key. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RequiredModules Specifies modules that must be in the global session state. If the required modules aren't in the global session state, PowerShell imports them. If the required modules aren't available, the `Import-Module` command fails. Enter each module name as a string or as a hash table with **ModuleName** and **ModuleVersion** keys. The hash table can also have an optional **GUID** key. You can combine strings and hash tables in the parameter value. In PowerShell 2.0, `Import-Module` doesn't import required modules automatically. It just verifies that the required modules are in the global session state. ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RequireLicenseAcceptance Flag to indicate whether the module requires explicit user acceptance for install, update, or save. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RootModule Specifies the primary or root file of the module. Enter the file name of a script (`.ps1`), a script module (`.psm1`), a module manifest(`.psd1`), an assembly (`.dll`), a cmdlet definition XML file (`.cdxml`), or a workflow (`.xaml`). When the module is imported, the members that are exported from the root module file are imported into the caller's session state. If a module has a manifest file and no root file was designated in the **RootModule** key, the manifest becomes the primary file for the module, and the module becomes a manifest module (ModuleType = Manifest). To export members from `.psm1` or `.dll` files in a module that has a manifest, the names of those files must be specified in the values of the **RootModule** or **NestedModules** keys in the manifest. Otherwise, their members aren't exported. > [!NOTE] > In PowerShell 2.0, this key was called **ModuleToProcess**. You can use the **RootModule** > parameter name or its **ModuleToProcess** alias. ```yaml Type: System.String Parameter Sets: (All) Aliases: ModuleToProcess Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ScriptsToProcess Specifies script (`.ps1`) files that run in the caller's session state when the module is imported. You can use these scripts to prepare an environment, just as you might use a login script. To specify scripts that run in the module's session state, use the **NestedModules** key. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Tags Specifies an array of tags. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TypesToProcess Specifies the type files (`.ps1xml`) that run when the module is imported. When you import the module, PowerShell runs the `Update-TypeData` cmdlet with the specified files. Because type files aren't scoped, they affect all session states in the session. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -VariablesToExport Specifies the variables that the module exports. Wildcards are permitted. You can use this parameter to restrict the variables that are exported by the module. It can remove variables from the list of exported variables, but it can't add variables to the list. If you omit this parameter, `New-ModuleManifest` creates a **VariablesToExport** key with a value of `*` (all), meaning that all variables defined in the module are exported by the manifest. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: * (all) Accept pipeline input: False Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if `New-ModuleManifest` runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.String When you use the **PassThru** parameter, this cmdlet returns a string representing the module manifest. ## NOTES `New-ModuleManifest` running on Windows and non-Windows platforms creates module manifest (`.psd1`) files encoded as **UTF8NoBOM**. Module manifests are usually optional. However, a module manifest is required to export an assembly that is installed in the global assembly cache. To add or change files in the `$PSHOME\Modules` directory, start PowerShell with the **Run as administrator** option. > [!NOTE] > Beginning in PowerShell 6.2, PowerShell attempts to load all the DLL files listed in **FileList** > property of the module manifest. Native DLLs is in the **FileList** fail to load in the process > and the error is ignored. All managed DLLs are loaded in the process. This behavior was removed in > PowerShell 7.1. In PowerShell 2.0, many parameters of `New-ModuleManifest` were mandatory, even though they weren't required in a module manifest. Beginning in PowerShell 3.0, only the **Path** parameter is mandatory. A session is an instance of the PowerShell execution environment. A session can have one or more session states. By default, a session has only a global session state, but each imported module has its own session state. Session states allow the commands in a module to run without affecting the global session state. The caller's session state is the session state into which a module is imported. Typically, it refers to the global session state, but when a module imports nested modules, the caller is the module and the caller's session state is the module's session state. ## RELATED LINKS [Export-ModuleMember](Export-ModuleMember.md) [Get-Module](Get-Module.md) [Import-Module](Import-Module.md) [New-Module](New-Module.md) [Remove-Module](Remove-Module.md) [Test-ModuleManifest](Test-ModuleManifest.md) [about_Modules](./About/about_Modules.md)

#File: reference/7.6/Microsoft.PowerShell.Core/New-PSRoleCapabilityFile.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 03/21/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/new-psrolecapabilityfile?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-PSRoleCapabilityFile --- # New-PSRoleCapabilityFile ## SYNOPSIS Creates a file that defines a set of capabilities to be exposed through a session configuration. ## SYNTAX ``` New-PSRoleCapabilityFile [-Path] <String> [-Guid <Guid>] [-Author <String>] [-Description <String>] [-CompanyName <String>] [-Copyright <String>] [-ModulesToImport <Object[]>] [-VisibleAliases <String[]>] [-VisibleCmdlets <Object[]>] [-VisibleFunctions <Object[]>] [-VisibleExternalCommands <String[]>] [-VisibleProviders <String[]>] [-ScriptsToProcess <String[]>] [-AliasDefinitions <IDictionary[]>] [-FunctionDefinitions <IDictionary[]>] [-VariableDefinitions <Object>] [-EnvironmentVariables <IDictionary>] [-TypesToProcess <String[]>] [-FormatsToProcess <String[]>] [-AssembliesToLoad <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `New-PSRoleCapabilityFile` cmdlet creates a file that defines a set of user capabilities that can be exposed through session configuration files. This includes determining which cmdlets, functions, and scripts are available to users. The capability file is a human-readable text file that contains a hash table of session configuration properties and values. The file has a `.psrc` file name extension, and can be used by more than one session configuration. All the parameters of `New-PSRoleCapabilityFile` are optional except for the **Path** parameter, which specifies the path for the file. If you don't include a parameter when you run the cmdlet, the corresponding key in the session configuration file is commented-out, except where noted in the parameter description. For example, if you don't include the **AssembliesToLoad** parameter then that section of the session configuration file is commented out. To use the role capability file in a session configuration, first place the file in a **RoleCapabilities** subfolder of a valid PowerShell module folder. Then reference the file by name in the **RoleDefinitions** field in a PowerShell Session Configuration (.pssc) file. This cmdlet was introduced in Windows PowerShell 5.0. ## EXAMPLES ### Example 1: Create a blank role capability file This example creates a new role capability file that uses the default (blank) values. The file can later be edited in a text editor to change these configuration settings. ```powershell New-PSRoleCapabilityFile -Path ".\ExampleFile.psrc" ``` ### Example 2: Create a role capability file allowing users to restart services and any VDI computer This example creates a sample role capability file that enables users to restart services and computers that match a specific name pattern. Name filtering is defined by setting the **ValidatePattern** parameter to the regular expression `VDI\d+`. ```powershell $roleParameters = @{ Path = ".\Maintenance.psrc" Author = "User01" CompanyName = "Fabrikam Corporation" Description = "This role enables users to restart any service and restart any VDI computer." ModulesToImport = "Microsoft.PowerShell.Core" VisibleCmdlets = "Restart-Service", @{ Name = "Restart-Computer" Parameters = @{ Name = "ComputerName"; ValidatePattern = "VDI\d+" } } } New-PSRoleCapabilityFile @roleParameters ``` ## PARAMETERS ### -AliasDefinitions Adds the specified aliases to sessions that use the role capability file. Enter a hash table with the following keys: - Name. Name of the alias. This key is required. - Value. The command that the alias represents. This key is required. - Description. A text string that describes the alias. This key is optional. - Options. Alias options. This key is optional. The default value is None. The acceptable values for this parameter are: None, ReadOnly, Constant, Private, or AllScope. For example: `@{Name="hlp";Value="Get-Help";Description="Gets help";Options="ReadOnly"}` ```yaml Type: System.Collections.IDictionary[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -AssembliesToLoad Specifies the assemblies to load into the sessions that use the role capability file. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Author Specifies the user that created the role capability file. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CompanyName Identifies the company that created the role capability file. The default value is Unknown. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Copyright Specifies a copyright for the role capability file. If you omit this parameter, `New-PSRoleCapabilityFile` generates a copyright statement using the value of the **Author** parameter. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Description Specifies a description for the role capability file. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -EnvironmentVariables Specifies the environment variables for sessions that expose this role capability file. Enter a hash table in which the keys are the environment variable names and the values are the environment variable values. For example: `EnvironmentVariables=@{TestShare="\\\\Server01\TestShare"}` ```yaml Type: System.Collections.IDictionary Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FormatsToProcess Specifies the formatting files (`.ps1xml`) that run in sessions that use the role capability file. The value of this parameter must be a full or absolute path of the formatting files. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FunctionDefinitions Adds the specified functions to sessions that expose the role capability. Enter a hash table with the following keys: - Name. Name of the function. This key is required. - ScriptBlock. Function body. Enter a script block. This key is required. - Options. Function options. This key is optional. The default value is None. The acceptable values for this parameter are: are None, ReadOnly, Constant, Private, or AllScope. For example: `@{Name="Get-PowerShellProcess";ScriptBlock={Get-Process powershell};Options="AllScope"}` ```yaml Type: System.Collections.IDictionary[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Guid Specifies a unique identifier for the role capability file. If you omit this parameter, `New-PSRoleCapabilityFile` generates a GUID for the file. To create a new GUID in PowerShell, type `[guid]::NewGuid()`. ```yaml Type: System.Guid Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ModulesToImport Specifies the modules that are automatically imported into sessions that use the role capability file. By default, all the commands in listed modules are visible. When used with **VisibleCmdlets** or **VisibleFunctions**, the commands visible from the specified modules can be restricted. Each module used in the value of this parameter can be represented by a string or by a hash table. A module string consists only of the name of the module. A module hash table can include **ModuleName**, **ModuleVersion**, and **GUID** keys. Only the **ModuleName** key is required. For example, the following value consists of a string and a hash table. Any combination of strings and hash tables, in any order, is valid. `"TroubleshootingPack", @{ModuleName="PSDiagnostics"; ModuleVersion="1.0.0.0";GUID="c61d6278-02a3-4618-ae37-a524d40a7f44"}` ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path and filename of the role capability file. The file must have a `.psrc` filename extension. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ScriptsToProcess Specifies scripts to add to sessions that use the role capability file. Enter the path and file names of the scripts. The value of this parameter must be a full or absolute path of the script file names. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TypesToProcess Specifies type files (`.ps1xml`) to add to sessions that use the role capability file. Enter the type filenames. The value of this parameter must be a full or absolute path of the type filenames. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -VariableDefinitions Specifies variables to add to sessions that use the role capability file. Enter a hash table with the following keys: - Name. Name of the variable. This key is required. - Value. Variable value. This key is required. For example: `@{Name="WarningPreference";Value="SilentlyContinue"}` ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -VisibleAliases Limits the aliases in the session to those aliases specified in the value of this parameter, plus any aliases that you define in the **AliasDefinition** parameter. Wildcard characters are supported. By default, all aliases that are defined by the PowerShell engine and all aliases that modules export are visible in the session. For example, to limit the available aliases to gm and gcm use this syntax: `VisibleAliases="gcm", "gp"` When any **Visible** parameter is included in the role capability file, PowerShell removes the `Import-Module` cmdlet and its `ipmo` alias from the session. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -VisibleCmdlets Limits the cmdlets in the session to those specified in the value of this parameter. Wildcard characters and Module Qualified Names are supported. By default, all cmdlets that the modules in the session export are visible in the session. Use the **SessionType** and **ModulesToImport** parameters to determine which modules and snap-ins are imported into the session. If no modules in **ModulesToImport** expose the cmdlet, `New-PSRoleCapabilityFile` tries to load the appropriate module. When any **Visible** parameter is included in the session configuration file, PowerShell removes the `Import-Module` cmdlet and its `ipmo` alias from the session. ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -VisibleExternalCommands Limits the external binaries, scripts and commands that can be executed in the session to those specified in the value of this parameter. By default, no external commands are visible in this session. When any **Visible** parameter is included in the session configuration file, PowerShell removes the `Import-Module` cmdlet and its `ipmo` alias from the session. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -VisibleFunctions Limits the functions in the session to those specified in the value of this parameter, plus any functions that you define in the **FunctionDefinitions** parameter. Wildcard characters are supported. By default, all functions exported by modules in the session are visible in that session. Use the **SessionType** and **ModulesToImport** parameters to determine which modules are imported into the session. When any **Visible** parameter is included in the session configuration file, PowerShell removes the `Import-Module` cmdlet and its `ipmo` alias from the session. ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -VisibleProviders Limits the PowerShell providers in the session to those specified in the value of this parameter. Wildcard characters are supported. By default, all providers exported by a module in the session are visible in the session. Use the **SessionType** and **ModulesToImport** parameters to determine which modules are imported into the session. When any **Visible** parameter is included in the session configuration file, PowerShell removes the `Import-Module` cmdlet and its `ipmo` alias from the session. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ## NOTES ## RELATED LINKS [New-PSSessionConfigurationFile](New-PSSessionConfigurationFile.md) [Get-PSSessionCapability](Get-PSSessionCapability.md)

#File: reference/7.6/Microsoft.PowerShell.Core/New-PSSession.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/new-pssession?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-PSSession --- # New-PSSession ## SYNOPSIS Creates a persistent connection to a local or remote computer. ## SYNTAX ### ComputerName (Default) ``` New-PSSession [[-ComputerName] <String[]>] [-Credential <PSCredential>] [-Name <String[]>] [-EnableNetworkAccess] [-ConfigurationName <String>] [-Port <Int32>] [-UseSSL] [-ApplicationName <String>] [-ThrottleLimit <Int32>] [-SessionOption <PSSessionOption>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ### Uri ``` New-PSSession [-Credential <PSCredential>] [-Name <String[]>] [-EnableNetworkAccess] [-ConfigurationName <String>] [-ThrottleLimit <Int32>] [-ConnectionUri] <Uri[]> [-AllowRedirection] [-SessionOption <PSSessionOption>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ### VMId ``` New-PSSession -Credential <PSCredential> [-Name <String[]>] [-ConfigurationName <String>] [-VMId] <Guid[]> [-ThrottleLimit <Int32>] [<CommonParameters>] ``` ### VMName ``` New-PSSession -Credential <PSCredential> [-Name <String[]>] [-ConfigurationName <String>] -VMName <String[]> [-ThrottleLimit <Int32>] [<CommonParameters>] ``` ### Session ``` New-PSSession [[-Session] <PSSession[]>] [-Name <String[]>] [-EnableNetworkAccess] [-ThrottleLimit <Int32>] [<CommonParameters>] ``` ### ContainerId ``` New-PSSession [-Name <String[]>] [-ConfigurationName <String>] -ContainerId <String[]> [-RunAsAdministrator] [-ThrottleLimit <Int32>] [<CommonParameters>] ``` ### UseWindowsPowerShellParameterSet ``` New-PSSession [-Name <String[]>] [-UseWindowsPowerShell] [<CommonParameters>] ``` ### SSHHost ``` New-PSSession [-Name <String[]>] [-Port <Int32>] [-HostName] <String[]> [-UserName <String>] [-KeyFilePath <String>] [-Subsystem <String>] [-ConnectingTimeout <Int32>] [-SSHTransport] [-Options <Hashtable>] [<CommonParameters>] ``` ### SSHHostHashParam ``` New-PSSession [-Name <String[]>] -SSHConnection <Hashtable[]> [<CommonParameters>] ``` ## DESCRIPTION The `New-PSSession` cmdlet creates a PowerShell session (**PSSession**) on a local or remote computer. When you create a **PSSession**, PowerShell establishes a persistent connection to the remote computer. Use a **PSSession** to run multiple commands that share data, such as a function or the value of a variable. To run commands in a **PSSession**, use the `Invoke-Command` cmdlet. To use the **PSSession** to interact directly with a remote computer, use the `Enter-PSSession` cmdlet. For more information, see [about_PSSessions](about/about_PSSessions.md). You can run commands on a remote computer without creating a **PSSession** with the **ComputerName** parameters of `Enter-PSSession` or `Invoke-Command`. When you use the **ComputerName** parameter, PowerShell creates a temporary connection that is used for the command and is then closed. Starting with PowerShell 6.0 you can use Secure Shell (SSH) to establish a connection to and create a session on a remote computer, if SSH is available on the local computer and the remote computer is configured with a PowerShell SSH endpoint. The benefit of an SSH based PowerShell remote session is that it can work across multiple platforms (Windows, Linux, macOS). For SSH based sessions you use the **HostName** or **SSHConnection** parameter set to specify the remote computer and relevant connection information. For more information about how to set up PowerShell SSH remoting, see [PowerShell Remoting Over SSH](/powershell/scripting/learn/remoting/ssh-remoting-in-powershell-core). > [!NOTE] > When using WSMan remoting from a Linux or macOS client with a HTTPS endpoint where the server > certificate is not trusted (e.g., a self-signed certificate). You must provide a > **PSSessionOption** that includes the **SkipCACheck** and **SkipCNCheck** values set to `$true` to > successfully establish the connection. Only do this if you are in an environment where you can be > certain of the server certificate and the network connection to the target system. ## EXAMPLES ### Example 1: Create a session on the local computer ```powershell $s = New-PSSession ``` This command creates a new **PSSession** on the local computer and saves the **PSSession** in the `$s` variable. You can now use this **PSSession** to run commands on the local computer. ### Example 2: Create a session on a remote computer ```powershell $Server01 = New-PSSession -ComputerName Server01 ``` This command creates a new **PSSession** on the Server01 computer and saves it in the `$Server01` variable. When creating multiple **PSSession** objects, assign them to variables with useful names. This will help you manage the **PSSession** objects in subsequent commands. ### Example 3: Create sessions on multiple computers ```powershell $s1, $s2, $s3 = New-PSSession -ComputerName Server01,Server02,Server03 ``` This command creates three **PSSession** objects, one on each of the computers specified by the **ComputerName** parameter. The command uses the assignment operator (`=`) to assign the new **PSSession** objects to variables: `$s1`, `$s2`, `$s3`. It assigns the Server01 **PSSession** to `$s1`, the Server02 **PSSession** to `$s2`, and the Server03 **PSSession** to `$s3`. When you assign multiple objects to a series of variables, PowerShell assigns each object to a variable in the series respectively. If there are more objects than variables, all remaining objects are assigned to the last variable. If there are more variables than objects, the remaining variables are empty (`$null`). ### Example 4: Create a session with a specified port ```powershell New-PSSession -ComputerName Server01 -Port 8081 -UseSSL -ConfigurationName E12 ``` This command creates a new **PSSession** on the Server01 computer that connects to server port `8081` and uses the SSL protocol. The new **PSSession** uses an alternative session configuration called `E12`. Before setting the port, you must configure the WinRM listener on the remote computer to listen on port 8081. For more information, see the description of the **Port** parameter. ### Example 5: Create a session based on an existing session ```powershell New-PSSession -Session $s -Credential Domain01\User01 ``` This command creates a **PSSession** with the same properties as an existing **PSSession**. You can use this command format when the resources of an existing **PSSession** are exhausted and a new **PSSession** is needed to offload some of the demand. The command uses the **Session** parameter of `New-PSSession` to specify the **PSSession** saved in the `$s` variable. It uses the credentials of the `Domain1\Admin01` user to complete the command. ### Example 6: Create a session with a global scope in a different domain ```powershell $Global:s = New-PSSession -ComputerName Server1.Domain44.Corpnet.Fabrikam.com -Credential Domain01\Admin01 ``` This example shows how to create a **PSSession** with a global scope on a computer in a different domain. By default, **PSSession** objects created at the command line are created with local scope and **PSSession** objects created in a script have script scope. To create a **PSSession** with global scope, create a new **PSSession** and then store the **PSSession** in a variable that is cast to a global scope. In this case, the `$s` variable is cast to a global scope. The command uses the **ComputerName** parameter to specify the remote computer. Because the computer is in a different domain than the user account, the full name of the computer is specified together with the credentials of the user. ### Example 7: Create sessions for many computers ```powershell $rs = Get-Content C:\Test\Servers.txt | New-PSSession -ThrottleLimit 50 ``` This command creates a **PSSession** on each of the 200 computers listed in the `Servers.txt` file and it stores the resulting **PSSession** in the `$rs` variable. The **PSSession** objects have a throttle limit of `50`. You can use this command format when the names of computers are stored in a database, spreadsheet, text file, or other text-convertible format. ### Example 8: Create a session by using a URI ```powershell $s = New-PSSession -Uri http://Server01:91/NewSession -Credential Domain01\User01 ``` This command creates a **PSSession** on the Server01 computer and stores it in the `$s` variable. It uses the **URI** parameter to specify the transport protocol, the remote computer, the port, and an alternate session configuration. It also uses the **Credential** parameter to specify a user account that has permission to create a session on the remote computer. ### Example 9: Run a background job in a set of sessions ```powershell $s = New-PSSession -ComputerName (Get-Content Servers.txt) -Credential Domain01\Admin01 -ThrottleLimit 16 Invoke-Command -Session $s -ScriptBlock {Get-Process powershell} -AsJob ``` These commands create a set of **PSSession** objects and then run a background job in each of the **PSSession** objects. The first command creates a new **PSSession** on each of the computers listed in the `Servers.txt` file. It uses the `New-PSSession` cmdlet to create the **PSSession**. The value of the **ComputerName** parameter is a command that uses the `Get-Content` cmdlet to get the list of computer names the `Servers.txt` file. The command uses the **Credential** parameter to create the **PSSession** objects that have the permission of a domain administrator, and it uses the **ThrottleLimit** parameter to limit the command to `16` concurrent connections. The command saves the **PSSession** objects in the `$s` variable. The second command uses the **AsJob** parameter of the `Invoke-Command` cmdlet to start a background job that runs a `Get-Process powershell` command in each of the **PSSession** objects in `$s`. For more information about PowerShell background jobs, see [about_Jobs](About/about_Jobs.md) and [about_Remote_Jobs](About/about_Remote_Jobs.md). ### Example 10: Create a session for a computer by using its URI ```powershell New-PSSession -ConnectionURI https://management.exchangelabs.com/Management ``` This command creates a **PSSession** objects that connects to a computer that is specified by a URI instead of a computer name. ### Example 11: Create a session option ```powershell $so = New-PSSessionOption -SkipCACheck New-PSSession -ConnectionUri https://management.exchangelabs.com/Management -SessionOption $so -Credential Server01\Admin01 ``` This example shows how to create a session option object and use the **SessionOption** parameter. The first command uses the `New-PSSessionOption` cmdlet to create a session option. It saves the resulting **SessionOption** object in the `$so` variable. The second command uses the option in a new session. The command uses the `New-PSSession` cmdlet to create a new session. The value of the **SessionOption** parameter is the **SessionOption** object in the `$so` variable. ### Example 12: Create a session using SSH ```powershell New-PSSession -HostName UserA@LinuxServer01 ``` This example shows how to create a new **PSSession** using Secure Shell (SSH). If SSH is configured on the remote computer to prompt for passwords then you will get a password prompt. Otherwise you will have to use SSH key based user authentication. ### Example 13: Create a session using SSH and specify the port and user authentication key ```powershell New-PSSession -HostName UserA@LinuxServer01:22 -KeyFilePath C:\<path>\userAKey_rsa ``` This example shows how to create a **PSSession** using Secure Shell (SSH). It uses the **Port** parameter to specify the port to use and the **KeyFilePath** parameter to specify an RSA key used to identify and authenticate the user on the remote computer. ### Example 14: Create multiple sessions using SSH ```powershell $sshConnections = @( @{ HostName = 'WinServer1' UserName = 'domain\userA' KeyFilePath = 'C:\Users\UserA\id_rsa' } @{ HostName = 'UserB@LinuxServer5' KeyFilePath = 'C:\UserB\<path>\id_rsa' } ) New-PSSession -SSHConnection $sshConnections ``` This example shows how to create multiple sessions using Secure Shell (SSH) and the **SSHConnection** parameter set. The **SSHConnection** parameter takes an array of hash tables that contain connection information for each session. Note that this example requires that the target remote computers have SSH configured to support key-based user authentication. ### Example 15: Create a new session using SSH options ```powershell $options = @{ Port=22 User = 'UserB' Host = 'LinuxServer5' } New-PSSession -KeyFilePath '/Users/UserB/id_rsa' -Options $options ``` This example shows how to create a new SSH-based session a remote Linux-based machine using SSH options. The **Options** parameter takes a hashtable of values that are passed as options to the underlying `ssh` command the established the connection to the remote system. ## PARAMETERS ### -AllowRedirection Indicates that this cmdlet allows redirection of this connection to an alternate Uniform Resource Identifier (URI). When you use the **ConnectionURI** parameter, the remote destination can return an instruction to redirect to a different URI. By default, PowerShell does not redirect connections, but you can use this parameter to enable it to redirect the connection. You can also limit the number of times the connection is redirected by changing the **MaximumConnectionRedirectionCount** session option value. Use the **MaximumRedirection** parameter of the `New-PSSessionOption` cmdlet or set the **MaximumConnectionRedirectionCount** property of the **$PSSessionOption** preference variable. The default value is `5`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Uri Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ApplicationName Specifies the application name segment of the connection URI. Use this parameter to specify the application name when you are not using the **ConnectionURI** parameter in the command. The default value is the value of the `$PSSessionApplicationName` preference variable on the local computer. If this preference variable is not defined, the default value is `WSMAN`. This value is appropriate for most uses. For more information, see [about_Preference_Variables](About/about_Preference_Variables.md). The WinRM service uses the application name to select a listener to service the connection request. The value of this parameter should match the value of the **URLPrefix** property of a listener on the remote computer. ```yaml Type: System.String Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Authentication Specifies the mechanism that is used to authenticate the user's credentials. The acceptable values for this parameter are: - `Default` - `Basic` - `Credssp` - `Digest` - `Kerberos` - `Negotiate` - `NegotiateWithImplicitCredential` The default value is `Default`. For more information about the values of this parameter, see [AuthenticationMechanism Enumeration](/dotnet/api/system.management.automation.runspaces.authenticationmechanism). > [!CAUTION] > Credential Security Support Provider (CredSSP) authentication, in which the user credentials are > passed to a remote computer to be authenticated, is designed for commands that require > authentication on more than one resource, such as accessing a remote network share. This mechanism > increases the security risk of the remote operation. If the remote computer is compromised, the > credentials that are passed to it can be used to control the network session. ```yaml Type: System.Management.Automation.Runspaces.AuthenticationMechanism Parameter Sets: ComputerName, Uri Aliases: Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential, Credssp, Digest, Kerberos Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to perform this action. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they do not work with domain accounts. To get a certificate, use the `Get-Item` or `Get-ChildItem` command in the PowerShell `Cert:` drive. ```yaml Type: System.String Parameter Sets: ComputerName, Uri Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies an array of names of computers. This cmdlet creates a persistent connection (**PSSession**) to the specified computer. If you enter multiple computer names, `New-PSSession` creates multiple **PSSession** objects, one for each computer. The default is the local computer. Type the NetBIOS name, an IP address, or a fully qualified domain name of one or more remote computers. To specify the local computer, type the computer name, `localhost`, or a dot (`.`). When the computer is in a different domain than the user, the fully qualified domain name is required. You can also pipe a computer name, in quotation marks, to `New-PSSession`. To use an IP address in the value of the **ComputerName** parameter, the command must include the **Credential** parameter. Also, the computer must be configured for HTTPS transport or the IP address of the remote computer must be included in the WinRM TrustedHosts list on the local computer. For instructions for adding a computer name to the TrustedHosts list, see "How to Add a Computer to the Trusted Host List" in [about_Remote_Troubleshooting](about/about_Remote_Troubleshooting.md). To include the local computer in the value of the **ComputerName** parameter, start Windows PowerShell by using the **Run as administrator option**. ```yaml Type: System.String[] Parameter Sets: ComputerName Aliases: Cn Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -ConfigurationName Specifies the session configuration that is used for the new **PSSession**. Enter a configuration name or the fully qualified resource URI for a session configuration. If you specify only the configuration name, the following schema URI is prepended: `http://schemas.microsoft.com/PowerShell`. The session configuration for a session is located on the remote computer. If the specified session configuration does not exist on the remote computer, the command fails. The default value is the value of the `$PSSessionConfigurationName` preference variable on the local computer. If this preference variable is not set, the default is `Microsoft.PowerShell`. For more information, see [about_Preference_Variables](About/about_Preference_Variables.md). ```yaml Type: System.String Parameter Sets: ComputerName, Uri, VMId, VMName, ContainerId Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ConnectingTimeout Specifies the amount of time in milliseconds allowed for the initial SSH connection to complete. If the connection doesn't complete within the specified time, an error is returned. This parameter was introduced in PowerShell 7.2 ```yaml Type: System.Int32 Parameter Sets: SSHHost Aliases: Required: False Position: Named Default value: unlimited Accept pipeline input: False Accept wildcard characters: False ``` ### -ConnectionUri Specifies a URI that defines the connection endpoint for the session. The URI must be fully qualified. The format of this string is as follows: `<Transport>://<ComputerName>:<Port>/<ApplicationName>` The default value is as follows: `http://localhost:5985/WSMAN` If you do not specify a **ConnectionURI**, you can use the **UseSSL**, **ComputerName**, **Port**, and **ApplicationName** parameters to specify the **ConnectionURI** values. Valid values for the Transport segment of the URI are HTTP and HTTPS. If you specify a connection URI with a Transport segment, but do not specify a port, the session is created with standards ports: `80` for HTTP and `443` for HTTPS. To use the default ports for PowerShell remoting, specify port `5985` for HTTP or `5986` for HTTPS. If the destination computer redirects the connection to a different URI, PowerShell prevents the redirection unless you use the **AllowRedirection** parameter in the command. ```yaml Type: System.Uri[] Parameter Sets: Uri Aliases: URI, CU Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ContainerId Specifies an array of IDs of containers. This cmdlet starts an interactive session with each of the specified containers. Use the `docker ps` command to get a list of container IDs. For more information, see the help for the [docker ps](https://docs.docker.com/engine/reference/commandline/ps/) command. ```yaml Type: System.String[] Parameter Sets: ContainerId Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to do this action. The default is the current user. Type a user name, such as `User01` or `Domain01\User01`, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. If you type a user name, you're prompted to enter the password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: ComputerName, Uri, VMId, VMName Aliases: Required: True (VMId, VMName), False (ComputerName, Uri) Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -EnableNetworkAccess Indicates that this cmdlet adds an interactive security token to loopback sessions. The interactive token lets you run commands in the loopback session that get data from other computers. For example, you can run a command in the session that copies XML files from a remote computer to the local computer. A loopback session is a **PSSession** that originates and ends on the same computer. To create a loopback session, omit the **ComputerName** parameter or set its value to dot (`.`), `localhost`, or the name of the local computer. By default, this cmdlet creates loopback sessions by using a network token, which might not provide sufficient permission to authenticate to remote computers. The **EnableNetworkAccess** parameter is effective only in loopback sessions. If you use **EnableNetworkAccess** when you create a session on a remote computer, the command succeeds, but the parameter is ignored. You can also enable remote access in a loopback session by using the `CredSSP` value of the **Authentication** parameter, which delegates the session credentials to other computers. To protect the computer from malicious access, disconnected loopback sessions that have interactive tokens, which are those created by using the **EnableNetworkAccess** parameter, can be reconnected only from the computer on which the session was created. Disconnected sessions that use CredSSP authentication can be reconnected from other computers. For more information, see `Disconnect-PSSession`. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerName, Uri, Session Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -HostName Specifies an array of computer names for a Secure Shell (SSH) based connection. This is similar to the **ComputerName** parameter except that the connection to the remote computer is made using SSH rather than Windows WinRM. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.String[] Parameter Sets: SSHHost Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -KeyFilePath Specifies a key file path used by Secure Shell (SSH) to authenticate a user on a remote computer. SSH allows user authentication to be performed via private/public keys as an alternative to basic password authentication. If the remote computer is configured for key authentication then this parameter can be used to provide the key that identifies the user. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.String Parameter Sets: SSHHost Aliases: IdentityFilePath Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies a friendly name for the **PSSession**. You can use the name to refer to the **PSSession** when you use other cmdlets, such as `Get-PSSession` and `Enter-PSSession`. The name is not required to be unique to the computer or the current session. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Options Specifies a hashtable of SSH options used when connecting to a remote SSH-based session. The possible options are any values supported by the Unix-based version of the [ssh](https://man.openbsd.org/ssh#o) command. Any values explicitly passed by parameters take precedence over values passed in the **Options** hashtable. For example, using the **Port** parameter overrides any `Port` key-value pair passed in the **Options** hashtable. ```yaml Type: System.Collections.Hashtable Parameter Sets: SSHHost Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Port Specifies the network port on the remote computer that is used for this connection. To connect to a remote computer, the remote computer must be listening on the port that the connection uses. The default ports are `5985`, which is the WinRM port for HTTP, and `5986`, which is the WinRM port for HTTPS. Before using another port, you must configure the WinRM listener on the remote computer to listen at that port. Use the following commands to configure the listener: 1. `winrm delete winrm/config/listener?Address=*+Transport=HTTP` 2. `winrm create winrm/config/listener?Address=*+Transport=HTTP @{Port="\<port-number\>"}` Do not use the **Port** parameter unless you must. The port setting in the command applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on all computers. ```yaml Type: System.Int32 Parameter Sets: ComputerName, SSHHost Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RunAsAdministrator Indicates that the **PSSession** runs as administrator. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ContainerId Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Session Specifies an array of **PSSession** objects that this cmdlet uses as a model for the new **PSSession**. This parameter creates new **PSSession** objects that have the same properties as the specified **PSSession** objects. Enter a variable that contains the **PSSession** objects or a command that creates or gets the **PSSession** objects, such as a `New-PSSession` or `Get-PSSession` command. The resulting **PSSession** objects have the same computer name, application name, connection URI, port, configuration name, throttle limit, and Secure Sockets Layer (SSL) value as the originals, but they have a different display name, ID, and instance ID (GUID). ```yaml Type: System.Management.Automation.Runspaces.PSSession[] Parameter Sets: Session Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -SessionOption Specifies advanced options for the session. Enter a **SessionOption** object, such as one that you create by using the `New-PSSessionOption` cmdlet, or a hash table in which the keys are session option names and the values are session option values. The default values for the options are determined by the value of the `$PSSessionOption` preference variable, if it is set. Otherwise, the default values are established by options set in the session configuration. The session option values take precedence over default values for sessions set in the `$PSSessionOption` preference variable and in the session configuration. However, they do not take precedence over maximum values, quotas or limits set in the session configuration. For a description of the session options that includes the default values, see `New-PSSessionOption`. For information about the `$PSSessionOption` preference variable, see [about_Preference_Variables](About/about_Preference_Variables.md). For more information about session configurations, see [about_Session_Configurations](About/about_Session_Configurations.md). ```yaml Type: System.Management.Automation.Remoting.PSSessionOption Parameter Sets: ComputerName, Uri Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SSHConnection This parameter takes an array of hashtables where each hashtable contains one or more connection parameters needed to establish a Secure Shell (SSH) connection (**HostName**, **Port**, **UserName**, **KeyFilePath**). The hashtable connection parameters are the same as defined for the **SSHHost** parameter set. The **SSHConnection** parameter is useful for creating multiple sessions where each session requires different connection information. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Collections.Hashtable[] Parameter Sets: SSHHostHashParam Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SSHTransport Indicates that the remote connection is established using Secure Shell (SSH). By default PowerShell uses Windows WinRM to connect to a remote computer. This switch forces PowerShell to use the HostName parameter set for establishing an SSH based remote connection. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: SSHHost Aliases: Accepted values: true Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Subsystem Specifies the SSH subsystem used for the new **PSSession**. This specifies the subsystem to use on the target as defined in `sshd_config`. The subsystem starts a specific version of PowerShell with predefined parameters. If the specified subsystem does not exist on the remote computer, the command fails. If this parameter is not used, the default is the `powershell` subsystem. ```yaml Type: System.String Parameter Sets: SSHHost Aliases: Required: False Position: Named Default value: powershell Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ThrottleLimit Specifies the maximum number of concurrent connections that can be established to run this command. If you omit this parameter or enter a value of `0` (zero), the default value, `32`, is used. The throttle limit applies only to the current command, not to the session or to the computer. ```yaml Type: System.Int32 Parameter Sets: ComputerName, Uri, VMId, VMName, Session, ContainerId Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UserName Specifies the username for the account used to create a session on the remote computer. The user authentication method depends on how Secure Shell (SSH) is configured on the remote computer. If SSH is configured for basic password authentication then you'll be prompted for the user password. If SSH is configured for key-based user authentication then a key file path can be provided via the **KeyFilePath** parameter and you won't be prompted for a password. Note that if the client user key file is located in an SSH known location then the **KeyFilePath** parameter is not needed for key-based authentication, and user authentication occurs automatically based on the username. See SSH documentation about key-based user authentication for more information. This is not a required parameter. If no **UserName** parameter is specified then the current log on username is used for the connection. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.String Parameter Sets: SSHHost Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL Indicates that this cmdlet uses the SSL protocol to establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all PowerShell content transmitted over the network. The **UseSSL** parameter offers an additional protection that sends the data across an HTTPS connection instead of an HTTP connection. If you use this parameter, but SSL is not available on the port that is used for the command, the command fails. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -UseWindowsPowerShell Creates a remote connection to a new Windows PowerShell runspace on the local system. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: UseWindowsPowerShellParameterSet Aliases: Required: True Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -VMId Specifies an array of virtual machine IDs. This cmdlet starts a PowerShell Direct interactive session with each of the specified virtual machines. For more information, see [Virtual Machine automation and management using PowerShell](/virtualization/hyper-v-on-windows/user-guide/powershell-direct). Use `Get-VM` to see the virtual machines that are available on your Hyper-V host. ```yaml Type: System.Guid[] Parameter Sets: VMId Aliases: VMGuid Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -VMName Specifies an array of names of virtual machines. This cmdlet starts a PowerShell Direct interactive session with each of the specified virtual machines. For more information, see [Virtual Machine automation and management using PowerShell](/virtualization/hyper-v-on-windows/user-guide/powershell-direct). Use `Get-VM` to see the virtual machines that are available on your Hyper-V host. ```yaml Type: System.String[] Parameter Sets: VMName Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string to this cmdlet. ### System.URI You can pipe a URI to this cmdlet. ### System.Management.Automation.Runspaces.PSSession You can pipe a session object to this cmdlet. ## OUTPUTS ### System.Management.Automation.Runspaces.PSSession ## NOTES PowerShell includes the following aliases for `New-PSSession`: - All platforms: - `nsn` - This cmdlet uses the PowerShell remoting infrastructure. To use this cmdlet, the local computer and any remote computers must be configured for PowerShell remoting. For more information, see [about_Remote_Requirements](About/about_Remote_Requirements.md). - To create a **PSSession** on the local computer, start PowerShell with the **Run as administrator** option. - When you are finished with the **PSSession**, use the `Remove-PSSession` cmdlet to delete the **PSSession** and release its resources. - The **HostName** and **SSHConnection** parameter sets were included starting with PowerShell 6.0. They were added to provide PowerShell remoting based on Secure Shell (SSH). Both SSH and PowerShell are supported on multiple platforms (Windows, Linux, macOS) and PowerShell remoting will work over these platforms where PowerShell and SSH are installed and configured. This is separate from the previous Windows-only remoting that is based on WinRM and many of the WinRM specific features and limitations do not apply. For example, WinRM-based quotas, session options, custom endpoint configuration, and disconnect/reconnect features are not supported. For more information about how to set up PowerShell SSH remoting, see [PowerShell Remoting Over SSH](/powershell/scripting/learn/remoting/ssh-remoting-in-powershell-core). The `ssh` executable obtains configuration data from the following sources in the following order: 1. command-line options 1. user's configuration file (~/.ssh/config) 1. system-wide configuration file (/etc/ssh/ssh_config) The following cmdlet parameters get mapped into `ssh` parameters and options: | Cmdlet parameter | ssh parameter | equivalent ssh -o option | | -------------------------- | ------------------------------- | ------------------------------- | | `-KeyFilePath` | `-i <KeyFilePath>` | `-o IdentityFile=<KeyFilePath>` | | `-UserName` | `-l <UserName>` | `-o User=<UserName>` | | `-Port` | `-p <Port>` | `-o Port=<Port>` | | `-ComputerName -Subsystem` | `-s <ComputerName> <Subsystem>` | `-o Host=<ComputerName>` | Any values explicitly passed by parameters take precedence over values passed in the **Options** hashtable. For more information about `ssh_config` files, see [ssh_config(5)](https://man.openbsd.org/ssh_config.5). ## RELATED LINKS [Connect-PSSession](Connect-PSSession.md) [Disconnect-PSSession](Disconnect-PSSession.md) [Enter-PSSession](Enter-PSSession.md) [Exit-PSSession](Exit-PSSession.md) [Get-PSSession](Get-PSSession.md) [Invoke-Command](Invoke-Command.md) [Receive-PSSession](Receive-PSSession.md) [Remove-PSSession](Remove-PSSession.md)

#File: reference/7.6/Microsoft.PowerShell.Core/New-PSSessionConfigurationFile.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 10/02/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/new-pssessionconfigurationfile?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-PSSessionConfigurationFile --- # New-PSSessionConfigurationFile ## SYNOPSIS Creates a file that defines a session configuration. ## SYNTAX ``` New-PSSessionConfigurationFile [-Path] <String> [-SchemaVersion <Version>] [-Guid <Guid>] [-Author <String>] [-Description <String>] [-CompanyName <String>] [-Copyright <String>] [-SessionType <SessionType>] [-TranscriptDirectory <String>] [-RunAsVirtualAccount] [-RunAsVirtualAccountGroups <String[]>] [-MountUserDrive] [-UserDriveMaximumSize <Int64>] [-GroupManagedServiceAccount <String>] [-ScriptsToProcess <String[]>] [-RoleDefinitions <IDictionary>] [-RequiredGroups <IDictionary>] [-LanguageMode <PSLanguageMode>] [-ExecutionPolicy <ExecutionPolicy>] [-PowerShellVersion <Version>] [-ModulesToImport <Object[]>] [-VisibleAliases <String[]>] [-VisibleCmdlets <Object[]>] [-VisibleFunctions <Object[]>] [-VisibleExternalCommands <String[]>] [-VisibleProviders <String[]>] [-AliasDefinitions <IDictionary[]>] [-FunctionDefinitions <IDictionary[]>] [-VariableDefinitions <Object>] [-EnvironmentVariables <IDictionary>] [-TypesToProcess <String[]>] [-FormatsToProcess <String[]>] [-AssembliesToLoad <String[]>] [-Full] [<CommonParameters>] ``` ## DESCRIPTION The `New-PSSessionConfigurationFile` cmdlet creates a file of settings that define a session configuration and the environment of sessions that are created by using the session configuration. To use the file in a session configuration, use the **Path** parameter of the `Register-PSSessionConfiguration` or `Set-PSSessionConfiguration` cmdlets. The session configuration file that `New-PSSessionConfigurationFile` creates is a human-readable text file that contains a hash table of the session configuration properties and values. The file has a `.pssc` filename extension. All parameters of `New-PSSessionConfigurationFile` are optional, except for the **Path** parameter. If you omit a parameter, the corresponding key in the session configuration file is commented-out, except where noted in the parameter description. A session configuration, also known as an endpoint, is a collection of settings on the local computer that define the environment for PowerShell sessions (**PSSessions**) that connect to the computer. All **PSSessions** use a session configuration. To specify a particular session configuration, use the **ConfigurationName** parameter of cmdlets that create a session, such as the `New-PSSession` cmdlet. A session configuration file makes it easy to define a session configuration without complex scripts or code assemblies. The settings in the file are used with the optional startup script and any assemblies in the session configuration. For more information about session configurations and session configuration files, see [about_Session_Configurations](About/about_Session_Configurations.md) and [about_Session_Configuration_Files](About/about_Session_Configuration_Files.md). This cmdlet was introduced in PowerShell 3.0. Starting with PowerShell 6.0, this cmdlet was only available on the Windows platform. PowerShell 7.3 made this cmdlet available on all supported platforms. ## EXAMPLES ### Example 1: Creating and using a NoLanguage session This example show how to create and the effects of using a no-language session. The steps include: 1. Create a new configuration file. 1. Register the configuration. 1. Create a new session that uses the configuration. 1. Run commands in that new session. To run the commands in this example, start PowerShell by using the Run as administrator option. This option is required to run the `Register-PSSessionConfiguration` cmdlet. ```powershell New-PSSessionConfigurationFile -Path .\NoLanguage.pssc -LanguageMode NoLanguage Register-PSSessionConfiguration -Path .\NoLanguage.pssc -Name NoLanguage -Force $NoLanguageSession = New-PSSession -ComputerName Srv01 -ConfigurationName NoLanguage Invoke-Command -Session $NoLanguageSession -ScriptBlock { if ((Get-Date) -lt '1January2099') {'Before'} else {'After'} } ``` ```Output The syntax is not supported by this runspace. This might be because it is in no-language mode. + CategoryInfo : ParserError: (if ((Get-Date) ...') {'Before'} :String) [], ParseException + FullyQualifiedErrorId : ScriptsNotAllowed + PSComputerName : localhost ``` In this example, the `Invoke-Command` fails because the **LanguageMode** is set to **NoLanguage**. ### Example 2: Creating and using a RestrictedLanguage session This example show how to create and the effects of using a no-language session. The steps include: 1. Create a new configuration file. 1. Register the configuration. 1. Create a new session that uses the configuration. 1. Run commands in that new session. To run the commands in this example, start PowerShell by using the Run as administrator option. This option is required to run the `Register-PSSessionConfiguration` cmdlet. ```powershell New-PSSessionConfigurationFile -Path .\NoLanguage.pssc -LanguageMode RestrictedLanguage Register-PSSessionConfiguration -Path .\NoLanguage.pssc -Name RestrictedLanguage -Force $RestrictedSession = New-PSSession -ComputerName Srv01 -ConfigurationName RestrictedLanguage Invoke-Command -Session $RestrictedSession -ScriptBlock { if ((Get-Date) -lt '1January2099') {'Before'} else {'After'} } ``` ```Output Before ``` In this example, the `Invoke-Command` succeeds because the **LanguageMode** is set to **RestrictedLanguage**. ### Example 3: Changing a Session Configuration File This example shows how to change the session configuration file that is used in an existing session named "ITTasks". Previously, these sessions had only the core modules and an internal **ITTasks** module. The administrator wants to add the **PSScheduledJob** module to sessions created by using the ITTasks session configuration. ```powershell New-PSSessionConfigurationFile -Path .\New-ITTasks.pssc -ModulesToImport Microsoft*, ITTasks, PSScheduledJob Set-PSSessionConfiguration -Name ITTasks -Path .\New-ITTasks.pssc ``` The `New-PSSessionConfigurationFile` cmdlet to create a session configuration file that imports the required modules. The `Set-PSSessionConfiguration` cmdlet replaces the current configuration file with the new one. This new configuration only affects new sessions created after the change. Existing "ITTasks" sessions are not affected. ### Example 4: Editing a Session Configuration File This example shows how to change a session configuration by editing the active session configuration copy of the configuration file. To modify the session configuration copy of the configuration file, you must have full control access to the file. This may require you to change the permissions on the file. In this scenario, we want to add a new alias for the `Select-String` cmdlet by editing the active configuration file. The example code below performs the following steps to make this change: 1. Get the configuration file path for the ITConfig session. 1. The user edits the configuration file using **Notepad.exe** to change the **AliasDefinitions** value as follows: `AliasDefinitions = @(@{Name='slst';Value='Select-String'})`. 1. Test the updated configuration file. ```powershell $ITConfig = Get-PSSessionConfiguration -Name ITConfig notepad.exe $ITConfig.ConfigFilePath Test-PSSessionConfigurationFile -Path $ITConfig.ConfigFilePath ``` ```Output True ``` Use the **Verbose** parameter with `Test-PSSessionConfigurationFile` to display any errors that are detected. The cmdlet returns `$true` if no errors are detected in the file. ### Example 5: Create a sample configuration file This example shows a `New-PSSessionConfigurationFile` command that uses all the cmdlet parameters. It is included to show the correct input format for each parameter. The resulting SampleFile.pssc is displayed in the output. ```powershell $configSettings = @{ Path = '.\SampleFile.pssc' SchemaVersion = '1.0.0.0' Author = 'User01' Copyright = '(c) Fabrikam Corporation. All rights reserved.' CompanyName = 'Fabrikam Corporation' Description = 'This is a sample file.' ExecutionPolicy = 'AllSigned' PowerShellVersion = '3.0' LanguageMode = 'FullLanguage' SessionType = 'Default' EnvironmentVariables = @{TESTSHARE='\\Test2\Test'} ModulesToImport = @{ModuleName='PSScheduledJob'; ModuleVersion='1.0.0.0'; GUID='50cdb55f-5ab7-489f-9e94-4ec21ff51e59'},'PSDiagnostics' AssembliesToLoad = 'System.Web.Services','FSharp.Compiler.CodeDom.dll' TypesToProcess = 'Types1.ps1xml','Types2.ps1xml' FormatsToProcess = 'CustomFormats.ps1xml' ScriptsToProcess = 'Get-Inputs.ps1' AliasDefinitions = @{Name='hlp';Value='Get-Help';Description='Gets help.';Options='AllScope'}, @{Name='Update';Value='Update-Help';Description='Updates help';Options='ReadOnly'} FunctionDefinitions = @{Name='Get-Function';ScriptBlock={Get-Command -CommandType Function};Options='ReadOnly'} VariableDefinitions = @{Name='WarningPreference';Value='SilentlyContinue'} VisibleAliases = 'c*','g*','i*','s*' VisibleCmdlets = 'Get*' VisibleFunctions = 'Get*' VisibleProviders = 'FileSystem','Function','Variable' RunAsVirtualAccount = $true RunAsVirtualAccountGroups = 'Backup Operators' } New-PSSessionConfigurationFile @configSettings Get-Content SampleFile.pssc ``` ```Output @{ # Version number of the schema used for this document SchemaVersion = '1.0.0.0' # ID used to uniquely identify this document GUID = '1caeff7f-27ca-4360-97cf-37846f594235' # Author of this document Author = 'User01' # Description of the functionality provided by these settings Description = 'This is a sample file.' # Company associated with this document CompanyName = 'Fabrikam Corporation' # Copyright statement for this document Copyright = '(c) Fabrikam Corporation. All rights reserved.' # Session type defaults to apply for this session configuration. Can be 'RestrictedRemoteServer' (recommended), 'Empty', or 'Default' SessionType = 'Default' # Directory to place session transcripts for this session configuration # TranscriptDirectory = 'C:\Transcripts\' # Whether to run this session configuration as the machine's (virtual) administrator account RunAsVirtualAccount = $true # Groups associated with machine's (virtual) administrator account RunAsVirtualAccountGroups = 'Backup Operators' # Scripts to run when applied to a session ScriptsToProcess = 'Get-Inputs.ps1' # User roles (security groups), and the role capabilities that should be applied to them when applied to a session # RoleDefinitions = @{ 'CONTOSO\SqlAdmins' = @{ RoleCapabilities = 'SqlAdministration' }; 'CONTOSO\SqlManaged' = @{ RoleCapabilityFiles = 'C:\RoleCapability\SqlManaged.psrc' }; 'CONTOSO\ServerMonitors' = @{ VisibleCmdlets = 'Get-Process' } } # Language mode to apply when applied to a session. Can be 'NoLanguage' (recommended), 'RestrictedLanguage', 'ConstrainedLanguage', or 'FullLanguage' LanguageMode = 'FullLanguage' # Execution policy to apply when applied to a session ExecutionPolicy = 'AllSigned' # Version of the PowerShell engine to use when applied to a session PowerShellVersion = '3.0' # Modules to import when applied to a session ModulesToImport = @{ 'GUID' = '50cdb55f-5ab7-489f-9e94-4ec21ff51e59' 'ModuleName' = 'PSScheduledJob' 'ModuleVersion' = '1.0.0.0' }, 'PSDiagnostics' # Aliases to make visible when applied to a session VisibleAliases = 'c*', 'g*', 'i*', 's*' # Cmdlets to make visible when applied to a session VisibleCmdlets = 'Get*' # Functions to make visible when applied to a session VisibleFunctions = 'Get*' # Providers to make visible when applied to a session VisibleProviders = 'FileSystem', 'Function', 'Variable' # Aliases to be defined when applied to a session AliasDefinitions = @{ 'Description' = 'Gets help.' 'Name' = 'hlp' 'Options' = 'AllScope' 'Value' = 'Get-Help' }, @{ 'Description' = 'Updates help' 'Name' = 'Update' 'Options' = 'ReadOnly' 'Value' = 'Update-Help' } # Functions to define when applied to a session FunctionDefinitions = @{ 'Name' = 'Get-Function' 'Options' = 'ReadOnly' 'ScriptBlock' = {Get-Command -CommandType Function} } # Variables to define when applied to a session VariableDefinitions = @{ 'Name' = 'WarningPreference' 'Value' = 'SilentlyContinue' } # Environment variables to define when applied to a session EnvironmentVariables = @{ 'TESTSHARE' = '\\Test2\Test' } # Type files (.ps1xml) to load when applied to a session TypesToProcess = 'Types1.ps1xml', 'Types2.ps1xml' # Format files (.ps1xml) to load when applied to a session FormatsToProcess = 'CustomFormats.ps1xml' # Assemblies to load when applied to a session AssembliesToLoad = 'System.Web.Services', 'FSharp.Compiler.CodeDom.dll' } ``` ## PARAMETERS ### -AliasDefinitions Adds the specified aliases to sessions that use the session configuration. Enter a hash table with the following keys: - Name - Name of the alias. This key is required. - Value - The command that the alias represents. This key is required. - Description - A text string that describes the alias. This key is optional. - Options - Alias options. This key is optional. The default value is **None**. The acceptable values for this parameter are: None, ReadOnly, Constant, Private, or AllScope. For example: `@{Name='hlp';Value='Get-Help';Description='Gets help';Options='ReadOnly'}` ```yaml Type: System.Collections.IDictionary[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -AssembliesToLoad Specifies the assemblies to load into the sessions that use the session configuration. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Author Specifies the author of the session configuration or the configuration file. The default is the current user. The value of this parameter is visible in the session configuration file, but it is not a property of the session configuration object. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CompanyName Specifies the company that created the session configuration or the configuration file. The default value is **Unknown**. The value of this parameter is visible in the session configuration file, but it is not a property of the session configuration object. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Unknown Accept pipeline input: False Accept wildcard characters: False ``` ### -Copyright Specifies a copyright the session configuration file. The value of this parameter is visible in the session configuration file, but it is not a property of the session configuration object. If you omit this parameter, `New-PSSessionConfigurationFile` generates a copyright statement by using the value of the **Author** parameter. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Description Specifies a description of the session configuration or the session configuration file. The value of this parameter is visible in the session configuration file, but it is not a property of the session configuration object. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -EnvironmentVariables Adds environment variables to the session. Enter a hash table in which the keys are the environment variable names and the values are the environment variable values. For example: `EnvironmentVariables=@{TestShare='\\Server01\TestShare'}` ```yaml Type: System.Collections.IDictionary Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ExecutionPolicy Specifies the execution policy of sessions that use the session configuration. If you omit this parameter, the value of the **ExecutionPolicy** key in the session configuration file is **Restricted**. For information about execution policies in PowerShell, see [about_Execution_Policies](about/about_Execution_Policies.md). ```yaml Type: Microsoft.PowerShell.ExecutionPolicy Parameter Sets: (All) Aliases: Accepted values: Unrestricted, RemoteSigned, AllSigned, Restricted, Default, Bypass, Undefined Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FormatsToProcess Specifies the formatting files (`.ps1xml`) that run in sessions that use the session configuration. The value of this parameter must be a full or absolute path of the formatting files. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Full Indicates that this operation includes all possible configuration properties in the session configuration file. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FunctionDefinitions Adds the specified functions to sessions that use the session configuration. Enter a hash table with the following keys: - Name - Name of the function. This key is required. - ScriptBlock - Function body. Enter a script block. This key is required. - Options - Function options. This key is optional. The default value is **None**. The acceptable values for this parameter are: None, ReadOnly, Constant, Private, or AllScope. For example: `@{Name='Get-PowerShellProcess';ScriptBlock={Get-Process powershell};Options='AllScope'}` ```yaml Type: System.Collections.IDictionary[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -GroupManagedServiceAccount Configures sessions using this session configuration to run under the context of the specified Group Managed Service Account. The machine where this session configuration is registered must have permission to request the gMSA password in order for sessions to be created successfully. This field cannot be used with the **RunAsVirtualAccount** parameter. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Guid Specifies a unique identifier for the session configuration file. If you omit this parameter, `New-PSSessionConfigurationFile` generates a GUID for the file. To create a new GUID in PowerShell, type `New-Guid`. ```yaml Type: System.Guid Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LanguageMode Determines which elements of the PowerShell language are permitted in sessions that use this session configuration. You can use this parameter to restrict the commands that particular users can run on the computer. The acceptable values for this parameter are: - FullLanguage - All language elements are permitted. - ConstrainedLanguage - Commands that contain scripts to be evaluated are not allowed. The ConstrainedLanguage mode restricts user access to Microsoft .NET Framework types, objects, or methods. - NoLanguage - Users may run cmdlets and functions, but are not permitted to use any language elements, such as script blocks, variables, or operators. - RestrictedLanguage - Users may run cmdlets and functions, but are not permitted to use script blocks or variables except for the following permitted variables: `$PSCulture`, `$PSUICulture`, `$true`, `$false`, and `$null`. Users may use only the basic comparison operators (`-eq`, `-gt`, `-lt`). Assignment statements, property references, and method calls are not permitted. The default value of the **LanguageMode** parameter depends on the value of the **SessionType** parameter. - Empty - NoLanguage - RestrictedRemoteServer - NoLanguage - Default - FullLanguage ```yaml Type: System.Management.Automation.PSLanguageMode Parameter Sets: (All) Aliases: Accepted values: FullLanguage, RestrictedLanguage, NoLanguage, ConstrainedLanguage Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ModulesToImport Specifies the modules and snap-ins that are automatically imported into sessions that use the session configuration. By default, only the **Microsoft.PowerShell.Core** snap-in is imported into remote sessions, but unless the cmdlets are excluded, users can use the `Import-Module` and `Add-PSSnapin` cmdlets to add modules and snap-ins to the session. Each module or snap-in in the value of this parameter can be represented by a string or as a hash table. A module string consists only of the name of the module or snap-in. A module hash table can include **ModuleName**, **ModuleVersion**, and **GUID** keys. Only the **ModuleName** key is required. For example, the following value consists of a string and a hash table. Any combination of strings and hash tables, in any order, is valid. `'TroubleshootingPack', @{ModuleName='PSDiagnostics'; ModuleVersion='1.0.0.0';GUID='c61d6278-02a3-4618-ae37-a524d40a7f44'}` The value of the **ModulesToImport** parameter of the `Register-PSSessionConfiguration` cmdlet takes precedence over the value of the **ModulesToImport** key in the session configuration file. ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MountUserDrive Configures sessions that use this session configuration to expose the `User:` PSDrive. User drives are unique for each connecting user and allow users to copy data to and from PowerShell endpoints even if the FileSystem provider is not exposed. User drive roots are created under `$Env:LOCALAPPDATA\Microsoft\PowerShell\DriveRoots\`. For each user connecting to the endpoint, a folder is created with the name `$Env:USERDOMAIN\$Env:USERNAME`. For computers in workgroups, the value of `$Env:USERDOMAIN` is the hostname. Contents in the user drive persist across user sessions and are not automatically removed. By default, users can only store up to 50MB of data in the user drive. This can be customized with the **UserDriveMaximumSize** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path and filename of the session configuration file. The file must have a `.pssc` file name extension. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PowerShellVersion Specifies the version of the PowerShell engine in sessions that use the session configuration. The acceptable values for this parameter are: 2.0 and 3.0. If you omit this parameter, the **PowerShellVersion** key is commented-out and newest version of PowerShell runs in the session. The value of the **PSVersion** parameter of the `Register-PSSessionConfiguration` cmdlet takes precedence over the value of the **PowerShellVersion** key in the session configuration file. ```yaml Type: System.Version Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RequiredGroups Specifies conditional access rules for users connecting to sessions that use this session configuration. Enter a hashtable to compose your list of rules using only 1 key per hashtable, 'And' or 'Or', and set the value to an array of security group names or additional hashtables. Example requiring connecting users to be members of a single group: `@{ And = 'MyRequiredGroup' }` Example requiring users to belong to group A, or both groups B and C, to access the endpoint: `@{ Or = 'GroupA', @{ And = 'GroupB', 'GroupC' } }` ```yaml Type: System.Collections.IDictionary Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RoleDefinitions Specifies the mapping between security groups (or users) and role capabilities. Users will be granted access to all role capabilities which apply to their group membership at the time the session is created. Enter a hash table in which the keys are the name of the security group and the values are hash tables that contain a list of role capabilities that should be made available to the security group. For example: `@{'Contoso\Level 2 Helpdesk Users' = @{ RoleCapabilities = 'Maintenance', 'ADHelpDesk' }}` ```yaml Type: System.Collections.IDictionary Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RunAsVirtualAccount Configures sessions using this session configuration to be run as the computer's (virtual) administrator account. This field cannot be used with the **GroupManagedServiceAccount** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RunAsVirtualAccountGroups Specifies the security groups to be associated with the virtual account when a session that uses the session configuration is run as a virtual account. If omitted, the virtual account belongs to Domain Admins on domain controllers and Administrators on all other computers. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SchemaVersion Specifies the version of the session configuration file schema. The default value is "1.0.0.0". ```yaml Type: System.Version Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ScriptsToProcess Adds the specified scripts to sessions that use the session configuration. Enter the path and file names of the scripts. The value of this parameter must be a full or absolute path of script file names. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SessionType Specifies the type of session that is created by using the session configuration. The default value is Default. The acceptable values for this parameter are: - Empty - No modules are added to session by default. Use the parameters of this cmdlet to add modules, functions, scripts, and other features to the session. This option is designed for you to create custom sessions by adding selected commands. If you do not add commands to an empty session, the session is limited to expressions and might not be usable. - Default - Adds the Microsoft.PowerShell.Core module to the session. This module includes the `Import-Module` cmdlet that users can use to import other modules unless you explicitly prohibit this cmdlet. - RestrictedRemoteServer. Includes only the following proxy functions: `Exit-PSSession`, `Get-Command`, `Get-FormatData`, `Get-Help`, `Measure-Object`, `Out-Default`, and `Select-Object`. Use the parameters of this cmdlet to add modules, functions, scripts, and other features to the session. ```yaml Type: System.Management.Automation.Remoting.SessionType Parameter Sets: (All) Aliases: Accepted values: Empty, RestrictedRemoteServer, Default Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TranscriptDirectory Specifies the directory to place session transcripts for sessions using this session configuration. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TypesToProcess Adds the specified `.ps1xml` type files to sessions that use the session configuration. Enter the type filenames. The value of this parameter must be a full or absolute path to type filenames. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UserDriveMaximumSize Specifies the maximum size for user drives exposed in sessions that use this session configuration. When omitted, the default size of each `User:` drive root is 50MB. This parameter should be used with **MountUserDrive**. ```yaml Type: System.Int64 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -VariableDefinitions Adds the specified variables to sessions that use the session configuration. Enter a hash table with the following keys: - Name - Name of the variable. This key is required. - Value - Variable value. This key is required. For example: `@{Name='WarningPreference';Value='SilentlyContinue'}` ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -VisibleAliases Limits the aliases in the session to those specified in the value of this parameter, plus any aliases that you define in the **AliasDefinition** parameter. Wildcard characters are supported. By default, all aliases that are defined by the PowerShell engine and all aliases that modules export are visible in the session. For example: `VisibleAliases='gcm', 'gp'` When any **Visible** parameter is included in the session configuration file, PowerShell removes the `Import-Module` cmdlet and its ipmo alias from the session. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -VisibleCmdlets Limits the cmdlets in the session to those specified in the value of this parameter. Wildcard characters and Module Qualified Names are supported. By default, all cmdlets that modules in the session export are visible in the session. Use the **SessionType** and **ModulesToImport** parameters to determine which modules and snap-ins are imported into the session. If no modules in **ModulesToImport** expose the cmdlet, the appropriate module will attempt to be autoloaded. When any **Visible** parameter is included in the session configuration file, PowerShell removes the `Import-Module` cmdlet and its ipmo alias from the session. ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -VisibleExternalCommands Limits the external binaries, scripts, and commands that can be executed in the session to those specified in the value of this parameter. Wildcard characters are supported. By default, no external commands are visible in the session. When any **Visible** parameter is included in the session configuration file, PowerShell, removes the `Import-Module` cmdlet and its ipmo alias from the session. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -VisibleFunctions Limits the functions in the session to those specified in the value of this parameter, plus any functions that you define in the **FunctionDefinition** parameter. Wildcard characters are supported. By default, all functions that modules in the session export are visible in the session. Use the **SessionType** and **ModulesToImport** parameters to determine which modules and snap-ins are imported into the session. When any **Visible** parameter is included in the session configuration file, PowerShell removes the `Import-Module` cmdlet and its ipmo alias from the session. ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -VisibleProviders Limits the PowerShell providers in the session to those specified in the value of this parameter. Wildcard characters are supported. By default, all providers that modules in the session export are visible in the session. Use the **SessionType** and **ModulesToImport** parameters to determine which modules are imported into the session. When any **Visible** parameter is included in the session configuration file, PowerShell removes the `Import-Module` cmdlet and its `ipmo` alias from the session. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES - Parameters, such as **VisibleCmdlets** and **VisibleProviders**, do not import items into the session. Instead, they select from among the items imported into the session. For example, if the value of the **VisibleProviders** parameter is the Certificate provider, but the **ModulesToImport** parameter does not specify the **Microsoft.PowerShell.Security** module that contains the Certificate provider, the Certificate provider is not visible in the session. - `New-PSSessionConfigurationFile` creates a session configuration file that has a `.pssc` file name extension in the path that you specify in the **Path** parameter. When you use the session configuration file to create a session configuration, the `Register-PSSessionConfiguration` cmdlet copies the configuration file and saves an active copy of the file in the **SessionConfig** subdirectory of the `$PSHOME` directory. The **ConfigFilePath** property of the session configuration contains the fully qualified path of the active session configuration file. You can modify the active configuration file in the `$PSHOME` directory at any time using any text editor. The changes that you make affect all new sessions that use the session configuration, but not existing sessions. Before using an edited session configuration file, use the `Test-PSSessionConfigurationFile` cmdlet to verify that the configuration file entries are valid. ## RELATED LINKS [Disable-PSSessionConfiguration](Disable-PSSessionConfiguration.md) [Enable-PSSessionConfiguration](Enable-PSSessionConfiguration.md) [Get-PSSessionConfiguration](Get-PSSessionConfiguration.md) [Register-PSSessionConfiguration](Register-PSSessionConfiguration.md) [Set-PSSessionConfiguration](Set-PSSessionConfiguration.md) [Test-PSSessionConfigurationFile](Test-PSSessionConfigurationFile.md) [Unregister-PSSessionConfiguration](Unregister-PSSessionConfiguration.md) [WSMan Provider](../Microsoft.WsMan.Management/About/about_WSMan_Provider.md) [about_Session_Configurations](About/about_Session_Configurations.md) [about_Session_Configuration_Files](About/about_Session_Configuration_Files.md)

#File: reference/7.6/Microsoft.PowerShell.Core/New-PSSessionOption.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/new-pssessionoption?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-PSSessionOption --- # New-PSSessionOption ## SYNOPSIS Creates an object that contains advanced options for a PSSession. ## SYNTAX ``` New-PSSessionOption [-MaximumRedirection <Int32>] [-NoCompression] [-NoMachineProfile] [-Culture <CultureInfo>] [-UICulture <CultureInfo>] [-MaximumReceivedDataSizePerCommand <Int32>] [-MaximumReceivedObjectSize <Int32>] [-OutputBufferingMode <OutputBufferingMode>] [-MaxConnectionRetryCount <Int32>] [-ApplicationArguments <PSPrimitiveDictionary>] [-OpenTimeout <Int32>] [-CancelTimeout <Int32>] [-IdleTimeout <Int32>] [-ProxyAccessType <ProxyAccessType>] [-ProxyAuthentication <AuthenticationMechanism>] [-ProxyCredential <PSCredential>] [-SkipCACheck] [-SkipCNCheck] [-SkipRevocationCheck] [-OperationTimeout <Int32>] [-NoEncryption] [-UseUTF16] [-IncludePortInSPN] [<CommonParameters>] ``` ## DESCRIPTION The `New-PSSessionOption` cmdlet creates an object that contains advanced options for a user-managed session (**PSSession**). You can use the object as the value of the **SessionOption** parameter of cmdlets that create a **PSSession**, such as `New-PSSession`, `Enter-PSSession`, and `Invoke-Command`. Without parameters, `New-PSSessionOption` generates an object that contains the default values for all of the options. Because every property can be edited, you can use the resulting object as a template and create standard option objects for your enterprise. You can also save a **SessionOption** object in the `$PSSessionOption` preference variable. The values of this variable establish new default values for the session options. They are effective when no session options are set for the session and they take precedence over options set in the session configuration, but you can override them by specifying session options or a **SessionOption** object in a cmdlet that creates a session. For more information about the `$PSSessionOption` preference variable, see [about_Preference_Variables](About/about_Preference_Variables.md). When you use a **SessionOption** object in a cmdlet that creates a session, the session option values take precedence over default values for sessions set in the `$PSSessionOption` preference variable and in the session configuration. However, they do not take precedence over maximum values, quotas or limits set in the session configuration. For more information about session configurations, see [about_Session_Configurations](About/about_Session_Configurations.md). ## EXAMPLES ### Example 1: Create a default session option This command creates a **SessionOption** object with the default values. ```powershell New-PSSessionOption ``` ```Output MaximumConnectionRedirectionCount : 5 NoCompression : False NoMachineProfile : False ProxyAccessType : IEConfig ProxyAuthentication : Negotiate ProxyCredential : SkipCACheck : False SkipCNCheck : False SkipRevocationCheck : False OperationTimeout : 00:03:00 NoEncryption : False UseUTF16 : False Culture : UICulture : MaximumReceivedDataSizePerCommand : MaximumReceivedObjectSize : ApplicationArguments : OpenTimeout : 00:03:00 CancelTimeout : 00:01:00 IdleTimeout : 00:04:00 ``` ### Example 2: Configure a session by using a session option object This example shows how to use a **SessionOption** object to configure a session. ```powershell $pso = New-PSSessionOption -Culture "fr-FR" -MaximumReceivedObjectSize 10MB New-PSSession -ComputerName Server01 -SessionOption $pso ``` The first command creates a new **SessionOption** object and saves it in the value of the `$pso` variable. The second command uses the `New-PSSession` cmdlet to create a session on the Server01 remote computer. The command uses the **SessionOption** object in the value of the `$pso` variable as the value of the **SessionOption** parameter of the command. ### Example 3: Start an interactive session This command uses the `Enter-PSSession` cmdlet to start an interactive session with the Server01 computer. ```powershell Enter-PSSession -ComputerName Server01 -SessionOption (New-PSSessionOption -NoEncryption -NoCompression) ``` The value of the **SessionOption** parameter is a `New-PSSessionOption` command that has the **NoEncryption** and **NoCompression** parameters. The `New-PSSessionOption` command is enclosed in parentheses to make sure that it runs before the `Enter-PSSession` command. ### Example 4: Modify a session option object This example demonstrates that you can modify the **SessionOption** object. All properties have read/write values. ```powershell $a = New-PSSessionOption $a.OpenTimeout ``` ```Output Days : 0 Hours : 0 Minutes : 3 Seconds : 0 Milliseconds : 0 Ticks : 1800000000 TotalDays : 0.00208333333333333 TotalHours : 0.05 TotalMinutes : 3 TotalSeconds : 180 TotalMilliseconds : 180000 ``` ```powershell $a.UICulture = (Get-UICulture) $a.OpenTimeout = (New-TimeSpan -Minutes 4) $a.MaximumConnectionRedirectionCount = 1 $a ``` ```Output MaximumConnectionRedirectionCount : 1 NoCompression : False NoMachineProfile : False ProxyAccessType : IEConfig ProxyAuthentication : Negotiate ProxyCredential : SkipCACheck : False SkipCNCheck : False SkipRevocationCheck : False OperationTimeout : 00:03:00 NoEncryption : False UseUTF16 : False Culture : UICulture : en-US MaximumReceivedDataSizePerCommand : MaximumReceivedObjectSize : ApplicationArguments : OpenTimeout : 00:04:00 CancelTimeout : 00:01:00 IdleTimeout : 00:04:00 ``` Use this method to create a standard session object for your enterprise, and then create customized versions of it for particular uses. ### Example 5: Create a preference variable This command creates a `$PSSessionOption` preference variable. ```powershell $PSSessionOption = New-PSSessionOption -OpenTimeOut 120000 ``` When the `$PSSessionOption` preference variable is set in the session, it establishes default values for options in the sessions that are created with the `New-PSSession`, `Enter-PSSession`, and `Invoke-Command` cmdlets. To make the `$PSSessionOption` variable available in all sessions, add it to your PowerShell session and to your PowerShell profile. For more information about the `$PSSessionOption` preference variable, see [about_Preference_Variables](About/about_Preference_Variables.md). For more information about profiles, see [about_Profiles](About/about_Profiles.md). ### Example 6: Fulfill the requirements for a remote session configuration This example shows how to use a **SessionOption** object to fulfill the requirements for a remote session configuration. ```powershell $skipCN = New-PSSessionOption -SkipCNCheck New-PSSession -ComputerName 171.09.21.207 -UseSSL -Credential Domain01\User01 -SessionOption $SkipCN ``` The first command uses the `New-PSSessionOption` cmdlet to create a **SessionOption** object that has the **SkipCNCheck** property. The command saves the resulting session object in the `$skipCN` variable. The second command uses the `New-PSSession` cmdlet to create a new session on a remote computer. The `$skipCN` check variable is used in the value of the **SessionOption** parameter. Because the computer is identified by its IP address, the value of the **ComputerName** parameter does not match any of the common names in the certificate that is used for Secure Sockets Layer (SSL). As a result, the **SkipCNCheck** option is required. ### Example 7: Make arguments available to a remote session This example shows how to use the **ApplicationArguments** parameter of the `New-PSSessionOption` cmdlet to make additional data available to the remote session. ```powershell $team = @{Team="IT"; Use="Testing"} $TeamOption = New-PSSessionOption -ApplicationArguments $team $s = New-PSSession -ComputerName Server01 -SessionOption $TeamOption Invoke-Command -Session $s {$PSSenderInfo.ApplicationArguments} ``` ```Output Name Value ---- ----- Team IT Use Testing PSVersionTable {CLRVersion, BuildVersion, PSVersion, WSManStackVersion...} ``` ```powershell Invoke-Command -Session $s { if ($PSSenderInfo.ApplicationArguments.Use -ne "Testing") { .\logFiles.ps1 } else { "Just testing." } } ``` ```Output Just testing. ``` The first command creates a hash table with two keys, **Team** and **Use**. The command saves the hash table in the `$team` variable. For more information about hash tables, see [about_Hash_Tables](about/about_Hash_Tables.md). Next, the `New-PSSessionOption` cmdlet, using the **ApplicationArguments** parameter, creates a **SessionOption** object saved in the `$team` variable. When `New-PSSessionOption` creates the session option object, it automatically converts the hash table in the value of the **ApplicationArguments** parameter to a **PrimitiveDictionary** so the data can be reliably transmitted to the remote session. The `New-PSSession` cmdlet starts a session on the Server01 computer. It uses the **SessionOption** parameter to include the options in the `$teamOption` variable. The `Invoke-Command` cmdlet demonstrates that the data in the `$team` variable is available to commands in the remote session. The data appears in the **ApplicationArguments** property of the `$PSSenderInfo` automatic variable. The final `Invoke-Command` shows how the data might be used. ## PARAMETERS ### -ApplicationArguments Specifies a **PrimitiveDictionary** that is sent to the remote session. Commands and scripts in the remote session, including startup scripts in the session configuration, can find this dictionary in the **ApplicationArguments** property of the `$PSSenderInfo` automatic variable. You can use this parameter to send data to the remote session. For more information, see [about_Hash_Tables](about/about_Hash_Tables.md), [about_Session_Configurations](About/about_Session_Configurations.md), and [about_Automatic_Variables](about/about_Automatic_Variables.md). ```yaml Type: System.Management.Automation.PSPrimitiveDictionary Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CancelTimeout Determines how long PowerShell waits for a cancel operation (<kbd>CTRL</kbd>+<kbd>C</kbd>) to finish before ending it. Enter a value in milliseconds. The default value is `60000` (one minute). A value of `0` (zero) means no time-out; the command continues indefinitely. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: CancelTimeoutMSec Required: False Position: Named Default value: 60000 Accept pipeline input: False Accept wildcard characters: False ``` ### -Culture Specifies the culture to use for the session. Enter a culture name in `<languagecode2>-<country/regioncode2>` format (like `ja-JP`), a variable that contains a **CultureInfo** object, or a command that gets a **CultureInfo** object. The default value is `$null`, and the culture that is set in the operating system is used in the session. ```yaml Type: System.Globalization.CultureInfo Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -IdleTimeout Determines how long the session stays open if the remote computer does not receive any communication from the local computer. This includes the heartbeat signal. When the interval expires, the session closes. The idle time-out value is of significant importance if you intend to disconnect and reconnect to a session. You can reconnect only if the session has not timed out. Enter a value in milliseconds. The minimum value is `60000` (1 minute). The maximum is the value of the **MaxIdleTimeoutMs** property of the session configuration. The default value, `-1`, does not set an idle time-out. The session uses the idle time-out that is set in the session options, if any. If none is set (`-1`), the session uses the value of the **IdleTimeoutMs** property of the session configuration or the WSMan shell time-out value (`WSMan:\<ComputerName>\Shell\IdleTimeout`), whichever is shortest. If the idle time-out set in the session options exceeds the value of the **MaxIdleTimeoutMs** property of the session configuration, the command to create a session fails. The **IdleTimeoutMs** value of the default **Microsoft.PowerShell** session configuration is `7200000` milliseconds (2 hours). Its **MaxIdleTimeoutMs** value is `2147483647` milliseconds (\>24 days). The default value of the WSMan shell idle time-out (`WSMan:\<ComputerName>\Shell\IdleTimeout`) is `7200000` milliseconds (2 hours). The idle time-out value of a session can also be changed when disconnecting from a session or reconnecting to a session. For more information, see `Disconnect-PSSession` and `Connect-PSSession`. In Windows PowerShell 2.0, the default value of the **IdleTimeout** parameter is `240000` (4 minutes). ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: IdleTimeoutMSec Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -IncludePortInSPN Includes the port number in the Service Principal Name (SPN) used for Kerberos authentication, for example, `HTTP://<ComputerName>:5985`. This option allows a client that uses a non-default SPN to authenticate against a remote computer that uses Kerberos authentication. The option is designed for enterprises where multiple services that support Kerberos authentication are running under different user accounts. For example, an IIS application that allows for Kerberos authentication can require the default SPN to be registered to a user account that differs from the computer account. In such cases, PowerShell remoting cannot use Kerberos to authenticate because it requires an SPN that is registered to the computer account. To resolve this problem, administrators can create different SPNs, such as by using `Setspn.exe`, that are registered to different user accounts and can distinguish between them by including the port number in the SPN. For more information, see [Setspn Overview](/previous-versions/windows/it-pro/windows-server-2003/cc773257(v=ws.10)). This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaxConnectionRetryCount Specifies the number of times that PowerShell attempts to make a connection to a target machine if the current attempt fails due to network issues. The default value is `5`. This parameter was added for PowerShell version 5.0. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumReceivedDataSizePerCommand Specifies the maximum number of bytes that the local computer can receive from the remote computer in a single command. Enter a value in bytes. By default, there is no data size limit. This option is designed to protect the resources on the client computer. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumReceivedObjectSize Specifies the maximum size of an object that the local computer can receive from the remote computer. This option is designed to protect the resources on the client computer. Enter a value in bytes. In Windows PowerShell 2.0, if you omit this parameter, there is no object size limit. Beginning in Windows PowerShell 3.0, if you omit this parameter, the default value is `209715200` bytes (or `200MB`). ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 209715200 Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumRedirection Determines how many times PowerShell redirects a connection to an alternate Uniform Resource Identifier (URI) before the connection fails. The default value is `5`. A value of `0` (zero) prevents all redirection. This option is used in the session only when the **AllowRedirection** parameter is used in the command that creates the session. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 5 Accept pipeline input: False Accept wildcard characters: False ``` ### -NoCompression Turns off packet compression in the session. Compression uses more processor cycles, but it makes transmission faster. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -NoEncryption Turns off data encryption. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NoMachineProfile Prevents loading the user's Windows user profile. As a result, the session might be created faster, but user-specific registry settings, items such as environment variables, and certificates are not available in the session. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -OpenTimeout Determines how long the client computer waits for the session connection to be established. When the interval expires, the command to establish the connection fails. Enter a value in milliseconds. The default value is `180000` (3 minutes). A value of `0` (zero) means no time-out; the command continues indefinitely. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: OpenTimeoutMSec Required: False Position: Named Default value: 180000 (3 minutes) Accept pipeline input: False Accept wildcard characters: False ``` ### -OperationTimeout Determines the maximum time **WinRM** waits for positive connection tests from a live connection before initiating a connection time-out. For more information on WinRM, see the [Windows Remote Management Documentation](/windows/win32/winrm/portal). **OperationTimeout** does _not_ impose a time limit on commands or processes running in a remote session and does _not_ affect other remoting protocols like SSH. The default value is `180000` (3 minutes). A value of `0` (zero) means no time-out. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: OperationTimeoutMSec Required: False Position: Named Default value: 180000 (3 minutes) Accept pipeline input: False Accept wildcard characters: False ``` ### -OutputBufferingMode Determines how command output is managed in disconnected sessions when the output buffer becomes full. If the output buffering mode is not set in the session or in the session configuration, the default value is `Block`. Users can also change the output buffering mode when disconnecting the session. If you omit this parameter, the value of the **OutputBufferingMode** of the **SessionOption** object is `None`. A value of `Block` or `Drop` overrides the output buffering mode transport option set in the session configuration. The acceptable values for this parameter are: - `Block`. When the output buffer is full, execution is suspended until the buffer is clear. - `Drop`. When the output buffer is full, execution continues. As new output is saved, the oldest output is discarded. - `None`. No output buffering mode is specified. For more information about the output buffering mode transport option, see `New-PSTransportOption`. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.Runspaces.OutputBufferingMode Parameter Sets: (All) Aliases: Accepted values: None, Drop, Block Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProxyAccessType Determines which mechanism is used to resolve the hostname. The acceptable values for this parameter are: - `IEConfig` - `WinHttpConfig` - `AutoDetect` - `NoProxyServer` - `None` The default value is `None`. For information about the values of this parameter, see [ProxyAccessType Enumeration](/dotnet/api/system.management.automation.remoting.proxyaccesstype). ```yaml Type: System.Management.Automation.Remoting.ProxyAccessType Parameter Sets: (All) Aliases: Accepted values: None, IEConfig, WinHttpConfig, AutoDetect, NoProxyServer Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProxyAuthentication Specifies the authentication method that is used for proxy resolution. The acceptable values for this parameter are: - `Basic` - `Digest` - `Negotiate` The default value is `Negotiate`. For more information about the values of this parameter, see [AuthenticationMechanism Enumeration](/dotnet/api/system.management.automation.runspaces.authenticationmechanism). ```yaml Type: System.Management.Automation.Runspaces.AuthenticationMechanism Parameter Sets: (All) Aliases: Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential, Credssp, Digest, Kerberos Required: False Position: Named Default value: Negotiate Accept pipeline input: False Accept wildcard characters: False ``` ### -ProxyCredential Specifies the credentials to use for proxy authentication. Enter a variable that contains a **PSCredential** object or a command that gets a **PSCredential** object, such as a `Get-Credential` command. If this option is not set, no credentials are specified. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipCACheck Specifies that when it connects over HTTPS, the client does not validate that the server certificate is signed by a trusted certification authority (CA). Use this option only when the remote computer is trusted by using another mechanism, such as when the remote computer is part of a network that is physically secure and isolated or when the remote computer is listed as a trusted host in a WinRM configuration. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipCNCheck Specifies that the certificate common name (CN) of the server does not have to match the hostname of the server. This option is used only in remote operations that use the HTTPS protocol. Use this option only for trusted computers. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipRevocationCheck Does not validate the revocation status of the server certificate. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -UICulture Specifies the UI culture to use for the session. Valid values include: - A culture name in `<languagecode2>-<country/regioncode2>` format, such as `ja-JP` - A variable that contains a **CultureInfo** object - A command that gets a **CultureInfo** object, such as `Get-Culture` The default value is `$null`, and the UI culture that is set in the operating system when the session is created. ```yaml Type: System.Globalization.CultureInfo Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseUTF16 Indicates that this cmdlet encodes the request in UTF16 format instead of UTF8 format. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.Remoting.PSSessionOption ## NOTES If the **SessionOption** parameter is not used in a command to create a **PSSession**, the session options are determined by the property values of the `$PSSessionOption` preference variable, if it is set. For more information about the `$PSSessionOption` variable, see [about_Preference_Variables](About/about_Preference_Variables.md). The properties of a session configuration object vary with the options set for the session configuration and the values of those options. Also, session configurations that use a session configuration file have additional properties. ## RELATED LINKS [Enter-PSSession](Enter-PSSession.md) [Invoke-Command](Invoke-Command.md) [New-PSSession](New-PSSession.md)

#File: reference/7.6/Microsoft.PowerShell.Core/New-PSTransportOption.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/new-pstransportoption?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-PSTransportOption --- # New-PSTransportOption ## SYNOPSIS Creates an object that contains advanced options for a session configuration. ## SYNTAX ``` New-PSTransportOption [-MaxIdleTimeoutSec <Int32>] [-ProcessIdleTimeoutSec <Int32>] [-MaxSessions <Int32>] [-MaxConcurrentCommandsPerSession <Int32>] [-MaxSessionsPerUser <Int32>] [-MaxMemoryPerSessionMB <Int32>] [-MaxProcessesPerSession <Int32>] [-MaxConcurrentUsers <Int32>] [-IdleTimeoutSec <Int32>] [-OutputBufferingMode <OutputBufferingMode>] [<CommonParameters>] ``` ## DESCRIPTION The `New-PSTransportOption` cmdlet creates an object that contains transport options for session configurations. You can use the object as the value of the **TransportOption** parameter of cmdlets that create or change a session configuration, such as the `Register-PSSessionConfiguration` and `Set-PSSessionConfiguration` cmdlets. You can also change the transport option settings by editing the values of the session configuration properties in the WSMan: drive. For more information, see WSMan Provider. The session configuration options represent the session values set on the server-side, or receiving end of a remote connection. The client-side, or sending end of the connection, can set session option values when the session is created, or when the client disconnects from or reconnects to the session. Unless stated otherwise, when the setting values conflict, the client-side values take precedence. However, the client-side values cannot violate maximum values and quotas set in the session configuration. Without parameters, `New-PSTransportOption` generates a transport option object that has null values for all of the options. If you omit a parameter, the object has a null value for the property that the parameter represents. A null value does not affect the session configuration. For more information about session options, see `New-PSSessionOption`. For more information about session configurations, see [about_Session_Configurations](About/about_Session_Configurations.md). This cmdlet was introduced in Windows PowerShell 3.0. ## EXAMPLES ### Example 1: Generate a default transport option ```powershell New-PSTransportOption ``` ```Output ProcessIdleTimeoutSec : MaxIdleTimeoutSec : MaxSessions : MaxConcurrentCommandsPerSession : MaxSessionsPerUser : MaxMemoryPerSessionMB : MaxProcessesPerSession : MaxConcurrentUsers : IdleTimeoutSec : OutputBufferingMode : ``` This command runs the `New-PSTransportOption` without parameters. The output shows that the cmdlet generates a transport option object that has null values for all properties. ### Example 2: Get session configuration options This example shows how to use a transport options object to set session configuration options. ```powershell $t = New-PSTransportOption -MaxSessions 40 Register-PSSessionConfiguration -Name ITTasks -TransportOption $t Get-PSSessionConfiguration -Name ITTasks | Format-List -Property * ``` ```Output Architecture : 64 Filename : %windir%\system32\pwrshplugin.dll ResourceUri : http://schemas.microsoft.com/powershell/ITTasks MaxConcurrentCommandsPerShell : 1000 UseSharedProcess : false ProcessIdleTimeoutSec : 0 xmlns : http://schemas.microsoft.com/wbem/wsman/1/config/PluginConfiguration MaxConcurrentUsers : 5 lang : en-US SupportsOptions : true ExactMatch : true RunAsUser : IdleTimeoutms : 7200000 PSVersion : 3.0 OutputBufferingMode : Block AutoRestart : false MaxShells : 40 MaxMemoryPerShellMB : 1024 MaxIdleTimeoutMs : 43200000 SDKVersion : 2 Name : ITTasks XmlRenderingType : text Capability : {Shell} RunAsPassword : MaxProcessesPerShell : 15 Enabled : True MaxShellsPerUser : 25 Permission : ``` The first command uses the `New-PSTransportOption` cmdlet to create a transport options object, which it saves in the `$t` variable. The command uses the **MaxSessions** parameter to increase the maximum number of sessions to 40. The second command uses the `Register-PSSessionConfiguration` cmdlet create the ITTasks session configuration. The command uses the **TransportOption** parameter to specify the transport options object in the `$t` variable. The third command uses the `Get-PSSessionConfiguration` cmdlet to get the ITTasks session configurations and the `Format-List` cmdlet to display all of the properties of the session configuration object in a list. The output shows that the value of the **MaxShells** property of the session configuration is 40. ### Example 3: Setting a transport option This command shows the effect of setting a transport option in a session configuration on the sessions that use the session configuration. ```powershell $t = New-PSTransportOption -IdleTimeoutSec 3600 Set-PSSessionConfiguration -Name ITTasks -TransportOption $t $s = New-PSSession -Name MyITTasks -ConfigurationName ITTasks $s | Format-List -Property * ``` ```Output State : Opened IdleTimeout : 3600000 OutputBufferingMode : Block ComputerName : localhost ConfigurationName : ITTasks InstanceId : 4110c3f5-68ea-40fa-9bbf-04a433dbb02d Id : 1 Name : MyITTasks Availability : Available ApplicationPrivateData : {PSVersionTable} Runspace : System.Management.Automation.RemoteRunspace ``` The first command uses the `New-PSTransportOption` cmdlet to create a transport option object. The command uses the **IdleTimeoutSec** parameter to set the **IdleTimeoutSec** property value of the object to one hour (3600 seconds). The command saves the transport objects object in the `$t` variable. The second command uses the `Set-PSSessionConfiguration` cmdlet to change the transport options of the ITTasks session configuration. The command uses the **TransportOption** parameter to specify the transport options object in the `$t` variable. The third command uses the `New-PSSession` cmdlet to create the MyITTasks session on the local computer. The command uses the **ConfigurationName** property to specify the ITTasks session configuration. The command saves the session in the $s variable.Notice that the command does not use the **SessionOption** parameter of `New-PSSession` to set a custom idle time-out for the session. If it did, the idle time-out value set in the session option would take precedence over the idle time-out set in the session configuration. The fourth command uses the `Format-List` cmdlet to display all properties of the session in the `$s` variable in a list. The output shows that the session has an idle time-out of one hour (360,000 milliseconds). ## PARAMETERS ### -IdleTimeoutSec Determines how long each session stays open if the remote computer does not receive any communication from the local computer. This includes the heartbeat signal. When the interval expires, the session closes. The idle time-out value is of significant importance when the user intends to disconnect and reconnect to a session. The user can reconnect only if the session has not timed out. The **IdleTimeoutSec** parameter corresponds to the **IdleTimeoutMs** property of a session configuration. Enter a value in seconds. The default value is 7200 (2 hours). The minimum value is 60 (1 minute). The maximum is the value of the **IdleTimeout** property of Shell objects in the WSMan configuration (`WSMan:\\\<ComputerName\>\Shell\IdleTimeout`). The default value is 7200000 milliseconds (2 hours). If an idle time-out value is set in the session options and in the session configuration, value set in the session options takes precedence, but it cannot exceed the value of the **MaxIdleTimeoutMs** property of the session configuration. To set the value of the **MaxIdleTimeoutMs** property, use the **MaxIdleTimeoutSec** parameter. ```yaml Type: System.Nullable`1[System.Int32] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -MaxConcurrentCommandsPerSession Limits the number of commands that can run at the same time in each session to the specified value. The default value is 1000. The **MaxConcurrentCommandsPerSession** parameter corresponds to the **MaxConcurrentCommandsPerShell** property of a session configuration. ```yaml Type: System.Nullable`1[System.Int32] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -MaxConcurrentUsers Limits the number of users who can run commands at the same time in each session to the specified value. The default value is 5. ```yaml Type: System.Nullable`1[System.Int32] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -MaxIdleTimeoutSec Limits the idle time-out set for each session to the specified value. The default value is `[int]::MaxValue` (~25 days). The idle time-out value is of significant importance when the user intends to disconnect and reconnect to a session. The user can reconnect only if the session has not timed out. The **MaxIdleTimeoutSec** parameter corresponds to the **MaxIdleTimeoutMs** property of a session configuration. ```yaml Type: System.Nullable`1[System.Int32] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -MaxMemoryPerSessionMB Limits the memory used by each session to the specified value. Enter a value in megabytes. The default value is 1024 megabytes (1 GB). The **MaxMemoryPerSessionMB** parameter corresponds to the **MaxMemoryPerShellMB** property of a session configuration. ```yaml Type: System.Nullable`1[System.Int32] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -MaxProcessesPerSession Limits the number of processes running in each session to the specified value. The default value is 15. The **MaxProcessesPerSession** parameter corresponds to the **MaxProcessesPerShell** property of a session configuration. ```yaml Type: System.Nullable`1[System.Int32] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -MaxSessions Limits the number of sessions that use the session configuration. The default value is 25. The **MaxSessions** parameter corresponds to the **MaxShells** property of a session configuration. ```yaml Type: System.Nullable`1[System.Int32] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -MaxSessionsPerUser Limits the number of sessions that use the session configuration and run with the credentials of a given user to the specified value. The default value is 25. When you specify this value, consider that many users might be using the credentials of a run as user. The **MaxSessionsPerUser** parameter corresponds to the **MaxShellsPerUser** property of a session configuration. ```yaml Type: System.Nullable`1[System.Int32] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -OutputBufferingMode Determines how command output is managed in disconnected sessions when the output buffer becomes full. The acceptable values for this parameter are: - `Block` When the output buffer is full, execution is suspended until the buffer is clear. - `Drop` When the output buffer is full, execution continues. As new output is saved, the oldest output is discarded. - `None` No output buffering mode is specified. The default value of the **OutputBufferingMode** property of sessions is Block. ```yaml Type: System.Nullable`1[System.Management.Automation.Runspaces.OutputBufferingMode] Parameter Sets: (All) Aliases: Accepted values: None, Drop, Block Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ProcessIdleTimeoutSec Limits the time-out for each host process to the specified value. The default value, 0, means that there is no time-out value for the process. Other session configurations have per-process time-out values. For example, the **Microsoft.PowerShell.Workflow** session configuration has a per-process time-out value of 28800 seconds (8 hours). ```yaml Type: System.Nullable`1[System.Int32] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.WSManConfigurationOption ## NOTES - The properties of a session configuration object vary with the options set for the session configuration and the values of those options. Also, session configurations that use a session configuration file have additional properties. ## RELATED LINKS [New-PSSession](New-PSSession.md) [New-PSSessionOption](New-PSSessionOption.md) [Register-PSSessionConfiguration](Register-PSSessionConfiguration.md) [Set-PSSessionConfiguration](Set-PSSessionConfiguration.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Out-Default.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 04/17/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/out-default?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Out-Default --- # Out-Default ## SYNOPSIS Sends the output to the default formatter and to the default output cmdlet. ## SYNTAX ``` Out-Default [-Transcript] [-InputObject <PSObject>] [<CommonParameters>] ``` ## DESCRIPTION PowerShell automatically adds `Out-Default` to the end of every top-level interactive pipeline. `Out-Default` passes the objects it receives to the PowerShell format system. Then, it writes the formatted output to the console. This cmdlet isn't intended to be used by the end user. ## EXAMPLES ### Example 1 While this cmdlet is not intended to be run directly by the end user, it can be. ```powershell Get-Process | Select-Object -First 5 | Out-Default ``` ```Output NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 12 2.56 5.20 0.00 7376 0 aesm_service 48 34.32 18.10 26.64 9320 13 AlertusDesktopAlert 24 13.97 12.74 0.77 12656 13 ApplicationFrameHost 8 1.79 4.41 0.00 8180 0 AppVShNotify 9 1.99 5.07 0.19 19320 13 AppVShNotify ``` No error is thrown when using `Out-Default` but the output isn't changed if it's not explicitly called. ## PARAMETERS ### -InputObject Accepts input to the cmdlet. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Transcript When you use this parameter, the output is only sent to the PowerShell transcript. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ## NOTES ## RELATED LINKS [Format-Custom](../Microsoft.PowerShell.Utility/Format-Custom.md) [Format-List](../Microsoft.PowerShell.Utility/Format-List.md) [Format-Table](../Microsoft.PowerShell.Utility/Format-Table.md) [Format-Wide](../Microsoft.PowerShell.Utility/Format-Wide.md) [about_Format.ps1xml](About/about_Format.ps1xml.md) [How PowerShell Formatting and Outputting REALLY works](https://devblogs.microsoft.com/powershell/how-powershell-formatting-and-outputting-really-works/)

#File: reference/7.6/Microsoft.PowerShell.Core/Out-Host.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 04/17/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/out-host?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Out-Host --- # Out-Host ## SYNOPSIS Sends output to the command line. ## SYNTAX ### All ``` Out-Host [-Paging] [-InputObject <PSObject>] [<CommonParameters>] ``` ## DESCRIPTION The `Out-Host` cmdlet sends output to the PowerShell host for display. The host displays the output at the command line. Because `Out-Host` is the default, you don't have to specify it unless you want to use its parameters. `Out-Host` passes the output of the pipeline to the host executing the command. `Out-Host` ignores ANSI escape sequences. The escape sequences are handled by the host. `Out-Host` passes ANSI escape sequences to the host without trying to interpret or change them. ## EXAMPLES ### Example 1: Display output one page at a time This example displays the system processes one page at a time. ```powershell Get-Process | Out-Host -Paging ``` ```Output NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 30 24.12 36.95 15.86 21004 14 ApplicationFrameHost 55 24.33 60.48 10.80 12904 14 BCompare <SPACE> next page; <CR> next line; Q quit 9 4.71 8.94 0.00 16864 14 explorer <SPACE> next page; <CR> next line; Q quit ``` `Get-Process` gets the system processes and sends the objects down the pipeline. `Out-Host` uses the **Paging** parameter to display one page of data at a time. ### Example 2: Use a variable as input This example uses objects stored in a variable as the input for `Out-Host`. ```powershell $io = Get-History Out-Host -InputObject $io ``` `Get-History` gets the PowerShell session's history, and stores the objects in the `$io` variable. `Out-Host` uses the **InputObject** parameter to specify the `$io` variable and displays the history. ## PARAMETERS ### -InputObject Specifies the objects that are written to the console. Enter a variable that contains the objects, or type a command or expression that gets the objects. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Paging Indicates that `Out-Host` displays one page of output at a time. The page size is determined by the characteristics of the host. After outputting the first page, the command waits for user input before the remaining pages are displayed. Press the <kbd>Spacebar</kbd> to display the next page of output or the <kbd>Enter</kbd> key to view the next line of output. Press <kbd>Q</kbd> to quit. Using **Paging** is similar to using the **more** command. > [!NOTE] > The **Paging** parameter isn't supported by the PowerShell ISE host. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. It sends objects to the host for display. ## NOTES PowerShell includes the following aliases for `Out-Host`: - All platforms: - `oh` Not all PowerShell hosts support the **Paging** parameter. For example, if you use the **Paging** parameter in the Windows PowerShell ISE, the following error is displayed: > out-lineoutput : The method or operation is not implemented. The cmdlets that contain the **Out** verb, `Out-`, don't format objects. They render objects and send them to the specified display destination. If you send an unformatted object to an `Out-` cmdlet, the cmdlet sends it to a formatting cmdlet before rendering it. The `Out-` cmdlets don't read input from files. To send data to an `Out-` cmdlet, use the pipeline to send data to the cmdlet. Or, you can store data in a variable and use the **InputObject** parameter to pass the data to the cmdlet. `Out-Host` sends data to the host only. Tt doesn't produce output objects to the pipeline. If you pipeline the output of `Out-Host` to the `Get-Member` cmdlet, `Get-Member` reports that no objects have been specified. ## RELATED LINKS [Clear-Host](Clear-Host.md) [Out-Default](Out-Default.md) [Out-File](../Microsoft.PowerShell.Utility/Out-File.md) [Out-Null](Out-Null.md) [Out-Printer](../Microsoft.PowerShell.Utility/Out-Printer.md) [Out-String](../Microsoft.PowerShell.Utility/Out-String.md) [Write-Host](../Microsoft.PowerShell.Utility/Write-Host.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Out-Null.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/out-null?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Out-Null --- # Out-Null ## SYNOPSIS Hides the output instead of sending it down the pipeline or displaying it. ## SYNTAX ``` Out-Null [-InputObject <PSObject>] [<CommonParameters>] ``` ## DESCRIPTION The `Out-Null` cmdlet sends its output to NULL, in effect, removing it from the pipeline and preventing the output from being displayed on screen. ## EXAMPLES ### Example 1: Delete output ```powershell Get-ChildItem | Out-Null ``` This command gets items in the current location/directory, but its output is not passed through the pipeline nor displayed at the command line. This is useful for hiding output that you do not need. ## PARAMETERS ### -InputObject Specifies the object to be sent to NULL (removed from pipeline). Enter a variable that contains the objects, or type a command or expression that gets the objects. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES - The cmdlets that contain the **Out** verb (the **Out** cmdlets) do not have parameters for names or file paths. To send data to an **Out** cmdlet, use a pipeline operator (`|`) to send the output of a PowerShell command to the cmdlet. You can also store data in a variable and use the **InputObject** parameter to pass the data to the cmdlet. For more information, see the examples. - `Out-Null` does not return any output objects. If you pipe the output of `Out-Null` to the Get-Member cmdlet, `Get-Member` reports that no objects have been specified. ## RELATED LINKS [Out-Default](Out-Default.md) [Out-Host](Out-Host.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Receive-Job.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 05/13/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/receive-job?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Receive-Job --- # Receive-Job ## SYNOPSIS Gets the results of the PowerShell background jobs in the current session. ## SYNTAX ### Location (Default) ``` Receive-Job [-Job] <Job[]> [[-Location] <string[]>] [-Keep] [-NoRecurse] [-Force] [-Wait] [-AutoRemoveJob] [-WriteEvents] [-WriteJobInResults] [<CommonParameters>] ``` ### ComputerName ``` Receive-Job [-Job] <Job[]> [[-ComputerName] <string[]>] [-Keep] [-NoRecurse] [-Force] [-Wait] [-AutoRemoveJob] [-WriteEvents] [-WriteJobInResults] [<CommonParameters>] ``` ### Session ``` Receive-Job [-Job] <Job[]> [[-Session] <PSSession[]>] [-Keep] [-NoRecurse] [-Force] [-Wait] [-AutoRemoveJob] [-WriteEvents] [-WriteJobInResults] [<CommonParameters>] ``` ### NameParameterSet ``` Receive-Job [-Name] <string[]> [-Keep] [-NoRecurse] [-Force] [-Wait] [-AutoRemoveJob] [-WriteEvents] [-WriteJobInResults] [<CommonParameters>] ``` ### InstanceIdParameterSet ``` Receive-Job [-InstanceId] <guid[]> [-Keep] [-NoRecurse] [-Force] [-Wait] [-AutoRemoveJob] [-WriteEvents] [-WriteJobInResults] [<CommonParameters>] ``` ### SessionIdParameterSet ``` Receive-Job [-Id] <int[]> [-Keep] [-NoRecurse] [-Force] [-Wait] [-AutoRemoveJob] [-WriteEvents] [-WriteJobInResults] [<CommonParameters>] ``` ## DESCRIPTION The `Receive-Job` cmdlet gets the results of PowerShell background jobs, such as those started by using the `Start-Job` cmdlet or the **AsJob** parameter of any cmdlet. You can get the results of all jobs or identify jobs by their name, ID, instance ID, computer name, location, or session, or by submitting a job object. When you start a PowerShell background job, the job starts, but the results don't appear immediately. Instead, the command returns an object that represents the background job. The job object contains useful information about the job, but it doesn't contain the results. This method lets you continue to work in the session while the job runs. For more information about background jobs in PowerShell, see [about_Jobs](./About/about_Jobs.md). The `Receive-Job` cmdlet gets the results that have been generated by the time that the `Receive-Job` command is submitted. If the results aren't yet complete, you can run additional `Receive-Job` commands to get the remaining results. By default, job results are deleted from the system when you receive them, but you can use the **Keep** parameter to save the results so that you can receive them again. To delete the job results, run the `Receive-Job` command again without the **Keep** parameter, close the session, or use the `Remove-Job` cmdlet to delete the job from the session. Starting in Windows PowerShell 3.0, `Receive-Job` also gets the results of custom job types, such as workflow jobs and instances of scheduled jobs. To enable `Receive-Job` to get the results a custom job type, import the module that supports the custom job type into the session before it runs a `Receive-Job` command, either by using the `Import-Module` cmdlet or by getting a cmdlet in the module. For information about a particular custom job type, see the documentation of the custom job type feature. ## EXAMPLES ### Example 1: Get results for a particular job ```powershell $job = Start-Job -ScriptBlock {Get-Process} Start-Sleep -Seconds 1 Receive-Job -Job $job ``` These commands use the **Job** parameter of `Receive-Job` to get the results of a particular job. The first command starts a job with `Start-Job` and stores the job object in the `$job` variable. The second command uses the `Receive-Job` cmdlet to get the results of the job. It uses the **Job** parameter to specify the job. ### Example 2: Use the Keep parameter ```powershell $job = Start-Job -ScriptBlock {Get-Service dhcp, fakeservice} Start-Sleep -Seconds 1 $job | Receive-Job -Keep ``` ```Output Cannot find any service with service name 'fakeservice'. + CategoryInfo : ObjectNotFound: (fakeservice:String) [Get-Service], ServiceCommandException + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand + PSComputerName : localhost Status Name DisplayName ------ ---- ----------- Running dhcp DHCP Client ``` ```powershell $job | Receive-Job -Keep ``` ```Output Cannot find any service with service name 'fakeservice'. + CategoryInfo : ObjectNotFound: (fakeservice:String) [Get-Service], ServiceCommandException + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.GetServiceCommand + PSComputerName : localhost Status Name DisplayName ------ ---- ----------- Running dhcp DHCP Client ``` This example stores a job in the `$job` variable, and pipes the job to the `Receive-Job` cmdlet. The `-Keep` parameter is also used to allow all aggregated stream data to be retrieved again after first view. ### Example 3: Get results of several background jobs When you use the **AsJob** parameter of `Invoke-Command` to start a job, the job object is created on the local computer, even though the job runs on the remote computers. As a result, you use local commands to manage the job. Also, when you use **AsJob**, PowerShell returns one job object that contains a child job for each job that was started. In this case, the job object contains three child jobs, one for each job on each remote computer. ```powershell # Use the Invoke-Command cmdlet with the -AsJob parameter to start a background job that # runs a Get-Service command on three remote computers. Store the resulting job object in # the $j variable $j = Invoke-Command -ComputerName Server01, Server02, Server03 -ScriptBlock {Get-Service} -AsJob # Display the value of the **ChildJobs** property of the job object in $j. The display # shows that the command created three child jobs, one for the job on each remote # computer. You could also use the -IncludeChildJobs parameter of the Get-Job cmdlet. $j.ChildJobs ``` ```Output Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 2 Job2 Completed True Server01 Get-Service 3 Job3 Completed True Server02 Get-Service 4 Job4 Completed True Server03 Get-Service ``` ```powershell # Use the Receive-Job cmdlet to get the results of just the Job3 child job that ran on the # Server02 computer. Use the *Keep* parameter to allow you to view the aggregated stream # data more than once. Receive-Job -Name Job3 -Keep ``` ```Output Status Name DisplayName PSComputerName ------ ----------- ----------- -------------- Running AeLookupSvc Application Experience Server02 Stopped ALG Application Layer Gateway Service Server02 Running Appinfo Application Information Server02 Running AppMgmt Application Management Server02 ``` ### Example 4: Get results of background jobs on multiple remote computers ```powershell # Use the New-PSSession cmdlet to create three user-managed PSSessions on three servers, # and save the sessions in the $s variable. $s = New-PSSession -ComputerName Server01, Server02, Server03 # Use Invoke-Command run a Start-Job command in each of the PSSessions in the $s variable. # The code creates a new job with a custom name to each server. The job outputs the # datetime from each server. Save the job objects in the $j variable. $invokeCommandSplat = @{ Session = $s ScriptBlock = { Start-Job -Name $('MyJob-' +$Env:COMPUTERNAME) -ScriptBlock { (Get-Date).ToString() } } } $j = Invoke-Command @invokeCommandSplat # To confirm that these job objects are from the remote machines, run Get-Job to show no # local jobs running. Get-Job` # Display the three job objects in $j. Note that the Localhost location is not the local # computer, but instead localhost as it relates to the job on each Server. $j ``` ```Output Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 1 MyJob-Server01 Completed True Localhost (Get-Date).ToString() 2 MyJob-Server02 Completed True Localhost (Get-Date).ToString() 3 MyJob-Server03 Completed True Localhost (Get-Date).ToString() ``` ```powershell # Use Invoke-Command to run a Receive-Job command in each of the sessions in the $s # variable and save the results in the $results variable. The Receive-Job command must be # run in each session because the jobs were run locally on each server. $results = Invoke-Command -Session $s -ScriptBlock { Receive-Job -Name $('MyJob-' +$Env:COMPUTERNAME) } ``` ```Output 3/22/2021 7:41:47 PM 3/22/2021 7:41:47 PM 3/22/2021 9:41:47 PM ``` This example shows how to get the results of background jobs run on three remote computers. Unlike the previous example, using `Invoke-Command` to run the `Start-Job` command actually started three independent jobs on each of the three computers. As a result, the command returned three job objects representing three jobs run locally on three different computers. ### Example 5: Access child jobs The `-Keep` parameter preserves the state of the aggregated streams of a job so that it can be viewed again. Without this parameter all aggregated stream data is erased when the job is received. For more information, see [about_Job_Details](About/about_Job_Details.md#child-jobs) > [!NOTE] > The aggregated streams include the streams of all child jobs. You can still reach the individual > streams of data through the job object and child job objects. ```powershell Start-Job -Name TestJob -ScriptBlock {dir C:\, Z:\} # Without the Keep parameter, aggregated child job data is displayed once. # Then destroyed. Receive-Job -Name TestJob ``` ```Output Directory: C:\ Mode LastWriteTime Length Name ---- ------------- ------ ---- d-r--- 1/24/2019 7:11 AM Program Files d-r--- 2/13/2019 8:32 AM Program Files (x86) d-r--- 10/3/2018 11:47 AM Users d----- 2/7/2019 1:52 AM Windows Cannot find drive. A drive with the name 'Z' does not exist. + CategoryInfo : ObjectNotFound: (Z:String) [Get-ChildItem], DriveNotFoundException + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand + PSComputerName : localhost ``` ```powershell # It would seem that the child job data is gone. Receive-Job -Name TestJob ``` ```Output ``` ```powershell # Using the object model, you can still retrieve child job data and streams. $job = Get-Job -Name TestJob $job.ChildJobs[0].Error ``` ```Output Cannot find drive. A drive with the name 'Z' does not exist. + CategoryInfo : ObjectNotFound: (Z:String) [Get-ChildItem], DriveNotFoundException + FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand + PSComputerName : localhost ``` ## PARAMETERS ### -AutoRemoveJob Indicates that this cmdlet deletes the job after it returns the job results. If the job has more results, the job is still deleted, but `Receive-Job` displays a message. This parameter works only on custom job types. It's designed for instances of job types that save the job or the type outside of the session, such as instances of scheduled jobs. This parameter can't be used without the **Wait** parameter. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies an array of names of computers. This parameter selects from among the job results that are stored on the local computer. It doesn't get data for jobs run on remote computers. To get job results that are stored on remote computers, use the `Invoke-Command` cmdlet to run a `Receive-Job` command remotely. ```yaml Type: System.String[] Parameter Sets: ComputerName Aliases: Cn Required: False Position: 1 Default value: All computers available Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Force Indicates that this cmdlet continues waiting if jobs are in the **Suspended** or **Disconnected** state. By default, the **Wait** parameter of `Receive-Job` returns, or terminates the wait, when jobs are in one of the following states: - Completed - Failed - Stopped - Suspended - Disconnected. The **Force** parameter is valid only when the **Wait** parameter is also used in the command. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies an array of IDs. This cmdlet gets the results of jobs with the specified IDs. The ID is an integer that uniquely identifies the job in the current session. it's easier to remember and type than the instance ID, but it's unique only in the current session. You can type one or more IDs separated by commas. To find the ID of a job, use `Get-Job`. ```yaml Type: System.Int32[] Parameter Sets: SessionIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InstanceId Specifies an array of instance IDs. This cmdlet gets the results of jobs with the specified instance IDs. An instance ID is a GUID that uniquely identifies the job on the computer. To find the instance ID of a job, use the `Get-Job` cmdlet. ```yaml Type: System.Guid[] Parameter Sets: InstanceIdParameterSet Aliases: Required: True Position: 0 Default value: All instances Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Job Specifies the job for which results are being retrieved. Enter a variable that contains the job or a command that gets the job. You can also pipe a job object to `Receive-Job`. ```yaml Type: System.Management.Automation.Job[] Parameter Sets: Location, Session, ComputerName Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Keep Indicates that this cmdlet saves the aggregated stream data in the system, even after you have received them. By default, aggregated stream data is erased after viewed with `Receive-Job`. Closing the session, or removing the job with the `Remove-Job` cmdlet also deletes aggregated stream data. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Location Specifies an array of locations. This cmdlet gets only the results of jobs in the specified locations. ```yaml Type: System.String[] Parameter Sets: Location Aliases: Required: False Position: 1 Default value: All locations Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies an array of friendly names. This cmdlet gets the results of jobs that have the specified names. Wildcard characters are supported. ```yaml Type: System.String[] Parameter Sets: NameParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -NoRecurse Indicates that this cmdlet gets results only from the specified job. By default, `Receive-Job` also gets the results of all child jobs of the specified job. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Session Specifies an array of sessions. This cmdlet gets the results of jobs that were run in the specified PowerShell session (**PSSession**). Enter a variable that contains the **PSSession** or a command that gets the **PSSession**, such as a `Get-PSSession` command. ```yaml Type: System.Management.Automation.Runspaces.PSSession[] Parameter Sets: Session Aliases: Required: False Position: 1 Default value: All sessions Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Wait Indicates that this cmdlet suppresses the command prompt until all job results are received. By default, `Receive-Job` immediately returns the available results. By default, the **Wait** parameter waits until the job is in one of the following states: - Completed - Failed - Stopped - Suspended - Disconnected To direct the **Wait** parameter to continue waiting if the job state is Suspended or Disconnected, use the **Force** parameter together with the **Wait** parameter. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WriteEvents Indicates that this cmdlet reports changes in the job state while it waits for the job to finish. This parameter is valid only when the **Wait** parameter is used in the command and the **Keep** parameter is omitted. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WriteJobInResults Indicates that this cmdlet returns the job object followed by the results. This parameter is valid only when the **Wait** parameter is used in the command and the **Keep** parameter is omitted. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](./About/about_CommonParameters.md). ## INPUTS ### System.Management.Automation.Job You can pipe job objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSObject This cmdlet returns the results of the commands in the job. ## NOTES PowerShell includes the following aliases for `Receive-Job`: - All platforms: - `rcjb` ## RELATED LINKS [Get-Job](Get-Job.md) [Invoke-Command](Invoke-Command.md) [Remove-Job](Remove-Job.md) [Start-Job](Start-Job.md) [Stop-Job](Stop-Job.md) [Wait-Job](Wait-Job.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Receive-PSSession.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/receive-pssession?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Receive-PSSession --- # Receive-PSSession ## SYNOPSIS Gets results of commands in disconnected sessions ## SYNTAX ### Session (Default) ``` Receive-PSSession [-Session] <PSSession> [-OutTarget <OutTarget>] [-JobName <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Id ``` Receive-PSSession [-Id] <Int32> [-OutTarget <OutTarget>] [-JobName <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ComputerSessionName ``` Receive-PSSession [-ComputerName] <String> [-ApplicationName <String>] [-ConfigurationName <String>] -Name <String> [-OutTarget <OutTarget>] [-JobName <String>] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [-Port <Int32>] [-UseSSL] [-SessionOption <PSSessionOption>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ComputerInstanceId ``` Receive-PSSession [-ComputerName] <String> [-ApplicationName <String>] [-ConfigurationName <String>] -InstanceId <Guid> [-OutTarget <OutTarget>] [-JobName <String>] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [-Port <Int32>] [-UseSSL] [-SessionOption <PSSessionOption>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ConnectionUriSessionName ``` Receive-PSSession [-ConfigurationName <String>] [-ConnectionUri] <Uri> [-AllowRedirection] -Name <String> [-OutTarget <OutTarget>] [-JobName <String>] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [-SessionOption <PSSessionOption>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ConnectionUriInstanceId ``` Receive-PSSession [-ConfigurationName <String>] [-ConnectionUri] <Uri> [-AllowRedirection] -InstanceId <Guid> [-OutTarget <OutTarget>] [-JobName <String>] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [-SessionOption <PSSessionOption>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### InstanceId ``` Receive-PSSession -InstanceId <Guid> [-OutTarget <OutTarget>] [-JobName <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### SessionName ``` Receive-PSSession -Name <String> [-OutTarget <OutTarget>] [-JobName <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Receive-PSSession` cmdlet gets the results of commands running in PowerShell sessions (**PSSession**) that were disconnected. If the session is currently connected, `Receive-PSSession` gets the results of commands that were running when the session was disconnected. If the session is still disconnected, `Receive-PSSession` connects to the session, resumes any commands that were suspended, and gets the results of commands running in the session. This cmdlet was introduced in PowerShell 3.0. You can use a `Receive-PSSession` in addition to or instead of a `Connect-PSSession` command. `Receive-PSSession` can connect to any disconnected or reconnected session that was started in other sessions or on other computers. `Receive-PSSession` works on **PSSessions** that were disconnected intentionally using the `Disconnect-PSSession` cmdlet or the `Invoke-Command` **InDisconnectedSession** parameter. Or disconnected unintentionally by a network interruption. If you use the `Receive-PSSession` cmdlet to connect to a session in which no commands are running or suspended, `Receive-PSSession` connects to the session, but returns no output or errors. For more information about the Disconnected Sessions feature, see [about_Remote_Disconnected_Sessions](./About/about_Remote_Disconnected_Sessions.md). Some examples use splatting to reduce the line length and improve readability. For more information, see [about_Splatting](./About/about_Splatting.md). ## EXAMPLES ### Example 1: Connect to a PSSession This example connects to a session on a remote computer and gets the results of commands that are running in a session. ```powershell Receive-PSSession -ComputerName Server01 -Name ITTask ``` The `Receive-PSSession` specifies the remote computer with the **ComputerName** parameter. The **Name** parameter identifies the ITTask session on the Server01 computer. The example gets the results of commands that were running in the ITTask session. Because the command doesn't use the **OutTarget** parameter, the results appear on the command line. ### Example 2: Get results of all commands on disconnected sessions This example gets the results of all commands running in all disconnected sessions on two remote computers. If any session wasn't disconnected or isn't running commands, `Receive-PSSession` doesn't connect to the session and doesn't return any output or errors. ```powershell Get-PSSession -ComputerName Server01, Server02 | Receive-PSSession ``` `Get-PSSession` uses the **ComputerName** parameter to specify the remote computers. The objects are sent down the pipeline to `Receive-PSSession`. ### Example 3: Get the results of a script running in a session This example uses the `Receive-PSSession` cmdlet to get the results of a script that was running in a remote computer's session. ```powershell $parms = @{ ComputerName = "Server01" Name = "ITTask" OutTarget = "Job" JobName = "ITTaskJob01" Credential = "Domain01\Admin01" } Receive-PSSession @parms ``` ```Output Id Name State HasMoreData Location -- ---- ----- ----------- -------- 16 ITTaskJob01 Running True Server01 ``` The command uses the **ComputerName** and **Name** parameters to identify the disconnected session. It uses the **OutTarget** parameter with a value of Job to direct `Receive-PSSession` to return the results as a job. The **JobName** parameter specifies a name for the job in the reconnected session. The **Credential** parameter runs the `Receive-PSSession` command using the permissions of a domain administrator. The output shows that `Receive-PSSession` returned the results as a job in the current session. To get the job results, use a `Receive-Job` command ### Example 4: Get results after a network outage This example uses the `Receive-PSSession` cmdlet to get the results of a job after a network outage disrupts a session connection. PowerShell automatically attempts to reconnect the session once per second for the next four minutes and abandons the effort only if all attempts in the four-minute interval fail. ``` PS> $s = New-PSSession -ComputerName Server01 -Name AD -ConfigurationName ADEndpoint PS> $s Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 8 AD Server01 Opened ADEndpoint Available PS> Invoke-Command -Session $s -FilePath \\Server12\Scripts\SharedScripts\New-ADResolve.ps1 Running "New-ADResolve.ps1" # Network outage # Restart local computer # Network access is not re-established within 4 minutes PS> Get-PSSession -ComputerName Server01 Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 Backup Server01 Disconnected Microsoft.PowerShell None 8 AD Server01 Disconnected ADEndpoint None PS> Receive-PSSession -ComputerName Server01 -Name AD -OutTarget Job -JobName AD Job Id Name State HasMoreData Location -- ---- ----- ----------- -------- 16 ADJob Running True Server01 PS> Get-PSSession -ComputerName Server01 Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 Backup Server01 Disconnected Microsoft.PowerShell Busy 8 AD Server01 Opened ADEndpoint Available ``` The `New-PSSession` cmdlet creates a session on the Server01 computer and saves the session in the `$s` variable. The `$s` variable displays that the **State** is Opened and the **Availability** is Available. These values indicate that you're connected to the session and can run commands in the session. The `Invoke-Command` cmdlet runs a script in the session in the `$s` variable. The script begins to run and return data, but a network outage occurs that interrupts the session. The user has to exit the session and restart the local computer. When the computer restarts, the user starts PowerShell and runs a `Get-PSSession` command to get sessions on the Server01 computer. The output shows that the **AD** session still exists on the Server01 computer. The **State** indicates that the **AD** session is disconnected. The **Availability** value of None, indicates that the session isn't connected to any client sessions. The `Receive-PSSession` cmdlet reconnects to the **AD** session and gets the results of the script that ran in the session. The command uses the **OutTarget** parameter to request the results in a job named **ADJob**. The command returns a job object and the output indicates that the script is still running. The `Get-PSSession` cmdlet is used to check the job state. The output confirms that the `Receive-PSSession` cmdlet reconnected to the **AD** session, which is now open and available for commands. And, the script resumed execution and is getting the script results. ### Example 5: Reconnect to disconnected sessions This example uses the `Receive-PSSession` cmdlet to reconnect to sessions that were intentionally disconnected and get the results of jobs that were running in the sessions. ``` PS> $parms = @{ InDisconnectedSession = $true ComputerName = "Server01", "Server02", "Server30" FilePath = "\\Server12\Scripts\SharedScripts\Get-BugStatus.ps1" Name = "BugStatus" SessionOption = @{IdleTimeout = 86400000} ConfigurationName = "ITTasks" } PS> Invoke-Command @parms PS> exit PS> $s = Get-PSSession -ComputerName Server01, Server02, Server30 -Name BugStatus PS> $s Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 ITTask Server01 Disconnected ITTasks None 8 ITTask Server02 Disconnected ITTasks None 2 ITTask Server30 Disconnected ITTasks None PS> $Results = Receive-PSSession -Session $s PS> $s Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 ITTask Server01 Opened ITTasks Available 8 ITTask Server02 Opened ITTasks Available 2 ITTask Server30 Opened ITTasks Available PS> $Results Bug Report - Domain 01 ---------------------- ComputerName BugCount LastUpdated -------------- --------- ------------ Server01 121 Friday, December 30, 2011 5:03:34 PM ``` The `Invoke-Command` cmdlet runs a script on three remote computers. Because the script gathers and summarizes data from multiple databases, it often takes the script an extended time to finish. The command uses the **InDisconnectedSession** parameter that starts the scripts and then immediately disconnects the sessions. The **SessionOption** parameter extends the **IdleTimeout** value of the disconnected session. Disconnected sessions are considered idle from the moment they're disconnected. It's important to set the idle time-out for long enough so that the commands can complete and you can reconnect to the session. You can set the **IdleTimeout** only when you create the **PSSession** and change it only when you disconnect from it. You can't change the **IdleTimeout** value when you connect to a **PSSession** or receiving its results. After running the command, the user exits PowerShell and closes the computer. The next day, the user resumes Windows, starts PowerShell, and uses `Get-PSSession` to get the sessions in which the scripts were running. The command identifies the sessions by the computer name, session name, and the name of the session configuration and saves the sessions in the `$s` variable. The value of the `$s` variable is displayed and shows that the sessions are disconnected, but aren't busy. The `Receive-PSSession` cmdlet connects to the sessions in the `$s` variable and gets their results. The command saves the results in the `$Results` variable. The `$s` variable is displayed and shows that the sessions are connected and available for commands. The script results in the `$Results` variable are displayed in the PowerShell console. If any of the results are unexpected, the user can run commands in the sessions to investigate the root cause. ### Example 6: Running a job in a disconnected session This example shows what happens to a job that's running in a disconnected session. ``` PS> $s = New-PSSession -ComputerName Server01 -Name Test PS> $j = Invoke-Command -Session $s { 1..1500 | ForEach-Object {"Return $_"; sleep 30}} -AsJob PS> $j Id Name State HasMoreData Location -- ---- ----- ----------- -------- 16 Job1 Running True Server01 PS> $s | Disconnect-PSSession Id Name ComputerName State ConfigurationName Availability -- ---- ------------ ----- ----------------- ------------ 1 Test Server01 Disconnected Microsoft.PowerShell None PS> $j Id Name State HasMoreData Location -- ---- ----- ----------- -------- 16 Job1 Disconnected True Server01 PS> Receive-Job $j -Keep Return 1 Return 2 PS> $s2 = Connect-PSSession -ComputerName Server01 -Name Test PS> $j2 = Receive-PSSession -ComputerName Server01 -Name Test PS> Receive-Job $j Return 3 Return 4 ``` The `New-PSSession` cmdlet creates the Test session on the Server01 computer. The command saves the session in the `$s` variable. The `Invoke-Command` cmdlet runs a command in the session in the `$s` variable. The command uses the **AsJob** parameter to run the command as a job and creates the job object in the current session. The command returns a job object that's saved in the `$j` variable. The `$j` variable displays the job object. The session object in the `$s` variable is sent down the pipeline to `Disconnect-PSSession` and the session is disconnected. The `$j` variable is displayed and shows the effect of disconnecting the job object in the `$j` variable. The job state is now Disconnected. The `Receive-Job` is run on the job in the `$j` variable. The output shows that the job began to return output before the session and the job were disconnected. The `Connect-PSSession` cmdlet is run in the same client session. The command reconnects to the Test session on the Server01 computer and saves the session in the `$s2` variable. The `Receive-PSSession` cmdlet gets the results of the job that was running in the session. Because the command is run in the same session, `Receive-PSSession` returns the results as a job by default and reuses the same job object. The command saves the job in the `$j2` variable. The `Receive-Job` cmdlet gets the results of the job in the `$j` variable. ## PARAMETERS ### -AllowRedirection Indicates that this cmdlet allows redirection of this connection to an alternate Uniform Resource Identifier (URI). When you use the **ConnectionURI** parameter, the remote destination can return an instruction to redirect to a different URI. By default, PowerShell doesn't redirect connections, but you can use this parameter to enable it to redirect the connection. You can also limit the number of times the connection is redirected by changing the **MaximumConnectionRedirectionCount** session option value. Use the **MaximumRedirection** parameter of the `New-PSSessionOption` cmdlet or set the **MaximumConnectionRedirectionCount** property of the `$PSSessionOption` preference variable. The default value is 5. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ConnectionUriSessionName, ConnectionUriInstanceId Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ApplicationName Specifies an application. This cmdlet connects only to sessions that use the specified application. Enter the application name segment of the connection URI. For example, in the following connection URI, WSMan is the application name: `http://localhost:5985/WSMAN`. The application name of a session is stored in the **Runspace.ConnectionInfo.AppName** property of the session. The parameter's value is used to select and filter sessions. It doesn't change the application that the session uses. ```yaml Type: System.String Parameter Sets: ComputerInstanceId, ComputerSessionName Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Authentication Specifies the mechanism that's used to authenticate the user credentials in the command to reconnect to a disconnected session. The acceptable values for this parameter are: - Default - Basic - Credssp - Digest - Kerberos - Negotiate - NegotiateWithImplicitCredential The default value is Default. For more information about the values of this parameter, see [AuthenticationMechanism Enumeration](/dotnet/api/system.management.automation.runspaces.authenticationmechanism). > [!CAUTION] > Credential Security Support Provider (CredSSP) authentication, in which the user credentials are > passed to a remote computer to be authenticated, is designed for commands that require > authentication on more than one resource, such as accessing a remote network share. This mechanism > increases the security risk of the remote operation. If the remote computer is compromised, the > credentials that are passed to it can be used to control the network session. ```yaml Type: System.Management.Automation.Runspaces.AuthenticationMechanism Parameter Sets: ComputerInstanceId, ComputerSessionName, ConnectionUriSessionName, ConnectionUriInstanceId Aliases: Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential, Credssp, Digest, Kerberos Required: False Position: Named Default value: Default Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to connect to the disconnected session. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. Certificates can be mapped only to local user accounts, and don't work with domain accounts. To get a certificate thumbprint, use a `Get-Item` or `Get-ChildItem` command in the PowerShell `Cert:` drive. ```yaml Type: System.String Parameter Sets: ComputerInstanceId, ComputerSessionName, ConnectionUriSessionName, ConnectionUriInstanceId Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies the computer on which the disconnected session is stored. Sessions are stored on the computer that's at the server-side, or receiving end of a connection. The default is the local computer. Type the NetBIOS name, an IP address, or a fully qualified domain name (FQDN) of one computer. Wildcard characters aren't permitted. To specify the local computer, type the computer name, a dot (`.`), `$Env:COMPUTERNAME`, or localhost. ```yaml Type: System.String Parameter Sets: ComputerInstanceId, ComputerSessionName Aliases: Cn Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ConfigurationName Specifies the name of a session configuration. This cmdlet connects only to sessions that use the specified session configuration. Enter a configuration name or the fully qualified resource URI for a session configuration. If you specify only the configuration name, the following schema URI is prepended: `http://schemas.microsoft.com/powershell`. The configuration name of a session is stored in the **ConfigurationName** property of the session. The parameter's value is used to select and filter sessions. It doesn't change the session configuration that the session uses. For more information about session configurations, see [about_Session_Configurations](./About/about_Session_Configurations.md). ```yaml Type: System.String Parameter Sets: ComputerInstanceId, ComputerSessionName, ConnectionUriSessionName, ConnectionUriInstanceId Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ConnectionUri Specifies a URI that defines the connection endpoint that is used to reconnect to the disconnected session. The URI must be fully qualified. The string's format is as follows: `<Transport>://<ComputerName>:<Port>/<ApplicationName>` The default value is as follows: `http://localhost:5985/WSMAN` If you don't specify a connection URI, you can use the **UseSSL**, **ComputerName**, **Port**, and **ApplicationName** parameters to specify the connection URI values. Valid values for the **Transport** segment of the URI are HTTP and HTTPS. If you specify a connection URI with a Transport segment, but don't specify a port, the session is created with standard ports: 80 for HTTP and 443 for HTTPS. To use the default ports for PowerShell remoting, specify port 5985 for HTTP or 5986 for HTTPS. If the destination computer redirects the connection to a different URI, PowerShell prevents the redirection unless you use the **AllowRedirection** parameter in the command. ```yaml Type: System.Uri Parameter Sets: ConnectionUriSessionName, ConnectionUriInstanceId Aliases: URI, CU Required: True Position: 0 Default value: http://localhost:5985/WSMAN Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to connect to the disconnected session. The default is the current user. Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. If you type a user name, you're prompted to enter the password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: ComputerInstanceId, ComputerSessionName, ConnectionUriSessionName, ConnectionUriInstanceId Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies the ID of a disconnected session. The **Id** parameter works only when the disconnected session was previously connected to the current session. This parameter is valid, but not effective, when the session is stored on the local computer, but wasn't connected to the current session. ```yaml Type: System.Int32 Parameter Sets: Id Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -InstanceId Specifies the instance ID of the disconnected session. The instance ID is a GUID that uniquely identifies a **PSSession** on a local or remote computer. The instance ID is stored in the **InstanceId** property of the **PSSession**. ```yaml Type: System.Guid Parameter Sets: ComputerInstanceId, ConnectionUriInstanceId, InstanceId Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -JobName Specifies a friendly name for the job that `Receive-PSSession` returns. `Receive-PSSession` returns a job when the value of the **OutTarget** parameter is Job or the job that's running in the disconnected session was started in the current session. If the job that's running in the disconnected session was started in the current session, PowerShell reuses the original job object in the session and ignores the value of the **JobName** parameter. If the job that's running in the disconnected session was started in a different session, PowerShell creates a new job object. It uses a default name, but you can use this parameter to change the name. If the default value or explicit value of the **OutTarget** parameter isn't Job, the command succeeds, but the **JobName** parameter has no effect. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies the friendly name of the disconnected session. ```yaml Type: System.String Parameter Sets: ComputerSessionName, ConnectionUriSessionName, SessionName Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OutTarget Determines how the session results are returned. The acceptable values for this parameter are: - **Job**. Returns the results asynchronously in a job object. You can use the **JobName** parameter to specify a name or new name for the job. - **Host**. Returns the results to the command line (synchronously). If the command is being resumed or the results consist of a large number of objects, the response might be delayed. The default value of the **OutTarget** parameter is Host. If the command that's being received in a disconnected session was started in the current session, the default value of the **OutTarget** parameter is the form in which the command was started. If the command was started as a job, by default, it's returned as a job. Otherwise, it's returned to the host program by default. Typically, the host program displays returned objects at the command line without delay, but this behavior can vary. ```yaml Type: Microsoft.PowerShell.Commands.OutTarget Parameter Sets: (All) Aliases: Accepted values: Default, Host, Job Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Port Specifies the remote computer's network port that's used to reconnect to the session. To connect to a remote computer, it must be listening on the port that the connection uses. The default ports are 5985, which is the WinRM port for HTTP, and 5986, which is the WinRM port for HTTPS. Before using an alternate port, you must configure the WinRM listener on the remote computer to listen on that port. To configure the listener, type the following two commands at the PowerShell prompt: `Remove-Item -Path WSMan:\Localhost\listener\listener* -Recurse` `New-Item -Path WSMan:\Localhost\listener -Transport http -Address * -Port \<port-number\>` Don't use the **Port** parameter unless it's necessary. The port that's set in the command applies to all computers or sessions on which the command runs. An alternate port setting might prevent the command from running on all computers. ```yaml Type: System.Int32 Parameter Sets: ComputerInstanceId, ComputerSessionName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Session Specifies the disconnected session. Enter a variable that contains the **PSSession** or a command that creates or gets the **PSSession**, such as a `Get-PSSession` command. ```yaml Type: System.Management.Automation.Runspaces.PSSession Parameter Sets: Session Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -SessionOption Specifies advanced options for the session. Enter a **SessionOption** object, such as one that you create by using the `New-PSSessionOption` cmdlet, or a hash table in which the keys are session option names and the values are session option values. The default values for the options are determined by the value of the `$PSSessionOption` preference variable, if it's set. Otherwise, the default values are established by options set in the session configuration. The session option values take precedence over default values for sessions set in the `$PSSessionOption` preference variable and in the session configuration. However, they don't take precedence over maximum values, quotas, or limits set in the session configuration. For a description of the session options that includes the default values, see `New-PSSessionOption`. For information about the **$PSSessionOption** preference variable, see [about_Preference_Variables](./About/about_Preference_Variables.md). For more information about session configurations, see [about_Session_Configurations](./About/about_Session_Configurations.md). ```yaml Type: System.Management.Automation.Remoting.PSSessionOption Parameter Sets: ComputerInstanceId, ComputerSessionName, ConnectionUriSessionName, ConnectionUriInstanceId Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL Indicates that this cmdlet uses the Secure Sockets Layer (SSL) protocol to connect to the disconnected session. By default, SSL isn't used. WS-Management encrypts all PowerShell content transmitted over the network. **UseSSL** is an additional protection that sends the data across an HTTPS connection instead of an HTTP connection. If you use this parameter and SSL isn't available on the port that's used for the command, the command fails. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerInstanceId, ComputerSessionName Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.Runspaces.PSSession You can pipe session objects to this cmdlet, such as objects returned by the `Get-PSSession` cmdlet. ### System.Int32 You can pipe session Ids to this cmdlet. ### System.Guid You can pipe the instance Ids of sessions this cmdlet. ### System.String You can pipe session names to this cmdlet. ## OUTPUTS ### System.Management.Automation.Job If the value or default value of the **OutTarget** parameter is `Job`, `Receive-PSSession` returns a job object. ### System.Management.Automation.PSObject This cmdlet returns the results of commands that ran in the disconnected session, if any. ## NOTES PowerShell includes the following aliases for `Receive-PSSession`: - All platforms: - `rcsn` This cmdlet is only available on Windows platforms. `Receive-PSSession` gets results only from sessions that were disconnected. Only sessions that are connected to, or terminate at, computers that run PowerShell 3.0 or later versions can be disconnected and reconnected. If the commands that were running in the disconnected session didn't generate results or if the results were already returned to another session, `Receive-PSSession` doesn't generate any output. A session's output buffering mode determines how commands in the session manage output when the session is disconnected. When the value of the **OutputBufferingMode** option of the session is Drop and the output buffer is full, the command starts to delete output. `Receive-PSSession` can't recover this output. For more information about the output buffering mode option, see the help articles for the [New-PSSessionOption](New-PSSessionOption.md) and [New-PSTransportOption](New-PSTransportOption.md) cmdlets. You can't change the idle time-out value of a **PSSession** when you connect to the **PSSession** or receive results. The **SessionOption** parameter of `Receive-PSSession` takes a **SessionOption** object that has an **IdleTimeout** value. However, the **IdleTimeout** value of the **SessionOption** object and the **IdleTimeout** value of the `$PSSessionOption` variable are ignored when it connects to a **PSSession** or receiving results. - You can set and change the idle time-out of a **PSSession** when you create the **PSSession**, by using the `New-PSSession` or `Invoke-Command` cmdlets, and when you disconnect from the **PSSession**. - The **IdleTimeout** property of a **PSSession** is critical to disconnected sessions because it determines how long a disconnected session is maintained on the remote computer. Disconnected sessions are considered to be idle from the moment that they are disconnected, even if commands are running in the disconnected session. If you start a start a job in a remote session by using the **AsJob** parameter of the `Invoke-Command` cmdlet, the job object is created in the current session, even though the job runs in the remote session. If you disconnect the remote session, the job object in the current session is disconnected from the job. The job object contains any results that were returned to it, but doesn't receive new results from the job in the disconnected session. If a different client connects to the session that contains the running job, the results that were delivered to the original job object in the original session aren't available in the newly connected session. Only results that were not delivered to the original job object are available in the reconnected session. Similarly, if you start a script in a session and then disconnect from the session, any results that the script delivers to the session before disconnecting aren't available to another client that connects to the session. To prevent data loss in sessions that you intend to disconnect, use the **InDisconnectedSession** parameter of the `Invoke-Command` cmdlet. Because this parameter prevents results from being returned to the current session, all results are available when the session is reconnected. You can also prevent data loss by using the `Invoke-Command` cmdlet to run a `Start-Job` command in the remote session. In this case, the job object is created in the remote session. You can't use the `Receive-PSSession` cmdlet to get the job results. Instead, use the `Connect-PSSession` cmdlet to connect to the session and then use the `Invoke-Command` cmdlet to run a `Receive-Job` command in the session. When a session that contains a running job is disconnected and then reconnected, the original job object is reused only if the job is disconnected and reconnected to the same session, and the command to reconnect doesn't specify a new job name. If the session is reconnected to a different client session or a new job name is specified, PowerShell creates a new job object for the new session. When you disconnect a **PSSession**, the session state is Disconnected and the availability is None. - The value of the **State** property is relative to the current session. A value of Disconnected means that the **PSSession** isn't connected to the current session. However, it doesn't mean that the **PSSession** is disconnected from all sessions. It might be connected to a different session. To determine whether you can connect or reconnect to the session, use the **Availability** property. - An **Availability** value of None indicates that you can connect to the session. A value of Busy indicates that you can't connect to the **PSSession** because it's connected to another session. - For more information about the values of the **State** property of sessions, see [RunspaceState](/dotnet/api/system.management.automation.runspaces.runspacestate). - For more information about the values of the **Availability** property of sessions, see [RunspaceAvailability](/dotnet/api/system.management.automation.runspaces.runspaceavailability). ## RELATED LINKS [about_PSSessions](./About/about_PSSessions.md) [about_Remote](./About/about_Remote.md) [about_Remote_Disconnected_Sessions](./About/about_Remote_Disconnected_Sessions.md) [about_Session_Configurations](./About/about_Session_Configurations.md) [Connect-PSSession](Connect-PSSession.md) [Enter-PSSession](Enter-PSSession.md) [Exit-PSSession](Exit-PSSession.md) [Get-PSSession](Get-PSSession.md) [Invoke-Command](Invoke-Command.md) [New-PSSession](New-PSSession.md) [New-PSSessionOption](New-PSSessionOption.md) [New-PSTransportOption](New-PSTransportOption.md) [Remove-PSSession](Remove-PSSession.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Register-ArgumentCompleter.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 07/10/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/register-argumentcompleter?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Register-ArgumentCompleter --- # Register-ArgumentCompleter ## SYNOPSIS Registers a custom argument completer. ## SYNTAX ### NativeSet ``` Register-ArgumentCompleter -CommandName <String[]> -ScriptBlock <ScriptBlock> [-Native] [<CommonParameters>] ``` ### PowerShellSet ``` Register-ArgumentCompleter [-CommandName <String[]>] -ParameterName <String> -ScriptBlock <ScriptBlock> [<CommonParameters>] ``` ## DESCRIPTION The `Register-ArgumentCompleter` cmdlet registers a custom argument completer. An argument completer allows you to provide dynamic tab completion, at run time for any command that you specify. When you call this command with the **CommandName** parameter and without the **ParameterName** or **Native** parameters, the command runs as if you specified the **Native** parameter. This prevents the argument completer from working for PowerShell command parameters. Always specify the **ParameterName** parameter when you want to register an argument completer for PowerShell commands. ## EXAMPLES ### Example 1: Register a custom argument completer The following example registers an argument completer for the **Id** parameter of the `Set-TimeZone` cmdlet. ```powershell $s = { param( $commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters ) (Get-TimeZone -ListAvailable).Id | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object { "'$_'" } } Register-ArgumentCompleter -CommandName Set-TimeZone -ParameterName Id -ScriptBlock $s ``` The first command creates a script block that takes the required parameters, which are passed in when the user presses <kbd>Tab</kbd>. For more information, see the **ScriptBlock** parameter description. Within the script block, the available values for **Id** are retrieved using the `Get-TimeZone` cmdlet. The **Id** property for each Time Zone is piped to the `Where-Object` cmdlet. The `Where-Object` cmdlet filters out any ids that don't start with the value provided by `$wordToComplete`, which represents the text the user typed before they pressed <kbd>Tab</kbd>. The filtered ids are piped to the `ForEach-Object` cmdlet, which encloses each value in quotes to handle values that contain spaces. The second command registers the argument completer by passing the scriptblock, the **ParameterName** **Id** and the **CommandName** `Set-TimeZone`. ### Example 2: Add details to your tab completion values The following example overwrites tab completion for the **Name** parameter of the `Stop-Service` cmdlet and only returns running services. ```powershell $s = { param( $commandName, $parameterName, $wordToComplete, $commandAst, $fakeBoundParameters ) $services = Get-Service | Where-Object { $_.Status -eq 'Running' -and $_.Name -like "$wordToComplete*" } $services | ForEach-Object { New-Object -Type System.Management.Automation.CompletionResult -ArgumentList @( $_.Name # completionText $_.Name # listItemText 'ParameterValue' # resultType $_.Name # toolTip ) } } Register-ArgumentCompleter -CommandName Stop-Service -ParameterName Name -ScriptBlock $s ``` The first command creates a script block that takes the required parameters, which are passed in when the user presses <kbd>Tab</kbd>. For more information, see the **ScriptBlock** parameter description. Within the script block, the first command retrieves all running services using the `Where-Object` cmdlet. The services are piped to the `ForEach-Object` cmdlet. The `ForEach-Object` cmdlet creates a new [System.Management.Automation.CompletionResult](/dotnet/api/system.management.automation.completionresult) object and populates it with the name of the current service (represented by the pipeline variable `$_.Name`). The **CompletionResult** object allows you to provide additional details to each returned value: - **completionText** (String) - The text to be used as the auto completion result. This is the value sent to the command. - **listItemText** (String) - The text to be displayed in a list, such as when the user presses <kbd>Ctrl</kbd>+<kbd>Space</kbd>. PowerShell uses this for display only. It isn't passed to the command when selected. - **resultType** ([CompletionResultType](/dotnet/api/system.management.automation.completionresulttype)) - The type of completion result. - **toolTip** (String) - The text for the tooltip with details to display about the object. This is visible when the user selects an item after pressing <kbd>Ctrl</kbd>+<kbd>Space</kbd>. ### Example 3: Register a custom Native argument completer You can use the **Native** parameter to provide tab-completion for a native command. The following example adds tab-completion for the `dotnet` Command Line Interface (CLI). > [!NOTE] > The `dotnet complete` command is only available in version 2.0 and greater of the dotnet cli. ```powershell $scriptblock = { param( $wordToComplete, $commandAst, $cursorPosition ) dotnet complete --position $cursorPosition $commandAst.ToString() | ForEach-Object { [System.Management.Automation.CompletionResult]::new( $_, # completionText $_, # listItemText 'ParameterValue', # resultType $_ # toolTip ) } } Register-ArgumentCompleter -Native -CommandName dotnet -ScriptBlock $scriptblock ``` The first command creates a script block that takes the required parameters, which are passed in when the user presses <kbd>Tab</kbd>. For more information, see the **ScriptBlock** parameter description. Within the script block, the `dotnet complete` command performs the tab completion. The results are piped to the `ForEach-Object` cmdlet, which uses the **new** static method of the [System.Management.Automation.CompletionResult](/dotnet/api/system.management.automation.completionresult) class to create a **CompletionResult** object for each value. ## PARAMETERS ### -CommandName Specifies the name of one or more commands to register the argument completer for. This parameter is mandatory for native commands. When you specify this parameter without the **ParameterName** or **Native** parameters, the command behaves as if you had specified the **Native** parameter. When registering argument completers for PowerShell commands, always specify the **ParameterName** parameter. If you don't specify this parameter, PowerShell registers the argument completer for the specified **ParameterName** across all PowerShell commands. ```yaml Type: System.String[] Parameter Sets: NativeSet, PowerShellSet Aliases: Required: True (NativeSet), False (PowerShellSet) Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Native Indicates that the argument completer is for a native command where PowerShell can't complete parameter names. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: NativeSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ParameterName Specifies the name of the parameter the argument completer applies to. The type for specified parameters can't be an enumeration, such as the **ForegroundColor** parameter of the `Write-Host` cmdlet. For more information on enums, see [about_Enum](./About/about_Enum.md). When registering an argument completer for PowerShell commands, always specify this parameter. When you specify the **CommandName** parameter without the **ParameterName** or **Native** parameters, the command behaves as if you specified the **Native** parameter. ```yaml Type: System.String Parameter Sets: PowerShellSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ScriptBlock Specifies the commands to run to perform tab completion. The script block you provide should return the values that complete the input. The script block must unroll the values using the pipeline (`ForEach-Object`, `Where-Object`, etc.), or another suitable method. Returning an array of values causes PowerShell to treat the entire array as **one** tab completion value. The script block can also return [System.Management.Automation.CompletionResult](/dotnet/api/system.management.automation.completionresult) objects for each value to enhance the user experience. Returning **CompletionResult** objects enables you to define tooltips and custom list entries displayed when users press <kbd>Ctrl</kbd>+<kbd>Space</kbd> to show the list of available completions. The script block must accept the following parameters in the order specified below. The names of the parameters aren't important because PowerShell passes in the values by position. - `$commandName` (Position 0, **String**) - This parameter is set to the name of the command for which the script block is providing tab completion. - `$parameterName` (Position 1, **String**) - This parameter is set to the parameter whose value requires tab completion. - `$wordToComplete` (Position 2, **String**) - This parameter is set to value the user has provided before they pressed <kbd>Tab</kbd>. Your script block should use this value to determine tab completion values. - `$commandAst` (Position 3, **CommandAst**) - This parameter is set to the Abstract Syntax Tree (AST) for the current input line. For more information, see [CommandAst Class](/dotnet/api/system.management.automation.language.commandast). - `$fakeBoundParameters` (Position 4 **IDictionary**) - This parameter is set to a hashtable containing the `$PSBoundParameters` for the cmdlet, before the user pressed <kbd>Tab</kbd>. For more information, see [about_Automatic_Variables](./About/about_Automatic_Variables.md). When you specify the **Native** parameter, the script block must take the following parameters in the specified order. The names of the parameters aren't important because PowerShell passes in the values by position. - `$wordToComplete` (Position 0, **String**) - This parameter is set to value the user has provided before they pressed <kbd>Tab</kbd>. Your script block should use this value to determine tab completion values. - `$commandAst` (Position 1, **CommandAst**) - This parameter is set to the Abstract Syntax Tree (AST) for the current input line. For more information, see [CommandAst Class](/dotnet/api/system.management.automation.language.commandast). - `$cursorPosition` (Position 2, **Int32**) - This parameter is set to the position of the cursor when the user pressed <kbd>Tab</kbd>. You can also provide an **ArgumentCompleter** as a parameter attribute. For more information, see [about_Functions_Advanced_Parameters](./About/about_Functions_Advanced_Parameters.md). ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: (All) Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](./About/about_CommonParameters.md). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES ## RELATED LINKS [about_Functions_Argument_Completion](./About/about_Functions_Argument_Completion.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Register-PSSessionConfiguration.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 07/24/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/register-pssessionconfiguration?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Register-PSSessionConfiguration --- # Register-PSSessionConfiguration ## SYNOPSIS Creates and registers a new session configuration. ## SYNTAX ### NameParameterSet (Default) ``` Register-PSSessionConfiguration [-ProcessorArchitecture <String>] [-Name] <String> [-ApplicationBase <String>] [-RunAsCredential <PSCredential>] [-ThreadApartmentState <ApartmentState>] [-ThreadOptions <PSThreadOptions>] [-AccessMode <PSSessionConfigurationAccessMode>] [-UseSharedProcess] [-StartupScript <String>] [-MaximumReceivedDataSizePerCommandMB <Double>] [-MaximumReceivedObjectSizeMB <Double>] [-SecurityDescriptorSddl <String>] [-ShowSecurityDescriptorUI] [-Force] [-NoServiceRestart] [-PSVersion <Version>] [-SessionTypeOption <PSSessionTypeOption>] [-TransportOption <PSTransportOption>] [-ModulesToImport <Object[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### AssemblyNameParameterSet ``` Register-PSSessionConfiguration [-ProcessorArchitecture <String>] [-Name] <String> [-AssemblyName] <String> [-ApplicationBase <String>] [-ConfigurationTypeName] <String> [-RunAsCredential <PSCredential>] [-ThreadApartmentState <ApartmentState>] [-ThreadOptions <PSThreadOptions>] [-AccessMode <PSSessionConfigurationAccessMode>] [-UseSharedProcess] [-StartupScript <String>] [-MaximumReceivedDataSizePerCommandMB <Double>] [-MaximumReceivedObjectSizeMB <Double>] [-SecurityDescriptorSddl <String>] [-ShowSecurityDescriptorUI] [-Force] [-NoServiceRestart] [-PSVersion <Version>] [-SessionTypeOption <PSSessionTypeOption>] [-TransportOption <PSTransportOption>] [-ModulesToImport <Object[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### SessionConfigurationFile ``` Register-PSSessionConfiguration [-ProcessorArchitecture <String>] [-Name] <String> [-RunAsCredential <PSCredential>] [-ThreadApartmentState <ApartmentState>] [-ThreadOptions <PSThreadOptions>] [-AccessMode <PSSessionConfigurationAccessMode>] [-UseSharedProcess] [-StartupScript <String>] [-MaximumReceivedDataSizePerCommandMB <Double>] [-MaximumReceivedObjectSizeMB <Double>] [-SecurityDescriptorSddl <String>] [-ShowSecurityDescriptorUI] [-Force] [-NoServiceRestart] [-TransportOption <PSTransportOption>] -Path <String> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Register-PSSessionConfiguration` cmdlet creates and registers a new session configuration on the local computer. This is an advanced cmdlet that you can use to create custom sessions for remote users. Every PowerShell session (**PSSession**) uses a session configuration, also known as an endpoint. When users create a session that connects to the computer, they can select a session configuration or use the default session configuration that's registered when you enable PowerShell remoting. Users can also set the $PSSessionConfigurationName preference variable, which specifies a default configuration for remote sessions created in the current session. The session configuration defines the environment for the remote session. The configuration can determine which commands and language elements are available in the session, and it can include settings that protect the computer, such as those that limit the amount of data that the session can receive remotely in a single object or command. The security descriptor of the session configuration determines which users have permission to use the session configuration. You can define the elements of configuration by using an assembly that implements a new configuration class and by using a script that runs in the session. Beginning in PowerShell 3.0, you can also use a session configuration file to define the session configuration. For information about session configurations, see [about_Session_Configurations](About/about_Session_Configurations.md). For information about session configuration files, see [about_Session_Configuration_Files](About/about_Session_Configuration_Files.md). ## EXAMPLES ### Example 1: Register a NewShell session configuration In this example, we register the **NewShell** session configuration. The **AssemblyName** and **ApplicationBase** parameters specify the location of the **MyShell.dll** file, which specifies the cmdlets and providers in the session configuration. The **ConfigurationTypeName** parameter specifies the configuration class to use from the assembly. ```powershell $sessionConfiguration = @{ Name='NewShell' ApplicationBase='C:\MyShells\' AssemblyName='MyShell.dll' ConfigurationTypeName='MyClass' } Register-PSSessionConfiguration @sessionConfiguration ``` To use this configuration, type `New-PSSession -ConfigurationName NewShell`. ### Example 2: Register a MaintenanceShell session configuration This example registers the **MaintenanceShell** session configuration on the local computer. The **StartupScript** parameter specifies the `Maintenance.ps1` script. ```powershell Register-PSSessionConfiguration -Name MaintenanceShell -StartupScript C:\ps-test\Maintenance.ps1 ``` When a user uses a `New-PSSession` command and selects the **MaintenanceShell** configuration, the `Maintenance.ps1` script runs in the new session. The script can configure the session. This includes importing modules and setting the execution policy for the session. If the script generates any errors, including non-terminating errors, the `New-PSSession` command fails. ### Example 3: Register a session configuration This example registers the **AdminShell** session configuration. The `$sessionParams` variable is a hashtable containing all the parameter values. This hashtable is passed to the cmdlet using PowerShell splatting. The `Register-PSSessionConfiguration` command uses the **SecurityDescriptorSDDL** parameter to specify the SDDL in the value of the `$sddl` variable and the **MaximumReceivedObjectSizeMB** parameter to increase the object size limit. It also uses the **StartupScript** parameter to specify a script that configures the session. ```powershell $sddl = "O:NSG:BAD:P(A;;GA;;;BA)S:P(AU;FA;GA;;;WD)(AU;FASA;GWGX;;;WD)" $sessionParams = @{ Name="AdminShell" SecurityDescriptorSDDL=$sddl MaximumReceivedObjectSizeMB=20 StartupScript="C:\scripts\AdminShell.ps1" } Register-PSSessionConfiguration @sessionParams ``` ### Example 4: Return a configuration container element This example shows how to register the **MaintenanceShell** configuration. `Register-PSSessionConfiguration` returns a **WSManConfigContainerElement** object stored in the `$s` variable. `Format-List` displays all the properties of the returned object. The **PSPath** property shows that the object is stored in a directory of the WSMan: drive. `Get-ChildItem` (alias `dir`) displays the items in the `WSMan:\LocalHost\PlugIn` path. These include the new **MaintenanceShell** configuration and the two default configurations that come with PowerShell. ```powershell $s = Register-PSSessionConfiguration -Name MaintenanceShell -StartupScript C:\ps-test\Maintenance.ps1 $s | Format-List -Property * dir WSMan:\LocalHost\Plugin ``` ```Output PSPath : Microsoft.WSMan.Management\WSMan::localhost\Plugin\MaintenanceShell PSParentPath : Microsoft.WSMan.Management\WSMan::localhost\Plugin PSChildName : MaintenanceShell PSDrive : WSMan PSProvider : Microsoft.WSMan.Management\WSMan PSIsContainer : True Keys : {Name=MaintenanceShell} Name : MaintenanceShell TypeNameOfElement : Container Name Type Keys ---- ---- ---- MaintenanceShell Container {Name=MaintenanceShell} microsoft.powershell Container {Name=microsoft.powershell} microsoft.powershell32 Container {Name=microsoft.powershell32} ``` ### Example 5: Register a session configuration with a startup script In this example we create and register the **WithProfile** session configuration. The **StartupScript** parameter directs PowerShell to run the specified script for any session that uses the session configuration. ```powershell Register-PSSessionConfiguration -Name WithProfile -StartupScript Add-Profile.ps1 ``` The script contains a single command that uses dot sourcing to run the user's **CurrentUserAllHosts** profile in the current scope of the session. For more information about profiles, see [about_Profiles](./About/about_Profiles.md). For more information about dot sourcing, see [about_Scopes](./About/about_Scopes.md). ## PARAMETERS ### -AccessMode Enables and disables the session configuration and determines whether it can be used for remote or local sessions on the computer. The acceptable values for this parameter are: - Disabled. Disables the session configuration. It can't be used for remote or local access to the computer. - Local. Allows users of the local computer to use the session configuration to create a local loopback session on the same computer, but denies access to remote users. - Remote. Allows local and remote users to use the session configuration to create sessions and run commands on this computer. The default value is Remote. Other cmdlets can override the value of this parameter later. For example, the `Enable-PSRemoting` cmdlet allows for remote access to all session configurations, the `Enable-PSSessionConfiguration` cmdlet enables session configurations, and the `Disable-PSRemoting` cmdlet prevents remote access to all session configurations. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.Runspaces.PSSessionConfigurationAccessMode Parameter Sets: (All) Aliases: Accepted values: Disabled, Local, Remote Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ApplicationBase Specifies the path of the assembly file (`*.dll`) that's specified in the value of the **AssemblyName** parameter. Use this parameter when the value of the **AssemblyName** parameter doesn't include a path. The default is the current directory. ```yaml Type: System.String Parameter Sets: NameParameterSet, AssemblyNameParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -AssemblyName Specifies the name of an assembly file (\*.dll) in which the configuration type is defined. You can specify the path of the .dll in this parameter or in the value of the **ApplicationBase** parameter. This parameter is required when you specify the **ConfigurationTypeName** parameter. ```yaml Type: System.String Parameter Sets: AssemblyNameParameterSet Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ConfigurationTypeName Specifies the fully qualified name of the Microsoft .NET Framework type that's used for this configuration. The type that you specify must implement the **System.Management.Automation.Remoting.PSSessionConfiguration** class. To specify the assembly file (`*.dll`) that implements the configuration type, specify the **AssemblyName** and **ApplicationBase** parameters. Creating a type lets you control more aspects of the session configuration, such as exposing or hiding certain parameters of cmdlets, or setting data size and object size limits that users can't override. If you omit this parameter, the **DefaultRemotePowerShellConfiguration** class is used for the session configuration. ```yaml Type: System.String Parameter Sets: AssemblyNameParameterSet Aliases: Required: True Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Suppresses all user prompts and restarts the **WinRM** service without prompting. Restarting the service makes the configuration change effective. To prevent a restart and suppress the restart prompt, specify the **NoServiceRestart** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumReceivedDataSizePerCommandMB Specifies a limit for the amount of data that can be sent to this computer in any single remote command. Enter the data size in megabytes (MB). The default is 50 MB. If a data size limit is defined in the configuration type that's specified in the **ConfigurationTypeName** parameter, the limit in the configuration type is used and the value of this parameter is ignored. ```yaml Type: System.Nullable`1[System.Double] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumReceivedObjectSizeMB Specifies a limit for the amount of data that can be sent to this computer in any single object. Enter the data size in megabytes. The default is 10 MB. If an object size limit is defined in the configuration type that's specified in the **ConfigurationTypeName** parameter, the limit in the configuration type is used and the value of this parameter is ignored. ```yaml Type: System.Nullable`1[System.Double] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 10 Accept pipeline input: False Accept wildcard characters: False ``` ### -ModulesToImport Specifies the modules that are automatically imported into sessions that use the session configuration. By default, only **Microsoft.PowerShell.Core** is imported into sessions. Unless the cmdlets are excluded, you can use `Import-Module` to add modules to the session. The modules specified in this parameter value are imported in additions to modules that are specified by the **SessionType** parameter and those listed in the **ModulesToImport** key in the session configuration file (`New-PSSessionConfigurationFile`). However, settings in the session configuration file can hide the commands exported by modules or prevent users from using them. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Object[] Parameter Sets: NameParameterSet, AssemblyNameParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies a name for the session configuration. This parameter is required. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -NoServiceRestart Doesn't restart the **WinRM** service, and suppresses the prompt to restart the service. By default, when you run a `Register-PSSessionConfiguration` command, you are prompted to restart the **WinRM** service to make the new session configuration effective. Until the **WinRM** service is restarted, the new session configuration is not effective. To restart the **WinRM** service without prompting, specify the **Force** parameter. To restart the **WinRM** service manually, use the `Restart-Service` cmdlet. This functionality was implemented in PowerShell 7.5.0-preview.4. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path and filename of a session configuration file (.pssc), such as one created by `New-PSSessionConfigurationFile`. If you omit the path, the default is the current directory. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.String Parameter Sets: SessionConfigurationFile Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProcessorArchitecture Determines whether a 32-bit or 64-bit version of the PowerShell process is started in sessions that use this session configuration. The acceptable values for this parameter are: x86 (32-bit) and AMD64 (64-bit). The default value is determined by the processor architecture of the computer that hosts the session configuration. You can use this parameter to create a 32-bit session on a 64-bit computer. Attempts to create a 64-bit process on a 32-bit computer fail. ```yaml Type: System.String Parameter Sets: (All) Aliases: PA Accepted values: x86, amd64 Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PSVersion Specifies the version of PowerShell in sessions that use this session configuration. The value of this parameter takes precedence over the value of the **PowerShellVersion** key in the session configuration file. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Version Parameter Sets: NameParameterSet, AssemblyNameParameterSet Aliases: PowerShellVersion Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RunAsCredential Specifies credentials for commands in the session. By default, commands run with the permissions of the current user. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SecurityDescriptorSddl Specifies a Security Descriptor Definition Language (SDDL) string for the configuration. This string determines the permissions that are required to use the new session configuration. To use a session configuration in a session, users must have at least Execute (Invoke) permission for the configuration. If the security descriptor is complex, consider using the **ShowSecurityDescriptorUI** parameter instead of this parameter. You can't use both parameters in the same command. If you omit this parameter, the root SDDL for the **WinRM** service is used for this configuration. To view or change the root SDDL, use the WSMan provider. For example `Get-Item WSMan:\localhost\service\rootSDDL`. For more information about the WSMan provider, type `Get-Help WSMan`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SessionTypeOption Specifies type-specific options for the session configuration. Enter a session type options object, such as the **PSWorkflowExecutionOption** object that the `New-PSWorkflowExecutionOption` cmdlet returns. The options of sessions that use the session configuration are determined by the values of session options and the session configuration options. Unless specified, options set in the session, such as by using the `New-PSSessionOption` cmdlet, take precedence over options set in the session configuration. However, session option values can't exceed maximum values set in the session configuration. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.PSSessionTypeOption Parameter Sets: NameParameterSet, AssemblyNameParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ShowSecurityDescriptorUI Indicates that this cmdlet displays a property sheet that helps you create the SDDL for the session configuration. The property sheet appears after you enter the `Register-PSSessionConfiguration` command and then restart the **WinRM** service. When setting the permissions for the configuration, remember that users must have at least Execute (Invoke) permission to use the session configuration in a session. You can't use the **SecurityDescriptorSDDL** parameter and this parameter in the same command. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -StartupScript Specifies the fully qualified path of a PowerShell script. The specified script runs in the new session that uses the session configuration. You can use the script to additionally configure the session. If the script generates an error, even a non-terminating error, the session isn't created and the `New-PSSession` command fails. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ThreadApartmentState Specifies the apartment state of the threading module to be used. Acceptable values are: - Unknown - MTA - STA ```yaml Type: System.Threading.ApartmentState Parameter Sets: (All) Aliases: Accepted values: STA, MTA, Unknown Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ThreadOptions Specifies how threads are created and used when a command runs in the session. The acceptable values for this parameter are: - Default - ReuseThread - UseCurrentThread - UseNewThread The default value is **UseCurrentThread**. For more information, see [PSThreadOptions Enumeration](/dotnet/api/system.management.automation.runspaces.psthreadoptions?view=powershellsdk-1.1.0). ```yaml Type: System.Management.Automation.Runspaces.PSThreadOptions Parameter Sets: (All) Aliases: Accepted values: Default, UseNewThread, ReuseThread, UseCurrentThread Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TransportOption Specifies the transport option. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.PSTransportOption Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSharedProcess Use only one process to host all sessions that are started by the same user and use the same session configuration. By default, each session is hosted in its own process. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.WSMan.Management.WSManConfigContainerElement ## NOTES This cmdlet is only available on Windows platforms. To run this cmdlet you must start PowerShell by using the **Run as administrator** option. This cmdlet generates XML that represents a Web Services for Management (WS-Management) plug-in configuration and sends the XML to WS-Management, which registers the plug-in on the local computer (`New-Item WSMan:\localhost\plugin`). The properties of a session configuration object vary with the options set for the session configuration and the values of those options. Also, session configurations that use a session configuration file have additional properties. ## RELATED LINKS [Disable-PSSessionConfiguration](Disable-PSSessionConfiguration.md) [Enable-PSSessionConfiguration](Enable-PSSessionConfiguration.md) [Get-PSSessionConfiguration](Get-PSSessionConfiguration.md) [New-PSSessionConfigurationFile](New-PSSessionConfigurationFile.md) [Set-PSSessionConfiguration](Set-PSSessionConfiguration.md) [Test-PSSessionConfigurationFile](Test-PSSessionConfigurationFile.md) [Unregister-PSSessionConfiguration](Unregister-PSSessionConfiguration.md) [WSMan Provider](../Microsoft.WsMan.Management/About/about_WSMan_Provider.md) [about_Session_Configurations](About/about_Session_Configurations.md) [about_Session_Configuration_Files](About/about_Session_Configuration_Files.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Remove-Job.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/remove-job?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-Job --- # Remove-Job ## SYNOPSIS Deletes a PowerShell background job. ## SYNTAX ### SessionIdParameterSet (Default) ``` Remove-Job [-Force] [-Id] <Int32[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### JobParameterSet ``` Remove-Job [-Job] <Job[]> [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### NameParameterSet ``` Remove-Job [-Force] [-Name] <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### InstanceIdParameterSet ``` Remove-Job [-Force] [-InstanceId] <Guid[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### FilterParameterSet ``` Remove-Job [-Force] [-Filter] <Hashtable> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### StateParameterSet ``` Remove-Job [-State] <JobState> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### CommandParameterSet ``` Remove-Job [-Command <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Remove-Job` cmdlet deletes PowerShell background jobs that were started by the `Start-Job` cmdlet or by cmdlets such as `Invoke-Command` that support the **AsJob** parameter. You can use `Remove-Job` to delete all jobs or delete selected jobs. The jobs are identified by their **Name**, **Id**, **InstanceId**, **Command**, or **State**. Or, a job object can be sent down the pipeline to `Remove-Job`. Without parameters or parameter values, `Remove-Job` has no effect. Since PowerShell 3.0, `Remove-Job` can delete custom job types, such as scheduled jobs and workflow jobs. For example, `Remove-Job` deletes the scheduled job, all instances of the scheduled job on disk, and the results of all triggered job instances. If you try to delete a running job, `Remove-Job` fails. Use the `Stop-Job` cmdlet to stop a running job. Or, use `Remove-Job` with the **Force** parameter to delete a running job. Jobs remain in the global job cache until you delete the background job or close the PowerShell session. ## EXAMPLES ### Example 1: Delete a job by using its name This example uses a variable and the pipeline to delete a job by name. ```powershell $batch = Get-Job -Name BatchJob $batch | Remove-Job ``` `Get-Job` uses the **Name** parameter to specify the job, **BatchJob**. The job object is stored in the `$batch` variable. The object in `$batch` is sent down the pipeline to `Remove-Job`. An alternative is to use the **Job** parameter, such as `Remove-Job -Job $batch`. ### Example 2: Delete all jobs in a session In this example, all the jobs in the current PowerShell session are deleted. ```powershell Get-Job | Remove-Job ``` `Get-Job` gets all the jobs in the current PowerShell session. The job objects are sent down the pipeline to `Remove-Job`. ### Example 3: Delete NotStarted jobs This example deletes all jobs from the current PowerShell session that haven't started. ```powershell Remove-Job -State NotStarted ``` `Remove-Job` uses the **State** parameter to specify the job status. ### Example 4: Delete jobs by using a friendly name This example deletes all jobs from the current session with friendly names that end with *batch**, including jobs that are running. ```powershell Remove-Job -Name *batch -Force ``` `Remove-Job` uses the **Name** parameter to specify a job name pattern. The pattern includes the asterisk (`*`) wildcard to find all job names that end with **batch**. The **Force** parameter deletes jobs that running. ### Example 5: Delete a job that was created by Invoke-Command This example removes a job that was started on a remote computer using `Invoke-Command` with the **AsJob** parameter. Because the example uses the **AsJob** parameter, the job object is created on the local computer. But, the job runs on a remote computer. As a result, you use local commands to manage the job. ```powershell $job = Invoke-Command -ComputerName Server01 -ScriptBlock {Get-Process} -AsJob $job | Remove-Job ``` `Invoke-Command` runs a job on the **Server01** computer. The **AsJob** parameter runs the **ScriptBlock** as a background job. The job object is stored in the `$job` variable. The `$job` variable object is sent down the pipeline to `Remove-Job`. ### Example 6: Delete a job that was created by Invoke-Command and Start-Job This example shows how to remove a job on a remote computer that was started by using `Invoke-Command` to run `Start-Job`. The job object is created on the remote computer and remote commands are used to manage the job. A persistent connection is required when running a remote `Start-Job` command. ```powershell $S = New-PSSession -ComputerName Server01 Invoke-Command -Session $S -ScriptBlock {Start-Job -ScriptBlock {Get-Process} -Name MyJob} Invoke-Command -Session $S -ScriptBlock {Remove-Job -Name MyJob} ``` `New-PSSession` creates a **PSSession**, a persistent connection, to the **Server01** computer. The connection is saved in the `$S` variable. `Invoke-Command` connects to the session saved in `$S`. The **ScriptBlock** uses `Start-Job` to start a remote job. The job runs a `Get-Process` command and uses the **Name** parameter to specify a friendly job name, **MyJob**. `Invoke-Command` uses the `$S` session and runs `Remove-Job`. The **Name** parameter specifies that the job named **MyJob** is deleted. ### Example 7: Delete a job by using its InstanceId This example removes a job based on its **InstanceId**. ```powershell $job = Start-Job -ScriptBlock {Get-Process powershell} $job | Format-List -Property * Remove-Job -InstanceId ad02b942-8007-4407-87f3-d23e71955872 ``` ```Output State : Completed HasMoreData : True StatusMessage : Location : localhost Command : Get-Process powershell JobStateInfo : Completed Finished : System.Threading.ManualResetEvent InstanceId : ad02b942-8007-4407-87f3-d23e71955872 Id : 3 Name : Job3 ChildJobs : {Job4} PSBeginTime : 7/26/2019 11:36:56 PSEndTime : 7/26/2019 11:36:57 PSJobTypeName : BackgroundJob Output : {} Error : {} Progress : {} Verbose : {} Debug : {} Warning : {} Information : {} ``` `Start-Job` starts a background job and the job object is saved in the `$job` variable. The object in `$job` is sent down the pipeline to `Format-List`. The **Property** parameter uses an asterisk (`*`) to specify that all the object's properties are displayed in a list. `Remove-Job` uses the **InstanceId** parameter to specify the job to delete. ## PARAMETERS ### -Command Deletes jobs that include the specified words in the command. You can enter a comma-separated array. ```yaml Type: System.String[] Parameter Sets: CommandParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Filter Deletes jobs that satisfy all the conditions established in the associated hash table. Enter a hash table where the keys are job properties and the values are job property values. This parameter works only on custom job types, such as workflow jobs and scheduled jobs. It doesn't work on standard background jobs, such as those created by using the `Start-Job`. This parameter is introduced in PowerShell 3.0. ```yaml Type: System.Collections.Hashtable Parameter Sets: FilterParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Force Deletes a job even if the job's state is **Running**. If the **Force** parameter isn't specified, `Remove-Job` doesn't delete running jobs. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: SessionIdParameterSet, JobParameterSet, InstanceIdParameterSet, NameParameterSet, FilterParameterSet Aliases: F Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Deletes background jobs with the specified **Id**. You can enter a comma-separated array. The job's **Id** is a unique integer that identifies a job within the current session. To find a job's **Id**, use `Get-Job` without parameters. ```yaml Type: System.Int32[] Parameter Sets: SessionIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InstanceId Deletes jobs with the specified **InstanceId**. You can enter a comma-separated array. An **InstanceId** is a unique GUID that identifies a job. To find a job's **InstanceId**, use `Get-Job`. ```yaml Type: System.Guid[] Parameter Sets: InstanceIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Job Specifies the jobs to be deleted. Enter a variable that contains the jobs or a command that gets the jobs. You can enter a comma-separated array. You can send job objects down the pipeline to `Remove-Job`. ```yaml Type: System.Management.Automation.Job[] Parameter Sets: JobParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Name Only deletes jobs with the specified friendly name. Wildcards are permitted. You can enter a comma-separated array. Friendly names for jobs aren't guaranteed to be unique, even within a PowerShell session. Use the **WhatIf** and **Confirm** parameters when you delete files by name. ```yaml Type: System.String[] Parameter Sets: NameParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -State Only deletes jobs with the specified state. To delete jobs with a state of **Running**, use the **Force** parameter. Accepted values: - AtBreakpoint - Blocked - Completed - Disconnected - Failed - NotStarted - Running - Stopped - Stopping - Suspended - Suspending ```yaml Type: System.Management.Automation.JobState Parameter Sets: StateParameterSet Aliases: Accepted values: AtBreakpoint, Blocked, Completed, Disconnected, Failed, NotStarted, Running, Stopped, Stopping, Suspended, Suspending Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before `Remove-Job` is run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if `Remove-Job` runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.Job You can pipe a **Job** object to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Remove-Job`: - All platforms: - `rjb` A PowerShell job creates a new process. When the job completes, the process exits. When `Remove-Job` is run, the job's state is removed. If a job stops before completion and its process hasn't exited, the process is forcibly terminated. ## RELATED LINKS [about_Jobs](./About/about_Jobs.md) [about_Job_Details](./About/about_Job_Details.md) [about_Remote_Jobs](./About/about_Remote_Jobs.md) [Get-Job](Get-Job.md) [Invoke-Command](Invoke-Command.md) [Receive-Job](Receive-Job.md) [Start-Job](Start-Job.md) [Stop-Job](Stop-Job.md) [Wait-Job](Wait-Job.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Remove-Module.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 07/10/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/remove-module?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-Module --- # Remove-Module ## SYNOPSIS Removes modules from the current session. ## SYNTAX ### name ``` Remove-Module [-Name] <String[]> [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### FullyQualifiedName ``` Remove-Module [-FullyQualifiedName] <ModuleSpecification[]> [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ModuleInfo ``` Remove-Module [-ModuleInfo] <PSModuleInfo[]> [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Remove-Module` cmdlet removes the members of a module, such as cmdlets and functions, from the current session. If the module includes an assembly (`.dll`), all members that are implemented by the assembly are removed, but the assembly isn't unloaded. This cmdlet doesn't uninstall the module or delete it from the computer. It affects only the current PowerShell session. ## EXAMPLES ### Example 1: Remove a module ```powershell Remove-Module -Name "BitsTransfer" ``` This command removes the **BitsTransfer** module from the current session. ### Example 2: Remove all modules ```powershell Get-Module | Remove-Module ``` This command removes all modules from the current session. ### Example 3: Remove modules by using the pipeline ```powershell "FileTransfer", "PSDiagnostics" | Remove-Module -Verbose ``` ```Output VERBOSE: Performing operation "Remove-Module" on Target "filetransfer (Path: 'C:\Windows\system32\WindowsPowerShell\v1.0\Modules\filetransfer\filetransfer.psd1')". VERBOSE: Performing operation "Remove-Module" on Target "Microsoft.BackgroundIntelligentTransfer.Management (Path: 'C:\Windows\assembly\GAC_MSIL\Microsoft.BackgroundIntelligentTransfer.Management\1.0.0.0__31bf3856ad364e35\Microsoft.BackgroundIntelligentTransfe r.Management.dll')". VERBOSE: Performing operation "Remove-Module" on Target "psdiagnostics (Path: 'C:\Windows\system32\WindowsPowerShell\v1.0\Modules\psdiagnostics\psdiagnostics.psd1')". VERBOSE: Removing imported function 'Start-Trace'. VERBOSE: Removing imported function 'Stop-Trace'. VERBOSE: Removing imported function 'Enable-WSManTrace'. VERBOSE: Removing imported function 'Disable-WSManTrace'. VERBOSE: Removing imported function 'Enable-PSWSManCombinedTrace'. VERBOSE: Removing imported function 'Disable-PSWSManCombinedTrace'. VERBOSE: Removing imported function 'Set-LogProperties'. VERBOSE: Removing imported function 'Get-LogProperties'. VERBOSE: Removing imported function 'Enable-PSTrace'. VERBOSE: Removing imported function 'Disable-PSTrace'. VERBOSE: Performing operation "Remove-Module" on Target "PSDiagnostics (Path: 'C:\Windows\system32\WindowsPowerShell\v1.0\Modules\psdiagnostics\PSDiagnostics.psm1')". ``` This command removes the **BitsTransfer** and **PSDiagnostics** modules from the current session. The command uses a pipeline operator (`|`) to send the module names to `Remove-Module`. It uses the **Verbose** common parameter to get detailed information about the members that are removed. The **Verbose** messages show the items that are removed. The messages differ because the BitsTransfer module includes an assembly that implements its cmdlets and a nested module with its own assembly. The PSDiagnostics module includes a module script file (`.psm1`) that exports functions. ### Example 4: Remove a module using ModuleInfo ```powershell $a = Get-Module BitsTransfer Remove-Module -ModuleInfo $a ``` This command uses the **ModuleInfo** parameter to remove the BitsTransfer module. ### Example 5: Using the OnRemove event When removing a module, there is an event trigger by the module that allows a module to react to being removed and perform some cleanup task, such as freeing resources. ```powershell $OnRemoveScript = { # perform cleanup $cachedSessions | Remove-PSSession } $ExecutionContext.SessionState.Module.OnRemove += $OnRemoveScript $registerEngineEventSplat = @{ SourceIdentifier = ([System.Management.Automation.PSEngineEvent]::Exiting) Action = $OnRemoveScript } Register-EngineEvent @registerEngineEventSplat ``` The `$OnRemoveScript` variable contains the script block that cleans up the resources. You register the script block by assigning it to `$ExecutionContext.SessionState.Module.OnRemove`. You can also use `Register-EngineEvent` to have the script block execute when the PowerShell session ends. For script-based modules, you would add this code to the `.psm1` file or put it in a startup script that is listed in the **ScriptsToProcess** property of the module manifest. ## PARAMETERS ### -Force Indicates that this cmdlet removes read-only modules. By default, `Remove-Module` removes only read-write modules. The **ReadOnly** and **ReadWrite** values are stored in **AccessMode** property of a module. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FullyQualifiedName The value can be a module name, a full module specification, or a path to a module file. When the value is a path, the path can be fully qualified or relative. A relative path is resolved relative to the script that contains the using statement. When the value is a name or module specification, PowerShell searches the **PSModulePath** for the specified module. A module specification is a hashtable that has the following keys. - `ModuleName` - **Required** Specifies the module name. - `GUID` - **Optional** Specifies the GUID of the module. - It's also **Required** to specify at least one of the three below keys. - `ModuleVersion` - Specifies a minimum acceptable version of the module. - `MaximumVersion` - Specifies the maximum acceptable version of the module. - `RequiredVersion` - Specifies an exact, required version of the module. This can't be used with the other Version keys. ```yaml Type: Microsoft.PowerShell.Commands.ModuleSpecification[] Parameter Sets: FullyQualifiedName Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -ModuleInfo Specifies the module objects to remove. Enter a variable that contains a **PSModuleInfo** object or a command that gets a module object, such as a `Get-Module` command. You can also pipe module objects to `Remove-Module`. ```yaml Type: System.Management.Automation.PSModuleInfo[] Parameter Sets: ModuleInfo Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies the names of modules to remove. Wildcard characters are permitted. You can also pipe name strings to `Remove-Module`. ```yaml Type: System.String[] Parameter Sets: name Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a module name to this cmdlet. ### System.Management.Automation.PSModuleInfo You can pipe a module object to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Remove-Module`: - All platforms: - `rmo` When you remove a module, there is an event is triggered that can be used to run some cleanup code. For more details, see [Example 5](#example-5-using-the-onremove-event). ## RELATED LINKS [Get-Module](Get-Module.md) [Import-Module](Import-Module.md) [about_Modules](About/about_Modules.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Remove-PSSession.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/remove-pssession?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-PSSession --- # Remove-PSSession ## SYNOPSIS Closes one or more PowerShell sessions (PSSessions). ## SYNTAX ### Id (Default) ``` Remove-PSSession [-Id] <Int32[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Session ``` Remove-PSSession [-Session] <PSSession[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ContainerId ``` Remove-PSSession -ContainerId <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### VMId ``` Remove-PSSession -VMId <Guid[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### VMName ``` Remove-PSSession -VMName <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### InstanceId ``` Remove-PSSession -InstanceId <Guid[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Name ``` Remove-PSSession -Name <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ComputerName ``` Remove-PSSession [-ComputerName] <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Remove-PSSession` cmdlet closes PowerShell sessions (**PSSessions**) in the current session. It stops any commands that are running in the **PSSessions**, ends the **PSSession**, and releases the resources that the **PSSession** was using. If the **PSSession** is connected to a remote computer, this cmdlet also closes the connection between the local and remote computers. To remove a **PSSession**, enter the **Name**, **ComputerName**, **Id**, or **InstanceId** of the session. If you have saved the **PSSession** in a variable, the session object remains in the variable, but the state of the **PSSession** is Closed. ## EXAMPLES ### Example 1: Remove sessions by ID ```powershell Remove-PSSession -Id 1, 2 ``` This command removes the **PSSessions** that have IDs `1` and `2`. ### Example 2: Remove all the sessions in the current session ```powershell Get-PSSession | Remove-PSSession Remove-PSSession -Session (Get-PSSession) $s = Get-PSSession Remove-PSSession -Session $s ``` These commands remove all of the **PSSessions** in the current session. Although the three command formats look different, they have the same effect. ### Example 3: Close sessions by name ```powershell $r = Get-PSSession -ComputerName Serv* $r | Remove-PSSession ``` These commands close the **PSSessions** that are connected to computers that have names that begin with `Serv`. ### Example 4: Close sessions connected to a port ```powershell Get-PSSession | where {$_.Port -eq 90} | Remove-PSSession ``` This command closes the **PSSessions** that are connected to port 90. You can use this command format to identify **PSSessions** by properties other than **ComputerName**, **Name**, **InstanceId**, and **Id**. ### Example 5: Close a session by instance ID ```powershell Get-PSSession | Format-Table ComputerName, InstanceId -AutoSize ``` ```Output ComputerName InstanceId ------------ ---------------- Server01 875d231b-2788-4f36-9f67-2e50d63bb82a localhost c065ffa0-02c4-406e-84a3-dacb0d677868 Server02 4699cdbc-61d5-4e0d-b916-84f82ebede1f Server03 4e5a3245-4c63-43e4-88d0-a7798bfc2414 TX-TEST-01 fc4e9dfa-f246-452d-9fa3-1adbdd64ae85 ``` ```powershell Remove-PSSession -InstanceId fc4e9dfa-f246-452d-9fa3-1adbdd64ae85 ``` These commands show how to close a **PSSession** based on its instance ID, or **RemoteRunspaceID**. The first command uses the `Get-PSSession` cmdlet to get the **PSSessions** in the current session. It uses a pipeline operator (`|`) to send the **PSSessions** to the `Format-Table` cmdlet, which formats their **ComputerName** and **InstanceId** properties in a table. The **AutoSize** parameter compresses the columns for display. From the resulting display, you can identify the **PSSession** to be closed, and copy and paste the **InstanceId** of that **PSSession** into the second command. The second command uses the `Remove-PSSession` cmdlet to remove the **PSSession** with the specified instance ID. ### Example 6: Create a function that deletes all sessions in the current session ```powershell function EndPSS { Get-PSSession | Remove-PSSession } ``` This function closes every **PSSession** in the current session. After you add this function to your PowerShell profile, to delete all sessions, type `EndPSS`. ## PARAMETERS ### -ComputerName Specifies an array of names of computers. This cmdlet closes the **PSSessions** that are connected to the specified computers. Wildcard characters are permitted. Type the NetBIOS name, an IP address, or a fully qualified domain name of one or more remote computers. To specify the local computer, type the computer name, `localhost`, or a dot (`.`). ```yaml Type: System.String[] Parameter Sets: ComputerName Aliases: Cn Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -ContainerId Specifies an array of IDs of containers. This cmdlet removes sessions for each of the specified containers. Use the `docker ps` command to get a list of container IDs. For more information, see the help for the [docker ps](https://docs.docker.com/engine/reference/commandline/ps/) command. ```yaml Type: System.String[] Parameter Sets: ContainerId Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Id Specifies an array of IDs of sessions. This cmdlet closes the **PSSessions** with the specified IDs. Type one or more IDs, separated by commas, or use the range operator (`..`) to specify a range of IDs. An ID is an integer that uniquely identifies the **PSSession** in the current session. It is easier to remember and type than the **InstanceId**, but it is unique only in the current session. To find the ID of a **PSSession**, run the `Get-PSSession` cmdlet without parameters. ```yaml Type: System.Int32[] Parameter Sets: Id Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InstanceId Specifies an array of instance IDs. This cmdlet closes the **PSSessions** that have the specified instance IDs. The instance ID is a GUID that uniquely identifies a **PSSession** in the current session. The instance ID is unique, even when you have multiple sessions running on a single computer. The instance ID is stored in the **InstanceId** property of the object that represents a **PSSession**. To find the **InstanceId** of the **PSSessions** in the current session, type `Get-PSSession | Format-Table Name, ComputerName, InstanceId`. ```yaml Type: System.Guid[] Parameter Sets: InstanceId Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies an array of friendly names of sessions. This cmdlet closes the **PSSessions** that have the specified friendly names. Wildcard characters are permitted. Because the friendly name of a **PSSession** might not be unique, when you use the **Name** parameter, consider also using the **WhatIf** or **Confirm** parameter in the `Remove-PSSession` command. ```yaml Type: System.String[] Parameter Sets: Name Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Session Specifies the session objects of the **PSSessions** to close. Enter a variable that contains the **PSSessions** or a command that creates or gets the **PSSessions**, such as a `New-PSSession` or `Get-PSSession` command. You can also pipe one or more session objects to `Remove-PSSession`. ```yaml Type: System.Management.Automation.Runspaces.PSSession[] Parameter Sets: Session Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -VMId Specifies an array of ID of virtual machines. This cmdlet starts an interactive session with each of the specified virtual machines. To see the virtual machines that are available to you, use the following command: `Get-VM | Select-Object -Property Name, ID` ```yaml Type: System.Guid[] Parameter Sets: VMId Aliases: VMGuid Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -VMName Specifies an array of names of virtual machines. This cmdlet starts an interactive session with each of the specified virtual machines. To see the virtual machines that are available to you, use the `Get-VM` cmdlet. ```yaml Type: System.String[] Parameter Sets: VMName Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.Runspaces.PSSession You can pipe a session object to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Remove-PSSession`: - All platforms: - `rsn` - The **Id** parameter is mandatory. To delete all the **PSSessions** in the current session, type `Get-PSSession | Remove-PSSession`. - A **PSSession** uses a persistent connection to a remote computer. Create a **PSSession** to run a series of commands that share data. For more information, type `Get-Help about_PSSessions`. - **PSSessions** are specific to the current session. When you end a session, the **PSSessions** that you created in that session are forcibly closed. ## RELATED LINKS [Connect-PSSession](Connect-PSSession.md) [Disconnect-PSSession](Disconnect-PSSession.md) [Enter-PSSession](Enter-PSSession.md) [Exit-PSSession](Exit-PSSession.md) [Get-PSSession](Get-PSSession.md) [Invoke-Command](Invoke-Command.md) [New-PSSession](New-PSSession.md) [Receive-PSSession](Receive-PSSession.md) [about_PSSessions](About/about_PSSessions.md) [about_Remote](About/about_Remote.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Save-Help.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 03/06/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/save-help?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Save-Help --- # Save-Help ## SYNOPSIS Downloads and saves the newest help files to a file system directory. ## SYNTAX ### Path (Default) ``` Save-Help [-DestinationPath] <String[]> [[-Module] <PSModuleInfo[]>] [-FullyQualifiedModule <ModuleSpecification[]>] [[-UICulture] <CultureInfo[]>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-Force] [-Scope <UpdateHelpScope>] [<CommonParameters>] ``` ### LiteralPath ``` Save-Help -LiteralPath <String[]> [[-Module] <PSModuleInfo[]>] [-FullyQualifiedModule <ModuleSpecification[]>] [[-UICulture] <CultureInfo[]>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-Force] [-Scope <UpdateHelpScope>] [<CommonParameters>] ``` ## DESCRIPTION The `Save-Help` cmdlet downloads the newest help files for PowerShell modules and saves them to a directory that you specify. This feature lets you update the help files on computers that don't have access to the internet, and makes it easier to update the help files on multiple computers. This cmdlet was introduced in Windows PowerShell 3.0. Beginning in Windows PowerShell 4.0, you can use `Save-Help` to download help files for modules that are installed on remote computers. It's also possible to save a **PSModuleInfo** object using `Export-Clixml` on a computer that doesn't have internet access, import the object on a computer that does have internet access, and then run `Save-Help` on the **PSModuleInfo** object. Once you have the saved help, you can copy it to the remote computer and install it by running `Update-Help`. This process can be used to install help on computers that don't have any kind of network access. Without parameters, a `Save-Help` command downloads the newest help for all modules in the session and for modules that are installed on the computer in a location listed in the **PSModulePath** environment variable. This action skips modules that don't support Updatable Help without warning. The `Save-Help` cmdlet checks the version of any help files in the destination folder. If newer help files are available, this cmdlet downloads the newest help files from the internet, and then saves them in the folder. The `Save-Help` cmdlet works just like the `Update-Help` cmdlet, except that it saves the downloaded content, instead of extracting the help files and installing them on the computer. The saved help for each module consists of one help information (HelpInfo XML) file and a cabinet or ZIP archive (`.cab` or `.zip`) for the help files in each language. On Windows, the command downloads the cabinet files. On Linux and macOS, the command downloads ZIP files. To save the help files for modules in the PowerShell installation folder (`$PSHOME\Modules`), start PowerShell by using the **Run as administrator option**. You must be a member of the Administrators group on the computer to download the help files for these modules. To install saved help files, run `Update-Help` with the **SourcePath** parameter to specify the folder containing the saved Help files. `Update-Help` extracts the help files from the archive and installs them on in the appropriate location. ## EXAMPLES ### Example 1: Save the help for the DhcpServer module This example shows three different ways to use `Save-Help` to save the help for the **DhcpServer** module from an internet-connected client computer, without installing the **DhcpServer** module or the DHCP Server role on the local computer. ```powershell # Option 1: # 1. Run Invoke-Command to get the PSModuleInfo object for the DhcpServer module, # 2. Save-Help on the PSModuleInfo object to save the help files to a folder on # the local computer. $mod = Invoke-Command -ComputerName RemoteServer -ScriptBlock { Get-Module -Name DhcpServer -ListAvailable } Save-Help -Module $mod -DestinationPath C:\SavedHelp # Option 2: # 1. Open a PSSession to the remote computer that's running the DhcpServer module # 2. Get the PSModuleInfo object from the remote computer # 3. Save-Help on the PSModuleInfo object $session = New-PSSession -ComputerName "RemoteServer" $mod = Get-Module -PSSession $session -Name "DhcpServer" -ListAvailable Save-Help -Module $mod -DestinationPath C:\SavedHelp # Option 3: # 1. Open a CimSession to the remote computer that's running the DhcpServer module # 2. Get the PSModuleInfo object from the remote computer # 3. Save-Help on the PSModuleInfo object $cimsession = New-CimSession -ComputerName "RemoteServer" $mod = Get-Module -CimSession $cimsession -Name "DhcpServer" -ListAvailable Save-Help -Module $mod -DestinationPath "C:\SavedHelp" ``` ### Example 2: Install help for the DhcpServer module This example shows how to install help for a computer that is not network connected. For this example, the first computer isn't connected to an accessible network. Files must be copied to it using removable media. The second computer is connected to the internet and can download the help files. ```powershell # On the first computer, get the PSModuleInfo object for the module and save it to # removable media. Get-Module -Name "DhcpServer" -ListAvailable | Export-CliXml -Path E:\UsbFlashDrive\DhcpModule.xml # Move the removable media to a computer that has internet access, and then import the # PSModuleInfo object. Run Save-Help on the imported PSModuleInfo object and save the help # files to the removable media. $moduleInfo = Import-CliXml E:\UsbFlashDrive\DhcpModule.xml Save-Help -Module $moduleInfo -DestinationPath E:\UsbFlashDrive\SavedHelp # Finally, move the removable media back to the first computer and install the help. Update-Help -Module DhcpServer -SourcePath E:\UsbFlashDrive\SavedHelp ``` ### Example 3: Save help for all modules This command downloads the newest help files for all modules on the local computer. It saves the help files in the `\\Server01\Fileshare01` folder. ```powershell Save-Help -DestinationPath \\Server01\FileShare01 ``` ### Example 4: Save help for a module on the computer This command downloads the newest help files for the **ServerManager** module, and then saves them in the `\\Server01\Fileshare01` folder. ```powershell $saveHelpSplat = @{ Module = 'ServerManager' DestinationPath = '\\Server01\FileShare01' Credential = 'Domain01/Admin01' } Save-Help @saveHelpSplat ``` When a module is installed on the computer, you can type the module name as the value of the **Module** parameter, even if the module isn't imported into the current session. The command uses the **Credential** parameter to supply the credentials of a user who has permission to write to the file share. ### Example 5: Save help for a module on a different computer These commands download the newest help files for the **CustomSQL** module and save them in the `\\Server01\Fileshare01` folder. ```powershell Invoke-Command -ComputerName Server02 { Get-Module -Name CustomSQL -ListAvailable } | Save-Help -DestinationPath \\Server01\FileShare01 -Credential Domain01\Admin01 ``` Because the **CustomSQL** module isn't installed on the computer, the sequence includes an `Invoke-Command` command that gets the module object for the CustomSQL module from the Server02 computer and then pipes the module object to the `Save-Help` cmdlet. When a module isn't installed on the computer, `Save-Help` needs the module object, which includes information about the location of the newest help files. ### Example 6: Save help for a module in multiple languages This command saves help for the core PowerShell modules in four different UI cultures. The language packs for these locales don't have to be installed on the computer. ```powershell $saveHelpSplat = @{ Module = 'Microsoft.PowerShell*' UICulture = 'de-DE', 'en-US', 'fr-FR', 'ja-JP' DestinationPath = "D:\Help" } Save-Help @saveHelpSplat ``` `Save-Help` can download help files for modules in different UI cultures only when the module owner makes the translated files available on the internet. ### Example 7: Save help more than one time each day This command saves help for all modules that are installed on the computer. The command specifies the **Force** parameter to override the rule that prevents the `Save-Help` cmdlet from downloading help more than once in each 24-hour period. ```powershell Save-Help -Force -DestinationPath \\Server3\AdminShare\Help ``` The **Force** parameter also overrides the 1 GB restriction and circumvents version checking. Therefore, you can download files even if the version isn't later than the version in the destination folder. The command uses the `Save-Help` cmdlet to download and save the help files to the specified folder. The **Force** parameter is required when you have to run a `Save-Help` command more than one time each day. ## PARAMETERS ### -Credential Specifies a user credential. This cmdlet runs the command by using credentials of a user who has permission to access the file system location specified by the **DestinationPath** parameter. This parameter is valid only when the **DestinationPath** or **LiteralPath** parameter is used in the command. This parameter enables you to run `Save-Help` commands that use the **DestinationPath** parameter on remote computers. By providing explicit credentials, you can run the command on a remote computer and access a file share on a third computer without encountering an access denied error or using CredSSP authentication to delegate credentials. Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. If you type a user name, you're prompted to enter the password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DestinationPath Specifies the path of the folder in which the help files are saved. Don't specify a filename or filename extension. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Path Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Indicates that this cmdlet doesn't follow the once-per-day limitation, skips version checking, and downloads files that exceed the 1 GB limit. Without this parameter, only one `Save-Help` command for each module is permitted in each 24-hour period, downloads are limited to 1 GB of uncompressed content per module, and help files for a module are installed only when they're newer than the files on the computer. The once-per-day limit protects the servers that host the help files, and makes it practical for you to add a `Save-Help` command to your PowerShell profile. To save help for a module in multiple UI cultures without the **Force** parameter, include all UI cultures in the same command, such as: `Save-Help -Module PSScheduledJobs -UICulture en-US, fr-FR, pt-BR` ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -FullyQualifiedModule The value can be a module name, a full module specification, or a path to a module file. When the value is a path, the path can be fully qualified or relative. A relative path is resolved relative to the script that contains the using statement. When the value is a name or module specification, PowerShell searches the **PSModulePath** for the specified module. A module specification is a hashtable that has the following keys. - `ModuleName` - **Required** Specifies the module name. - `GUID` - **Optional** Specifies the GUID of the module. - It's also **Required** to specify at least one of the three below keys. - `ModuleVersion` - Specifies a minimum acceptable version of the module. - `MaximumVersion` - Specifies the maximum acceptable version of the module. - `RequiredVersion` - Specifies an exact, required version of the module. This can't be used with the other Version keys. You can't specify the **FullyQualifiedModule** parameter in the same command as a **Module** parameter. the two parameters are mutually exclusive. ```yaml Type: Microsoft.PowerShell.Commands.ModuleSpecification[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -LiteralPath Specifies a path of the destination folder. Unlike the value of the **DestinationPath** parameter, the value of the **LiteralPath** parameter is used exactly as it's typed. No characters are interpreted as wildcard characters. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Module Specifies modules for which this cmdlet downloads help. Enter one or more module names or name patterns in a comma-separated list or in a file that has one module name on each line. Wildcard characters are permitted. You can also pipe module objects from the `Get-Module` cmdlet to `Save-Help`. By default, `Save-Help` downloads help for all modules that support Updatable Help and are installed on the local computer in a location listed in the **PSModulePath** environment variable. To save help for modules that aren't installed on the computer, run a `Get-Module` command on a remote computer. Then pipe the resulting module objects to the `Save-Help` cmdlet or submit the module objects as the value of the **Module** or **InputObject** parameters. If the module that you specify is installed on the computer, you can enter the module name or a module object. If the module isn't installed on the computer, you must enter a module object, such as one returned by the `Get-Module` cmdlet. The **Module** parameter of the `Save-Help` cmdlet doesn't accept the full path of a module file or module manifest file. To save help for a module that's not in a **PSModulePath** location, import the module into the current session before you run the `Save-Help` command. A value of "*" (all) attempts to update help for all modules that are installed on the computer. This includes modules that don't support Updatable Help. This value might generate errors when the command encounters modules that don't support Updatable Help. ```yaml Type: System.Management.Automation.PSModuleInfo[] Parameter Sets: (All) Aliases: Name Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Scope This parameter does nothing in this cmdlet. ```yaml Type: Microsoft.PowerShell.Commands.UpdateHelpScope Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -UICulture Specifies UI culture values for which this cmdlet gets updated help files. Enter one or more language codes, such as `es-ES`, a variable that contains culture objects, or a command that gets culture objects, such as a `Get-Culture` or `Get-UICulture` command. Wildcard characters aren't permitted. By default, `Save-Help` gets help files in the UI culture set for the operating system or its fallback culture. If you specify the **UICulture** parameter, `Save-Help` only looks for help for the specified language. Beginning in PowerShell 7.4, you can use a partial language code, such as `en` to download help in English for any region. ```yaml Type: System.Globalization.CultureInfo[] Parameter Sets: (All) Aliases: Required: False Position: 2 Default value: Current UI culture Accept pipeline input: False Accept wildcard characters: False ``` ### -UseDefaultCredentials Indicates that this cmdlet runs the command, including the web download, with the credentials of the current user. By default, the command runs without explicit credentials. This parameter is effective only when the web download uses NTLM, negotiate, or Kerberos-based authentication. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSModuleInfo You can pipe a module object to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES - To save help for modules in the $PSHOME\Modules folder, start PowerShell by using the Run as administrator option. Only members of the Administrators group on the computer can download help for modules in the $PSHOME\Modules folder. - The saved help for each module consists of one help information (HelpInfo XML) file and one cabinet (.cab) file for the help files each UI culture. You don't have to extract the help files from the cabinet file. The `Update-Help` cmdlet extracts the help files, validates the XML, and then installs the help files and the help information file in a language-specific subfolder of the module folder. - The `Save-Help` cmdlet can save help for modules that aren't installed on the computer. However, because help files are installed in the module folder, the `Update-Help` cmdlet can install updated help file only for modules that are installed on the computer. - If `Save-Help` can't find updated help files for a module, or can't find updated help files in the specified language, it continues silently without displaying an error message. To see which files were saved by the command, specify the **Verbose** parameter. - Modules are the smallest unit of updatable help. You can't save help for a particular cmdlet, only for all cmdlets in module. To find the module that contains a particular cmdlet, use the **ModuleName** property together with the `Get-Command` cmdlet, for example, `(Get-Command \<cmdlet-name\>).ModuleName` - `Save-Help` supports all modules and the core PowerShell snap-ins. It doesn't support any other snap-ins. - The `Update-Help` and `Save-Help` cmdlets use the following ports to download help files: Port 80 for HTTP and port 443 for HTTPS. - The `Update-Help` and `Save-Help` cmdlets aren't supported on Windows Preinstallation Environment (Windows PE). ## RELATED LINKS [Get-Help](Get-Help.md) [Get-Module](Get-Module.md) [Update-Help](Update-Help.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Set-PSDebug.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/set-psdebug?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-PSDebug --- # Set-PSDebug ## SYNOPSIS Turns script debugging features on and off, sets the trace level, and toggles strict mode. ## SYNTAX ### on ``` Set-PSDebug [-Trace <Int32>] [-Step] [-Strict] [<CommonParameters>] ``` ### off ``` Set-PSDebug [-Off] [<CommonParameters>] ``` ## DESCRIPTION The `Set-PSDebug` cmdlet turns script debugging features on and off, sets the trace level, and toggles strict mode. By default, the PowerShell debug features are off. When the **Trace** parameter has a value of `1`, each line of script is traced as it runs. When the parameter has a value of `2`, variable assignments, function calls, and script calls are also traced. If the **Step** parameter is specified, you're prompted before each line of the script runs. ## EXAMPLES ### Example 1: Set the trace level This example sets the trace level to `2`, and then runs a script that displays the numbers 1, 2, and 3. ```powershell Set-PSDebug -Trace 2; foreach ($i in 1..3) {$i} ``` ```Output DEBUG: 1+ Set-PSDebug -Trace 2; foreach ($i in >>>> 1..3) {$i} DEBUG: ! SET $foreach = 'IEnumerator'. DEBUG: 1+ Set-PSDebug -Trace 2; foreach ( >>>> $i in 1..3) {$i} DEBUG: ! SET $i = '1'. DEBUG: 1+ Set-PSDebug -Trace 2; foreach ($i in 1..3) { >>>> $i} 1 DEBUG: 1+ Set-PSDebug -Trace 2; foreach ( >>>> $i in 1..3) {$i} DEBUG: ! SET $i = '2'. DEBUG: 1+ Set-PSDebug -Trace 2; foreach ($i in 1..3) { >>>> $i} 2 DEBUG: 1+ Set-PSDebug -Trace 2; foreach ( >>>> $i in 1..3) {$i} DEBUG: ! SET $i = '3'. DEBUG: 1+ Set-PSDebug -Trace 2; foreach ($i in 1..3) { >>>> $i} 3 DEBUG: 1+ Set-PSDebug -Trace 2; foreach ( >>>> $i in 1..3) {$i} DEBUG: ! SET $foreach = ''. ``` ### Example 2: Turn on stepping This example turns on stepping, and then runs a script that displays the numbers 1, 2, and 3. ```powershell Set-PSDebug -Step; foreach ($i in 1..3) {$i} ``` ```Output Continue with this operation? 1+ Set-PSDebug -Step; foreach ($i in >>>> 1..3) {$i} [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): A DEBUG: 1+ Set-PSDebug -Step; foreach ($i in >>>> 1..3) {$i} 1 2 3 ``` ### Example 3: Use strict mode This example puts PowerShell in strict mode and attempts to access a variable that doesn't have an assigned value. ```powershell Set-PSDebug -Strict; $NewVar ``` ```Output The variable '$NewVar' cannot be retrieved because it has not been set. At line:1 char:22 + Set-PSDebug -Strict; $NewVar ``` ### Example 4: Turn off debug features This example turns off all debugging features, and then runs a script that displays the numbers 1, 2, and 3. ```powershell Set-PSDebug -Off; foreach ($i in 1..3) {$i} ``` ```Output 1 2 3 ``` ## PARAMETERS ### -Off Turns off all script debugging features. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: off Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Step Turns on script stepping. Before each line runs, PowerShell prompts you to stop, continue, or enter a new interpreter level to inspect the state of the script. Specifying the **Step** parameter automatically sets a trace level of `1`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: on Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Strict Specifies that variables must be assigned a value before being referenced in a script. If a variable is referenced before a value is assigned, PowerShell returns an exception error. This is equivalent to `Set-StrictMode -Version 1`. For more information, see [Set-StrictMode](Set-StrictMode.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: on Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Trace Specifies the trace level for each line in a script. Each line is traced as it's run. The acceptable values for this parameter are as follows: - 0: Turn script tracing off. - 1: Trace script lines as they run. - 2: Trace script lines, variable assignments, function calls, and scripts. ```yaml Type: System.Int32 Parameter Sets: on Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES ## RELATED LINKS [about_Debuggers](./About/about_Debuggers.md) [Debug-Process](../Microsoft.PowerShell.Management/Debug-Process.md) [Set-PSBreakpoint](../Microsoft.PowerShell.Utility/Set-PSBreakpoint.md) [Set-StrictMode](Set-StrictMode.md) [Write-Debug](../Microsoft.PowerShell.Utility/Write-Debug.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Set-PSSessionConfiguration.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/set-pssessionconfiguration?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-PSSessionConfiguration --- # Set-PSSessionConfiguration ## SYNOPSIS Changes the properties of a registered session configuration. ## SYNTAX ### NameParameterSet (Default) ``` Set-PSSessionConfiguration [-Name] <String> [-ApplicationBase <String>] [-RunAsCredential <PSCredential>] [-ThreadApartmentState <ApartmentState>] [-ThreadOptions <PSThreadOptions>] [-AccessMode <PSSessionConfigurationAccessMode>] [-UseSharedProcess] [-StartupScript <String>] [-MaximumReceivedDataSizePerCommandMB <Double>] [-MaximumReceivedObjectSizeMB <Double>] [-SecurityDescriptorSddl <String>] [-ShowSecurityDescriptorUI] [-Force] [-NoServiceRestart] [-PSVersion <Version>] [-SessionTypeOption <PSSessionTypeOption>] [-TransportOption <PSTransportOption>] [-ModulesToImport <Object[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### AssemblyNameParameterSet ``` Set-PSSessionConfiguration [-Name] <String> [-AssemblyName] <String> [-ApplicationBase <String>] [-ConfigurationTypeName] <String> [-RunAsCredential <PSCredential>] [-ThreadApartmentState <ApartmentState>] [-ThreadOptions <PSThreadOptions>] [-AccessMode <PSSessionConfigurationAccessMode>] [-UseSharedProcess] [-StartupScript <String>] [-MaximumReceivedDataSizePerCommandMB <Double>] [-MaximumReceivedObjectSizeMB <Double>] [-SecurityDescriptorSddl <String>] [-ShowSecurityDescriptorUI] [-Force] [-NoServiceRestart] [-PSVersion <Version>] [-SessionTypeOption <PSSessionTypeOption>] [-TransportOption <PSTransportOption>] [-ModulesToImport <Object[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### SessionConfigurationFile ``` Set-PSSessionConfiguration [-Name] <String> [-RunAsCredential <PSCredential>] [-ThreadApartmentState <ApartmentState>] [-ThreadOptions <PSThreadOptions>] [-AccessMode <PSSessionConfigurationAccessMode>] [-UseSharedProcess] [-StartupScript <String>] [-MaximumReceivedDataSizePerCommandMB <Double>] [-MaximumReceivedObjectSizeMB <Double>] [-SecurityDescriptorSddl <String>] [-ShowSecurityDescriptorUI] [-Force] [-NoServiceRestart] [-TransportOption <PSTransportOption>] -Path <String> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Set-PSSessionConfiguration` cmdlet changes the properties of the session configurations on the local computer. Use the **Name** parameter to identify the session configuration that you want to change. Use the other parameters to specify new values for the properties of the session configuration. To delete a property value from the configuration, and use the default value, enter an empty string (`""`) or a value of `$null` for the corresponding parameter. Starting in PowerShell 3.0, you can use a session configuration file to define a session configuration. This feature provides a simple and discoverable method for setting and changing the properties of sessions that use the session configuration. To specify a session configuration file, use the **Path** parameter of `Set-PSSessionConfiguration`. For information about session configuration files, see [about_Session_Configuration_Files](About/about_Session_Configuration_Files.md). For information about how to create and modify a session configuration file, see the `New-PSSessionConfigurationFile` cmdlet. Session configurations define the environment of remote sessions (**PSSessions**) that connect to the local computer. Every **PSSession** uses a session configuration. The session configuration determines the features of the **PSSession**, such as the modules that are available in the session, the cmdlets that are permitted to run, the language mode, quotas, and timeouts. The security descriptor of the session configuration determines who can use the session configuration to connect to the local computer. For more information about session configurations, see [about_Session_Configurations](About/about_Session_Configurations.md). To see the properties of a session configuration, use the `Get-PSSessionConfiguration` cmdlet or the WSMan Provider. For more information about the WSMan Provider, type `Get-Help WSMan`. ## EXAMPLES ### Example 1: Create and change a session configuration This example shows how to add and remove a startup script from a configuration. The first command creates the **AdminShell** configuration. The second command adds the `AdminConfig.ps1` script to the configuration. The change is effective when you restart **WinRM**. The third command removes the `AdminConfig.ps1` script from the configuration. ```powershell Register-PSSessionConfiguration -Name "AdminShell" -AssemblyName "C:\Shells\AdminShell.dll" -ConfigurationTypeName "AdminClass" Set-PSSessionConfiguration -Name "AdminShell" -StartupScript "AdminConfig.ps1" Set-PSSessionConfiguration -Name "AdminShell" -StartupScript $null ``` ### Example 2: Display results This example increases the value of the **MaximumReceivedObjectSizeMB** property to `20`. This command also prompts you to restart the **WinRM** service. The change is not effective until the **WinRM** service is restarted. ```powershell Set-PSSessionConfiguration -Name "IncObj" -MaximumReceivedObjectSizeMB 20 ``` ```Output WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin\IncObj\InitializationParameters ParamName ParamValue --------- ---------- psmaximumreceivedobjectsizemb 20 "Restart WinRM service" WinRM service need to be restarted to make the changes effective. Do you want to run the command "Restart-Service winrm"? [Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): y ``` ### Example 3: Display results in different ways In this example, `Set-PSSessionConfiguration` changes the startup script in the **MaintenanceShell** session configuration to `Maintenance.ps1`. The output shows the change and prompts you to restart the **WinRM** service. The response is `y` (yes). `Get-PSSessionConfiguration` gets the **MaintenanceShell** session configuration. The pipeline operator (`|`) sends the results of the command to `Format-List`, which displays all the properties of the configuration object in a list. Next, using the WSMan provider, we view the initialization parameters for the **MaintenanceShell** configuration. `Get-ChildItem` gets the child items in the **InitializationParameters** node for the **MaintenanceShell** plug-in. For more information about the WSMan provider, type `Get-Help WSMan`. ```powershell Set-PSSessionConfiguration -Name "MaintenanceShell" -StartupScript "C:\ps-test\Maintenance.ps1" ``` ```Output WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Plugin\MaintenanceShell\InitializationParameters ParamName ParamValue --------- ---------- startupscript C:\ps-test\Mainte... "Restart WinRM service" WinRM service need to be restarted to make the changes effective. Do you want to run the command "Restart-Service winrm"? [Y] Yes [N] No [S] Suspend [?] Help (default is "Y"): y ``` ```powershell Get-PSSessionConfiguration MaintenanceShell | Format-List -Property * ``` ```Output xmlns : http://schemas.microsoft.com/wbem/wsman/1/config/PluginConfiguration Name : MaintenanceShell Filename : %windir%\system32\pwrshplugin.dll SDKVersion : 1 XmlRenderingType : text lang : en-US PSVersion : 2.0 startupscript : C:\ps-test\Maintenance.ps1 ResourceUri : http://schemas.microsoft.com/powershell/MaintenanceShell SupportsOptions : true ExactMatch : true Capability : {Shell} Permission : ``` ```powershell Get-ChildItem WSMan:\localhost\Plugin\MaintenanceShell\InitializationParameters ``` ```Output ParamName ParamValue --------- ---------- PSVersion 2.0 startupscript C:\ps-test\Maintenance.ps1 ``` ## PARAMETERS ### -AccessMode Enables and disables the session configuration and determines whether it can be used for remote or local sessions on the computer. The acceptable values for this parameter are: - `Disabled`. Disables the session configuration. It cannot be used for remote or local access to the computer. This value sets the **Enabled** property of the session configuration (`WSMan:\<ComputerName>\PlugIn\<SessionConfigurationName>\Enabled`) to `False`. - `Local`. Adds a **Network_Deny_All** entry to security descriptor of the session configuration. Users of the local computer can use the session configuration to create a local loopback session on the same computer, but remote users are denied access. - `Remote`. Removes **Deny_All** and **Network_Deny_All** entries from the security descriptors of the session configuration. Users of local and remote computers can use the session configuration to create sessions and run commands on this computer. The default value is **Remote**. Other cmdlets can override the value of this parameter later. For example, the `Enable-PSRemoting` cmdlet enables all session configurations on the computer and permits remote access to them, and the `Disable-PSRemoting` cmdlet permits only local access to all session configurations on the computer. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.Runspaces.PSSessionConfigurationAccessMode Parameter Sets: (All) Aliases: Accepted values: Disabled, Local, Remote Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ApplicationBase Specifies the path of the assembly file (`*.dll`) that is specified in the value of the **AssemblyName** parameter. ```yaml Type: System.String Parameter Sets: NameParameterSet, AssemblyNameParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -AssemblyName Specifies the assembly name. This cmdlet creates a session configuration based on a class that is defined in an assembly. Enter the filename or full path of an assembly `.dll` file that defines a session configuration. If you enter only the file name, you can enter the path in the value of the **ApplicationBase** parameter. ```yaml Type: System.String Parameter Sets: AssemblyNameParameterSet Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ConfigurationTypeName Specifies the type of the session configuration that is defined in the assembly in the **AssemblyName** parameter. The type that you specify must implement the **System.Management.Automation.Remoting.PSSessionConfiguration** class. This parameter is required when you specify an assembly name. ```yaml Type: System.String Parameter Sets: AssemblyNameParameterSet Aliases: Required: True Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Suppresses all user prompts, and restarts the **WinRM** service without prompting. Restarting the service makes the configuration change effective. To prevent a restart and suppress the restart prompt, use the **NoServiceRestart** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumReceivedDataSizePerCommandMB Specifies the limit on the amount of data that can be sent to this computer in any single remote command. Enter the data size in megabytes (MB). The default is `50`. If a data size limit is defined in the configuration type that is specified in the **ConfigurationTypeName** parameter, the limit in the configuration type is used. The value of this parameter is ignored. ```yaml Type: System.Nullable`1[System.Double] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumReceivedObjectSizeMB Specifies the limits on the amount of data that can be sent to this computer in any single object. Enter the data size in megabytes. The default is `10`. If an object size limit is defined in the configuration type that is specified in the **ConfigurationTypeName** parameter, the limit in the configuration type is used. The value of this parameter is ignored. ```yaml Type: System.Nullable`1[System.Double] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ModulesToImport Specifies the modules and snap-ins that are automatically imported into sessions that use the session configuration. Enter the module and snap-in names. By default, only the **Microsoft.PowerShell.Core** module is imported into sessions, but unless the cmdlets are excluded, you can use the `Import-Module` and `Add-PSSnapin` cmdlets to add modules and snap-ins to the session. The modules specified in this parameter value are imported in additions to modules specified in the session configuration file (`New-PSSessionConfigurationFile`). However, settings in the session configuration file can hide the commands exported by modules or prevent users from using them. The modules specified in this parameter value replace the list of modules specified with the **ModulesToImport** parameter of the `Register-PSSessionConfiguration` cmdlet. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Object[] Parameter Sets: NameParameterSet, AssemblyNameParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies the name of the session configuration that you want to change. You cannot use this parameter to change the name of the session configuration. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -NoServiceRestart Does not restart the **WinRM** service, and suppresses the prompt to restart the service. By default, when you run `Set-PSSessionConfiguration`, you are prompted to restart the **WinRM** service to make the new session configuration effective. Until the **WinRM** service is restarted, the new session configuration is not effective. To restart the **WinRM** service without prompting, use the **Force** parameter. To restart the **WinRM** service manually, use the `Restart-Service` cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path of a session configuration file (`.pssc`), such as one created by the `New-PSSessionConfigurationFile` cmdlet. If you omit the path, the default is the current directory. For information about how to modify a session configuration file, see the help topic for the `New-PSSessionConfigurationFile` cmdlet. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.String Parameter Sets: SessionConfigurationFile Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PSVersion Specifies the version of PowerShell in sessions that use this session configuration. The value of this parameter takes precedence over the value of the **PowerShellVersion** key in the session configuration file. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Version Parameter Sets: NameParameterSet, AssemblyNameParameterSet Aliases: PowerShellVersion Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RunAsCredential Specifies credentials for commands in the session. By default, commands run with the permissions of the current user. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SecurityDescriptorSddl Specifies a different Security Descriptor Definition Language (SDDL) string for the configuration. This string determines the permissions that are required to use the new session configuration. To use a session configuration in a session, users must have at least `Execute(Invoke)` permission for the configuration. To use the default security descriptor for the configuration, enter an empty string (`""`) or a value of `$null`. The default is the root SDDL in the `WSMan:` drive. If the security descriptor is complex, consider using the **ShowSecurityDescriptorUI** parameter instead of this one. You cannot use both parameters in the same command. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SessionTypeOption Specifies type-specific options for the session configuration. Enter a session type options object, such as the **PSWorkflowExecutionOption** object that the `New-PSWorkflowExecutionOption` cmdlet returns. The options of sessions that use the session configuration are determined by the values of session options and the session configuration options. Unless specified, options set in the session, such as with the `New-PSSessionOption` cmdlet, take precedence over options set in the session configuration. However, session option values cannot exceed maximum values set in the session configuration. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.PSSessionTypeOption Parameter Sets: NameParameterSet, AssemblyNameParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ShowSecurityDescriptorUI When this parameter is used the cmdlet opens a property sheet that helps you create a new SDDL for the session configuration. The property sheet appears after you run the `Set-PSSessionConfiguration` command and then restart the **WinRM** service. When you set permissions to the configuration, remember that users must have at least `Execute(Invoke)` permission to use the session configuration in a session. You cannot use the **SecurityDescriptorSDDL** parameter and this parameter in the same command. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -StartupScript Specifies the startup script for the configuration. Enter the fully qualified path of a PowerShell script. The specified script runs in the new session that uses the session configuration. To delete a startup script from a session configuration, enter an empty string (`""`) or a value of `$null`. You can use a startup script to further configure the user session. If the script generates an error, even a non-terminating error, the session is not created and the `New-PSSession` command fails. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ThreadApartmentState Specifies the apartment state of the threading module to be used. Acceptable values are: - `Unknown` - `MTA` - `STA` ```yaml Type: System.Threading.ApartmentState Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ThreadOptions Specifies the thread options setting in the configuration. This setting defines how threads are created and used when a command is executed in the session. The acceptable values for this parameter are: - `Default` - `ReuseThread` - `UseCurrentThread` - `UseNewThread` The default value is `UseCurrentThread`. For more information, see [PSThreadOptions Enumeration](/dotnet/api/system.management.automation.runspaces.psthreadoptions). ```yaml Type: System.Management.Automation.Runspaces.PSThreadOptions Parameter Sets: (All) Aliases: Accepted values: Default, UseNewThread, ReuseThread, UseCurrentThread Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TransportOption Specifies the transport options for the session configuration. Enter a transport options object, such as the **WSManConfigurationOption** object that the `New-PSTransportOption` cmdlet returns. The options of sessions that use the session configuration are determined by the values of session options and the session configuration options. Unless specified, options set in the session, such as with the `New-PSSessionOption` cmdlet, take precedence over options set in the session configuration. However, session option values cannot exceed maximum values set in the session configuration. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.PSTransportOption Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSharedProcess Use only one process to host all sessions that are started by the same user and use the same session configuration. By default, each session is hosted in its own process. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.WSMan.Management.WSManConfigLeafElement ## NOTES This cmdlet is only available on Windows platforms. To run this cmdlet, start PowerShell by using the **Run as administrator** option. The `Set-PSSessionConfiguration` cmdlet does not change the configuration name and the **WSMan** provider does not support the `Rename-Item` cmdlet. To change the name of a session configuration, use the `Unregister-PSSessionConfiguration` cmdlet to delete the configuration and then use the `Register-PSSessionConfiguration` cmdlet to create and register a new session configuration. You can use the `Set-PSSessionConfiguration` cmdlet to change the default `Microsoft.PowerShell` and `Microsoft.PowerShell32` session configurations. They are not protected. To revert to the original version of a default session configuration, use the `Unregister-PSSessionConfiguration` cmdlet to delete the default session configuration and then use the `Enable-PSRemoting` cmdlet to restore it. The properties of a session configuration object vary with the options set for the session configuration and the values of those options. Also, session configurations that use a session configuration file have additional properties. You can use commands in the `WSMan:` drive to change the properties of session configurations. However, you cannot use the `WSMan:` drive in PowerShell 2.0 to change session configuration properties that are introduced in PowerShell 3.0, such as **OutputBufferingMode**. Windows PowerShell 2.0 commands do not generate an error, but they are ineffective. To change properties introduced in PowerShell 3.0, use the `WSMan:` drive in PowerShell 3.0 or later. ## RELATED LINKS [Disable-PSSessionConfiguration](Disable-PSSessionConfiguration.md) [Enable-PSSessionConfiguration](Enable-PSSessionConfiguration.md) [Get-PSSessionConfiguration](Get-PSSessionConfiguration.md) [New-PSSessionConfigurationFile](New-PSSessionConfigurationFile.md) [New-PSSessionOption](New-PSSessionOption.md) [New-PSTransportOption](New-PSTransportOption.md) [Register-PSSessionConfiguration](Register-PSSessionConfiguration.md) [Test-PSSessionConfigurationFile](Test-PSSessionConfigurationFile.md) [Unregister-PSSessionConfiguration](Unregister-PSSessionConfiguration.md) [WSMan Provider](../Microsoft.WsMan.Management/About/about_WSMan_Provider.md) [about_Session_Configurations](About/about_Session_Configurations.md) [about_Session_Configuration_Files](About/about_Session_Configuration_Files.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Set-StrictMode.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/set-strictmode?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-StrictMode --- # Set-StrictMode ## SYNOPSIS Establishes and enforces coding rules in expressions, scripts, and script blocks. ## SYNTAX ### Version (Default) ``` Set-StrictMode -Version <Version> [<CommonParameters>] ``` ### Off ``` Set-StrictMode [-Off] [<CommonParameters>] ``` ## DESCRIPTION The `Set-StrictMode` cmdlet configures strict mode for the current scope and all child scopes, and turns it on and off. When strict mode is on, PowerShell generates a terminating error when the content of an expression, script, or script block violates basic best-practice coding rules. Use the **Version** parameter to determine the coding rules to enforce. `Set-PSDebug -Strict` cmdlet turns on strict mode for the global scope. `Set-StrictMode` affects only the current scope and its child scopes. Then, you can use it in a script or function to override the setting inherited from the global scope. When `Set-StrictMode` is off, PowerShell has the following behaviors: - Uninitialized variables are assumed to have a value of `0` (zero) or `$null`, depending on type - References to non-existent properties return `$null` - Results of improper function syntax vary with the error conditions - Attempting to retrieve a value using an invalid index in an array returns `$null` ## EXAMPLES ### Example 1: Turn on strict mode as version 1.0 ```powershell # Strict mode is off by default. $a -gt 5 ``` ```Output False ``` ```powershell Set-StrictMode -Version 1.0 $a -gt 5 ``` ```Output InvalidOperation: The variable '$a' cannot be retrieved because it has not been set. ``` With strict mode set to version `1.0`, attempts to reference variables that aren't initialized fail. ### Example 2: Turn on strict mode as version 2.0 ```powershell # Strict mode is off by default. function add ($a, $b) { '$a = ' + $a '$b = ' + $b '$a+$b = ' + ($a + $b) } add 3 4 ``` ```Output $a = 3 $b = 4 $a+$b = 7 ``` ```powershell add(3,4) ``` ```Output $a = 3 4 $b = $a+$b = 3 4 ``` ```powershell Set-StrictMode -Version 2.0 add(3,4) ``` ```Output InvalidOperation: 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. ``` ```powershell Set-StrictMode -Off $string = "This is a string." $null -eq $string.Month ``` ```Output True ``` ```powershell Set-StrictMode -Version 2.0 $string = "This is a string." $null -eq $string.Month ``` ```Output PropertyNotFoundException: The property 'Month' cannot be found on this object. Verify that the property exists. ``` This command turns strict mode on and sets it to version `2.0`. As a result, PowerShell returns an error if you use method syntax, which uses parentheses and commas, for a function call or reference uninitialized variables or non-existent properties. The sample output shows the effect of version `2.0` strict mode. Without version `2.0` strict mode, the `(3,4)` value is interpreted as a single array object to which nothing is added. With version `2.0` strict mode, it's correctly interpreted as faulty syntax for submitting two values. Without version `2.0`, the reference to the non-existent **Month** property of a string returns only `$null`. With version `2.0`, it's interpreted correctly as a reference error. ### Example 3: Turn on strict mode as version 3.0 With strict mode set to **Off**, invalid or out of bounds indexes result return null values. ```powershell # Strict mode is off by default. $a = @(1) $null -eq $a[2] $null -eq $a['abc'] ``` ```Output True True ``` ```powershell Set-StrictMode -Version 3.0 $a = @(1) $null -eq $a[2] $null -eq $a['abc'] ``` ```Output OperationStopped: Index was outside the bounds of the array. InvalidArgument: Cannot convert value "abc" to type "System.Int32". Error: "Input string was not in a correct format." ``` With strict mode set to version `3` or higher, invalid or out of bounds indexes result in errors. ## PARAMETERS ### -Off Indicates that this cmdlet turns strict mode off for the current scope and all child scopes. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Off Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Version Specifies the conditions that cause an error in strict mode. This parameter accepts any valid PowerShell version number. Any number higher than `3` is treated as `Latest`. The value supplied must be the string `Latest` or a string that can be converted to a **System.Version** type. The version must match a valid release version of PowerShell. The effective values for this parameter are: - `1.0` - Prohibits references to uninitialized variables, except for uninitialized variables in strings. - `2.0` - Prohibits references to uninitialized variables. This includes uninitialized variables in strings. - Prohibits references to non-existent properties of an object. - Prohibits function calls that use the syntax for calling methods. - `3.0` - Prohibits references to uninitialized variables. This includes uninitialized variables in strings. - Prohibits references to non-existent properties of an object. - Prohibits function calls that use the syntax for calling methods. - Prohibit out of bounds or unresolvable array indexes. - `Latest` - Selects the latest version available. The latest version is the most strict. Use this value to make sure that scripts use the strictest available version, even when new versions are added to PowerShell. > [!CAUTION] > Using `Latest` for **Version** in scripts isn't deterministic. The meaning of `Latest` can change > in new releases of PowerShell. A script written for an older version of PowerShell that uses > `Set-StrictMode -Version Latest` is subject to more restrictive rules when run in a newer version > of PowerShell. ```yaml Type: System.Version Parameter Sets: Version Aliases: v Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES While the **Version** parameter accepts values greater than `3.0`, there are no additional rules defined for anything higher than `3.0`. `Set-StrictMode` is effective only in the scope it's set in and in its child scopes. For more information about scopes in PowerShell, see [about_Scopes](about/about_Scopes.md). ## RELATED LINKS [Set-PSDebug](Set-PSDebug.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Start-Job.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 09/29/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/start-job?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Start-Job --- # Start-Job ## SYNOPSIS Starts a PowerShell background job. ## SYNTAX ### ComputerName (Default) ``` Start-Job [-Name <String>] [-ScriptBlock] <ScriptBlock> [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [[-InitializationScript] <ScriptBlock>] [-WorkingDirectory <String>] [-RunAs32] [-PSVersion <Version>] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>] ``` ### DefinitionName ``` Start-Job [-DefinitionName] <String> [[-DefinitionPath] <String>] [[-Type] <String>] [-WorkingDirectory <String>] [<CommonParameters>] ``` ### FilePathComputerName ``` Start-Job [-Name <String>] [-Credential <PSCredential>] [-FilePath] <String> [-Authentication <AuthenticationMechanism>] [[-InitializationScript] <ScriptBlock>] [-WorkingDirectory <String>] [-RunAs32] [-PSVersion <Version>] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>] ``` ### LiteralFilePathComputerName ``` Start-Job [-Name <String>] [-Credential <PSCredential>] -LiteralPath <String> [-Authentication <AuthenticationMechanism>] [[-InitializationScript] <ScriptBlock>] [-WorkingDirectory <String>] [-RunAs32] [-PSVersion <Version>] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Start-Job` cmdlet starts a PowerShell background job on the local computer. A PowerShell background job runs a command without interacting with the current session. When you start a background job, a job object returns immediately, even if the job takes an extended time to finish. You can continue to work in the session without interruption while the job runs. The job object contains useful information about the job, but it doesn't contain the job results. When the job finishes, use the `Receive-Job` cmdlet to get the results of the job. For more information about background jobs, see [about_Jobs](./About/about_Jobs.md). To run a background job on a remote computer, use the **AsJob** parameter that is available on many cmdlets, or use the `Invoke-Command` cmdlet to run a `Start-Job` command on the remote computer. For more information, see [about_Remote_Jobs](./About/about_Remote_Jobs.md). Starting in PowerShell 3.0, `Start-Job` can start instances of custom job types, such as scheduled jobs. For information about how to use `Start-Job` to start jobs with custom types, see the help documents for the job type feature. Beginning in PowerShell 6.0, you can start jobs using the ampersand (`&`) background operator. The functionality of the background operator is similar to `Start-Job`. Both methods to start a job create a **PSRemotingJob** job object. For more information about using the ampersand (`&`), see [about_Operators](./about/about_operators.md#background-operator-). PowerShell 7 introduced the **WorkingDirectory** parameter that specifies a background job's initial working directory. If the parameter isn't specified, `Start-Job` defaults to the current working directory of the caller that started the job. > [!NOTE] > Creating an out-of-process background job with `Start-Job` is not supported in the scenario where > PowerShell is being hosted in other applications, such as the PowerShell Azure Functions. > > This is by design because `Start-Job` depends on the `pwsh` executable to be available under > `$PSHOME` to start an out-of-process background job, but when an application is hosting > PowerShell, it's directly using the PowerShell NuGet SDK packages and won't have `pwsh` shipped > along. > > The substitute in that scenario is `Start-ThreadJob` from the module **[ThreadJob](https://www.powershellgallery.com/packages/ThreadJob)**. ## EXAMPLES ### Example 1: Start a background job This example starts a background job that runs on the local computer. ```powershell Start-Job -ScriptBlock { Get-Process -Name pwsh } ``` ```Output Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 1 Job1 BackgroundJob Running True localhost Get-Process -Name pwsh ``` `Start-Job` uses the **ScriptBlock** parameter to run `Get-Process` as a background job. The **Name** parameter specifies to find PowerShell processes, `pwsh`. The job information is displayed and PowerShell returns to a prompt while the job runs in the background. To view the job's output, use the `Receive-Job` cmdlet. For example, `Receive-Job -Id 1`. ### Example 2: Use the background operator to start a background job This example uses the ampersand (`&`) background operator to start a background job on the local computer. The job gets the same result as `Start-Job` in Example 1. ```powershell Get-Process -Name pwsh & ``` ```Output Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 5 Job5 BackgroundJob Running True localhost Microsoft.PowerShell.Man... ``` `Get-Process` uses the **Name** parameter to specify PowerShell processes, `pwsh`. The ampersand (`&`) runs the command as a background job. The job information is displayed and PowerShell returns to a prompt while the job runs in the background. To view the job's output, use the `Receive-Job` cmdlet. For example, `Receive-Job -Id 5`. ### Example 3: Start a job using Invoke-Command This example runs a job on multiple computers. The job is stored in a variable and is executed by using the variable name on the PowerShell command line. ```powershell $jobWRM = Invoke-Command -ComputerName (Get-Content -Path C:\Servers.txt) -ScriptBlock { Get-Service -Name WinRM } -JobName WinRM -ThrottleLimit 16 -AsJob ``` A job that uses `Invoke-Command` is created and stored in the `$jobWRM` variable. `Invoke-Command` uses the **ComputerName** parameter to specify the computers where the job runs. `Get-Content` gets the server names from the `C:\Servers.txt` file. The **ScriptBlock** parameter specifies a command that `Get-Service` gets the **WinRM** service. The **JobName** parameter specifies a friendly name for the job, **WinRM**. The **ThrottleLimit** parameter limits the number of concurrent commands to 16. The **AsJob** parameter starts a background job that runs the command on the servers. ### Example 4: Get job information This example gets information about a job and displays the results of a completed job that was run on the local computer. ```powershell $j = Start-Job -ScriptBlock { Get-WinEvent -Log System } -Credential Domain01\User01 $j | Select-Object -Property * ``` ```Output State : Completed HasMoreData : True StatusMessage : Location : localhost Command : Get-WinEvent -Log System JobStateInfo : Completed Finished : System.Threading.ManualResetEvent InstanceId : 27ce3fd9-40ed-488a-99e5-679cd91b9dd3 Id : 18 Name : Job18 ChildJobs : {Job19} PSBeginTime : 8/8/2019 14:41:57 PSEndTime : 8/8/2019 14:42:07 PSJobTypeName : BackgroundJob Output : {} Error : {} Progress : {} Verbose : {} Debug : {} Warning : {} Information : {} ``` `Start-Job` uses the **ScriptBlock** parameter to run a command that specifies `Get-WinEvent` to get the **System** log. The **Credential** parameter specifies a domain user account with permission to run the job on the computer. The job object is stored in the `$j` variable. The object in the `$j` variable is sent down the pipeline to `Select-Object`. The **Property** parameter specifies an asterisk (`*`) to display all the job object's properties. ### Example 5: Run a script as a background job In this example, a script on the local computer is run as a background job. ```powershell Start-Job -FilePath C:\Scripts\Sample.ps1 ``` `Start-Job` uses the **FilePath** parameter to specify a script file that's stored on the local computer. ### Example 6: Get a process using a background job This example uses a background job to get a specified process by name. ```powershell Start-Job -Name PShellJob -ScriptBlock { Get-Process -Name powershell } ``` `Start-Job` uses the **Name** parameter to specify a friendly job name, **PShellJob**. The **ScriptBlock** parameter specifies `Get-Process` to get processes with the name `powershell`. ### Example 7: Collect and save data by using a background job This example starts a job that collects a large amount of map data and then saves it in a `.tif` file. ```powershell Start-Job -Name GetMappingFiles -InitializationScript {Import-Module -Name MapFunctions} -ScriptBlock { Get-Map -Name * | Set-Content -Path D:\Maps.tif } ``` `Start-Job` uses the **Name** parameter to specify a friendly job name, **GetMappingFiles**. The **InitializationScript** parameter runs a script block that imports the **MapFunctions** module. The **ScriptBlock** parameter runs `Get-Map` and `Set-Content` saves the data in the location specified by the **Path** parameter. ### Example 8: Pass input to a background job This example uses the `$input` automatic variable to process an input object. Use `Receive-Job` to view the job's output. ```powershell Start-Job -ScriptBlock { Get-Content -Path $input } -InputObject "C:\Servers.txt" Receive-Job -Name Job45 -Keep ``` ```Output Server01 Server02 Server03 Server04 ``` `Start-Job` uses the **ScriptBlock** parameter to run `Get-Content` with the `$input` automatic variable. The `$input` variable gets objects from the **InputObject** parameter. `Receive-Job` uses the **Name** parameter to specify the job and outputs the results. The **Keep** parameter saves the job output so it can be viewed again during the PowerShell session. ### Example 9: Set the working directory for a background job The **WorkingDirectory** allows you to specify an alternate directory for a job from which you can run scripts or open files. In this example, the background job specifies a working directory that's different than the current directory location. ``` PS C:\Test> Start-Job -WorkingDirectory C:\Test\Scripts { $PWD } | Receive-Job -AutoRemoveJob -Wait Path ---- C:\Test\Scripts ``` This example's current working directory is `C:\Test`. `Start-Job` uses the **WorkingDirectory** parameter to specify the job's working directory. The **ScriptBlock** parameter uses `$PWD` to display the job's working directory. `Receive-Job` displays the background job's output. **AutoRemoveJob** deletes the job and **Wait** suppresses the command prompt until all results are received. ### Example 10: Use the ArgumentList parameter to specify an array This example uses the **ArgumentList** parameter to specify an array of arguments. The array is a comma-separated list of process names. ```powershell Start-Job -ScriptBlock { Get-Process -Name $args } -ArgumentList powershell, pwsh, notepad ``` ```Output Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 1 Job1 BackgroundJob Running True localhost Get-Process -Name $args ``` The `Start-Job` cmdlet uses the **ScriptBlock** parameter to run a command. `Get-Process` uses the **Name** parameter to specify the automatic variable `$args`. The **ArgumentList** parameter passes the array of process names to `$args`. The process names powershell, pwsh, and notepad are processes running on the local computer. To view the job's output, use the `Receive-Job` cmdlet. For example, `Receive-Job -Id 1`. ### Example 11: Run job in a Windows PowerShell 5.1 This example uses the **PSVersion** parameter with value **5.1** to run job in a Windows PowerShell 5.1 session. ```powershell $PSVersionTable.PSVersion ``` ```Output Major Minor Patch PreReleaseLabel BuildLabel ----- ----- ----- --------------- ---------- 7 0 0 rc.1 ``` ```powershell $job = Start-Job -ScriptBlock { $PSVersionTable.PSVersion } -PSVersion 5.1 Receive-Job -Job $job ``` ```Output Major Minor Build Revision ----- ----- ----- -------- 5 1 14393 3383 ``` ## PARAMETERS ### -ArgumentList Specifies an array of arguments, or parameter values, for the script that is specified by the **FilePath** parameter or a command specified with the **ScriptBlock** parameter. Arguments must be passed to **ArgumentList** as single-dimension array argument. For example, a comma-separated list. For more information about the behavior of **ArgumentList**, see [about_Splatting](about/about_Splatting.md#splatting-with-arrays). ```yaml Type: System.Object[] Parameter Sets: ComputerName, FilePathComputerName, LiteralFilePathComputerName Aliases: Args Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Authentication Specifies the mechanism that is used to authenticate user credentials. The acceptable values for this parameter are as follows: - Default - Basic - Credssp - Digest - Kerberos - Negotiate - NegotiateWithImplicitCredential The default value is Default. CredSSP authentication is available only in Windows Vista, Windows Server 2008, and later versions of the Windows operating system. For more information about the values of this parameter, see [AuthenticationMechanism](/dotnet/api/system.management.automation.runspaces.authenticationmechanism). > [!CAUTION] > Credential Security Support Provider (CredSSP) authentication, in which the user's credentials are > passed to a remote computer to be authenticated, is designed for commands that require > authentication on more than one resource, such as accessing a remote network share. This mechanism > increases the security risk of the remote operation. If the remote computer is compromised, the > credentials that are passed to it can be used to control the network session. ```yaml Type: System.Management.Automation.Runspaces.AuthenticationMechanism Parameter Sets: ComputerName, FilePathComputerName, LiteralFilePathComputerName Aliases: Accepted values: Default, Basic, Negotiate, NegotiateWithImplicitCredential, Credssp, Digest, Kerberos Required: False Position: Named Default value: Default Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to perform this action. If the **Credential** parameter isn't specified, the command uses the current user's credentials. Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. If you type a user name, you're prompted to enter the password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: ComputerName, FilePathComputerName, LiteralFilePathComputerName Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: False Accept wildcard characters: False ``` ### -DefinitionName Specifies the definition name of the job that this cmdlet starts. Use this parameter to start custom job types that have a definition name, such as scheduled jobs. When you use `Start-Job` to start an instance of a scheduled job, the job starts immediately, regardless of job triggers or job options. The resulting job instance is a scheduled job, but it isn't saved to disk like triggered scheduled jobs. You can't use the **ArgumentList** parameter of `Start-Job` to provide values for parameters of scripts that run in a scheduled job. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.String Parameter Sets: DefinitionName Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DefinitionPath Specifies path of the definition for the job that this cmdlet starts. Enter the definition path. The concatenation of the values of the **DefinitionPath** and **DefinitionName** parameters is the fully qualified path of the job definition. Use this parameter to start custom job types that have a definition path, such as scheduled jobs. For scheduled jobs, the value of the **DefinitionPath** parameter is `$HOME\AppData\Local\Windows\PowerShell\ScheduledJob`. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.String Parameter Sets: DefinitionName Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FilePath Specifies a local script that `Start-Job` runs as a background job. Enter the path and file name of the script or use the pipeline to send a script path to `Start-Job`. The script must be on the local computer or in a folder that the local computer can access. When you use this parameter, PowerShell converts the contents of the specified script file to a script block and runs the script block as a background job. ```yaml Type: System.String Parameter Sets: FilePathComputerName Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InitializationScript Specifies commands that run before the job starts. To create a script block, enclose the commands in curly braces (`{}`). Use this parameter to prepare the session in which the job runs. For example, you can use it to add functions, snap-ins, and modules to the session. ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: ComputerName, FilePathComputerName, LiteralFilePathComputerName Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies input to the command. Enter a variable that contains the objects, or type a command or expression that generates the objects. In the value of the **ScriptBlock** parameter, use the `$input` automatic variable to represent the input objects. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: ComputerName, FilePathComputerName, LiteralFilePathComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -LiteralPath Specifies a local script that this cmdlet runs as a background job. Enter the path of a script on the local computer. `Start-Job` uses the value of the **LiteralPath** parameter exactly as it's typed. No characters are interpreted as wildcard characters. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String Parameter Sets: LiteralFilePathComputerName Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies a friendly name for the new job. You can use the name to identify the job to other job cmdlets, such as the `Stop-Job` cmdlet. The default friendly name is `Job#`, where `#` is an ordinal number that is incremented for each job. ```yaml Type: System.String Parameter Sets: ComputerName, FilePathComputerName, LiteralFilePathComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PSVersion Specifies a version of PowerShell to use for running the job. When the value of **PSVersion** is **5.1** The job is run in a Windows PowerShell 5.1 session. For any other value, the job is run using the current version of PowerShell. This parameter was added in PowerShell 7 and only works on Windows. ```yaml Type: System.Version Parameter Sets: ComputerName, FilePathComputerName, LiteralFilePathComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RunAs32 Beginning with PowerShell 7, the **RunAs32** parameter doesn't work on 64-bit PowerShell (`pwsh`). If **RunAs32** is specified in 64-bit PowerShell, `Start-Job` throws a terminating exception error. To start a 32-bit PowerShell (`pwsh`) process with **RunAs32**, you need to have the 32-bit PowerShell installed. In 32-bit PowerShell, **RunAs32** forces the job to run in a 32-bit process, even on a 64-bit operating system. On 64-bit versions of Windows 7 and Windows Server 2008 R2, when the `Start-Job` command includes the **RunAs32** parameter, you can't use the **Credential** parameter to specify the credentials of another user. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerName, FilePathComputerName, LiteralFilePathComputerName Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ScriptBlock Specifies the commands to run in the background job. To create a script block, enclose the commands in curly braces (`{}`). Use the `$input` automatic variable to access the value of the **InputObject** parameter. This parameter is required. ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: ComputerName Aliases: Command Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Type Specifies the custom type for jobs started by `Start-Job`. Enter a custom job type name, such as PSScheduledJob for scheduled jobs or PSWorkflowJob for workflows jobs. This parameter isn't valid for standard background jobs. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.String Parameter Sets: DefinitionName Aliases: Required: False Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WorkingDirectory Specifies the initial working directory of the background job. If the parameter isn't specified, the job runs from the default location. The default location is the current working directory of the caller that started the job. This parameter was introduced in PowerShell 7. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: $HOME on Unix (macOS, Linux) and $HOME\Documents on Windows Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe an object with the **Name** property to the **Name** parameter to this cmdlet. For example, you can pipe a **FileInfo** object from `Get-ChildItem`. ## OUTPUTS ### System.Management.Automation.PSRemotingJob This cmdlet returns a **PSRemotingJob** object representing the job that it started. ## NOTES PowerShell includes the following aliases for `Start-Job`: - All platforms: - `sajb` To run in the background, `Start-Job` runs in its own session in the current session. When you use the `Invoke-Command` cmdlet to run a `Start-Job` command in a session on a remote computer, `Start-Job` runs in a session in the remote session. ## RELATED LINKS [about_Arrays](./about/about_arrays.md) [about_Automatic_Variables](./about/about_automatic_variables.md) [about_Jobs](./About/about_Jobs.md) [about_Job_Details](./About/about_Job_Details.md) [about_Remote_Jobs](./About/about_Remote_Jobs.md) [Get-Job](Get-Job.md) [Invoke-Command](Invoke-Command.md) [Receive-Job](Receive-Job.md) [Remove-Job](Remove-Job.md) [Stop-Job](Stop-Job.md) [Wait-Job](Wait-Job.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Stop-Job.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 09/29/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/stop-job?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Stop-Job --- # Stop-Job ## SYNOPSIS Stops a PowerShell background job. ## SYNTAX ### SessionIdParameterSet (Default) ``` Stop-Job [-PassThru] [-Id] <Int32[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### JobParameterSet ``` Stop-Job [-Job] <Job[]> [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### NameParameterSet ``` Stop-Job [-PassThru] [-Name] <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### InstanceIdParameterSet ``` Stop-Job [-PassThru] [-InstanceId] <Guid[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### StateParameterSet ``` Stop-Job [-PassThru] [-State] <JobState> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### FilterParameterSet ``` Stop-Job [-PassThru] [-Filter] <Hashtable> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Stop-Job` cmdlet stops PowerShell background jobs that are in progress. You can use this cmdlet to stop all jobs or stop selected jobs based on their name, ID, instance ID, or state, or by passing a job object to `Stop-Job`. You can use `Stop-Job` to stop background jobs, such as those that were started by using the `Start-Job` cmdlet or the **AsJob** parameter of any cmdlet. When you stop a background job, PowerShell completes all tasks that are pending in that job queue and then ends the job. No new tasks are added to the queue after this command is submitted. This cmdlet does not delete background jobs. To delete a job, use the `Remove-Job` cmdlet. Starting in Windows PowerShell 3.0, `Stop-Job` also stops custom job types, such as **WorkflowJobs** and instances of **ScheduledJobs**. To enable `Stop-Job` to stop a job with custom job type, import the module that supports the custom job type into the session before you run a `Stop-Job` command, either by using the `Import-Module` cmdlet or by using or getting a cmdlet in the module. For information about a particular custom job type, see the documentation of the custom job type feature. ## EXAMPLES ### Example 1: Stop a job on a remote computer with Invoke-Command ```powershell $s = New-PSSession -ComputerName Server01 -Credential Domain01\Admin02 $j = Invoke-Command -Session $s -ScriptBlock {Start-Job -ScriptBlock {Get-EventLog -LogName System}} Invoke-Command -Session $s -ScriptBlock { Stop-Job -Job $Using:j } ``` This example shows how to use the `Stop-Job` cmdlet to stop a job that is running on a remote computer. Because the job was started with the `Invoke-Command` cmdlet to run a `Start-Job` command remotely, the job object is stored on the remote computer. You must use another `Invoke-Command` command to run a `Stop-Job` command remotely. For more information about remote background jobs, see about_Remote_Jobs. The first command creates a PowerShell session (**PSSession**) on the Server01 computer, and then stores the session object in the `$s` variable. The command uses the credentials of a domain administrator. The second command uses the `Invoke-Command` cmdlet to run a `Start-Job` command in the session. The command in the job gets all of the events in the System event log. The resulting job object is stored in the `$j` variable. The third command stops the job. It uses the `Invoke-Command` cmdlet to run a `Stop-Job` command in the **PSSession** on Server01. Because the job objects are stored in `$j`, which is a variable on the local computer, the command uses the `Using:` scope modifier to identify `$j` as a local variable. For more information about the `Using:` scope modifier, see [about_Remote_Variables](about/about_Remote_Variables.md). When the command finishes, the job is stopped and the **PSSession** in `$s` is available for use. ### Example 2: Stop a background job ```powershell Stop-Job -Name "Job1" ``` This command stops the `Job1` background job. ### Example 3: Stop several background jobs ```powershell Stop-Job -Id 1, 3, 4 ``` This command stops three jobs. It identifies them by their **IDs**. ### Example 4: Stop all background jobs ```powershell Get-Job | Stop-Job ``` This command stops all of the background jobs in the current session. ### Example 5: Stop all blocked background jobs ```powershell Stop-Job -State Blocked ``` This command stops all the jobs that are blocked. ### Example 6: Stop a job by instance ID ```powershell Get-Job | Format-Table ID, Name, Command, @{Label="State";Expression={$_.JobStateInfo.State}}, InstanceId -Auto ``` ```Output Id Name Command State InstanceId -- ---- ------- ----- ---------- 1 Job1 Start-Service schedule Running 05abb67a-2932-4bd5-b331-c0254b8d9146 3 Job3 Start-Service schedule Running c03cbd45-19f3-4558-ba94-ebe41b68ad03 5 Job5 Get-Service s* Blocked e3bbfed1-9c53-401a-a2c3-a8db34336adf ``` ```powershell Stop-Job -InstanceId e3bbfed1-9c53-401a-a2c3-a8db34336adf ``` These commands show how to stop a job based on its **InstanceId**. The first command uses the `Get-Job` cmdlet to get the jobs in the current session. The command uses a pipeline operator (`|`) to send the jobs to a `Format-Table` command, which displays a table of the specified properties of each job. The table includes the **InstanceId** of each job. It uses a calculated property to display the job state. The second command uses a `Stop-Job` command that has the **InstanceId** parameter to stop a selected job. ### Example 7: Stop a job on a remote computer ```powershell $j = Invoke-Command -ComputerName Server01 -ScriptBlock {Get-EventLog -LogName System} -AsJob $j | Stop-Job -PassThru ``` ```Output Id Name State HasMoreData Location Command -- ---- ---- ----------- -------- ------- 5 Job5 Stopped True user01-tablet Get-EventLog -LogName Sy... ``` This example shows how to use the `Stop-Job` cmdlet to stop a job that is running on a remote computer. Because the job was started with the **AsJob** parameter of the `Invoke-Command` cmdlet, the **Job** object is located on the local computer, even though the job runs on the remote computer. Therefore, you can use a local `Stop-Job` command to stop the job. The first command uses the `Invoke-Command` cmdlet to start a background job on the Server01 computer. The command uses the **AsJob** parameter to run the remote command as a background job. This command returns a job object, which is the same job object that the `Start-Job` cmdlet returns. The command saves the job object in the `$j` variable. The second command uses a pipeline operator to send the job in the `$j` variable to `Stop-Job`. The command uses the **PassThru** parameter to direct `Stop-Job` to return a job object. The job object display confirms that the state of the job is Stopped. For more information about remote background jobs, see [about_Remote_Jobs](About/about_Remote_Jobs.md). ## PARAMETERS ### -Filter Specifies a hash table of conditions. This cmdlet stops jobs that satisfy every condition. Enter a hash table where the keys are job properties and the values are job property values. This parameter works only on custom job types, such as **WorkflowJobs** and **ScheduledJobs**. It does not work on standard background jobs, such as those created by using the `Start-Job` cmdlet. For information about support for this parameter, see the help topic for the job type. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Collections.Hashtable Parameter Sets: FilterParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Id Specifies the IDs of jobs that this cmdlet stops. The default is all jobs in the current session. The ID is an integer that uniquely identifies the job in the current session. It is easier to remember and type than the instance ID, but it is unique only in the current session. You can type one or more IDs, separated by commas. To find the ID of a job, type `Get-Job`. ```yaml Type: System.Int32[] Parameter Sets: SessionIdParameterSet Aliases: Required: True Position: 0 Default value: All jobs Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InstanceId Specifies the instance IDs of jobs that this cmdlet stops. The default is all jobs. An instance ID is a GUID that uniquely identifies the job on the computer. To find the instance ID of a job, use `Get-Job`. ```yaml Type: System.Guid[] Parameter Sets: InstanceIdParameterSet Aliases: Required: True Position: 0 Default value: All jobs Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Job Specifies the jobs that this cmdlet stops. Enter a variable that contains the jobs or a command that gets the jobs. You can also use a pipeline operator to submit jobs to the `Stop-Job` cmdlet. By default, `Stop-Job` deletes all jobs that were started in the current session. ```yaml Type: System.Management.Automation.Job[] Parameter Sets: JobParameterSet Aliases: Required: True Position: 0 Default value: All jobs Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Name Specifies friendly names of jobs that this cmdlet stops. Enter the job names in a comma-separated list or use wildcard characters (`*`) to enter a job name pattern. By default, `Stop-Job` stops all jobs created in the current session. Because the friendly name is not guaranteed to be unique, use the **WhatIf** and **Confirm** parameters when stopping jobs by name. ```yaml Type: System.String[] Parameter Sets: NameParameterSet Aliases: Required: True Position: 0 Default value: All jobs Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -State Specifies a job state. This cmdlet stops only jobs in the specified state. The acceptable values for this parameter are: - `NotStarted` - `Running` - `Completed` - `Failed` - `Stopped` - `Blocked` - `Suspended` - `Disconnected` - `Suspending` - `Stopping` For more information about job states, see [JobState Enumeration](/dotnet/api/system.management.automation.jobstate). ```yaml Type: System.Management.Automation.JobState Parameter Sets: StateParameterSet Aliases: Accepted values: NotStarted, Running, Completed, Failed, Stopped, Blocked, Suspended, Disconnected, Suspending, Stopping, AtBreakpoint Required: True Position: 0 Default value: All jobs Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.RemotingJob You can pipe a job object to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSRemotingJob When you use the **PassThru** parameter, this cmdlet returns a job object. ## NOTES PowerShell includes the following aliases for `Stop-Job`: - All platforms: - `spjb` ## RELATED LINKS [Get-Job](Get-Job.md) [Invoke-Command](Invoke-Command.md) [Receive-Job](Receive-Job.md) [Remove-Job](Remove-Job.md) [Start-Job](Start-Job.md) [Wait-Job](Wait-Job.md) [about_Job_Details](About/about_Job_Details.md) [about_Remote_Jobs](About/about_Remote_Jobs.md) [about_Remote_Variables](About/about_Remote_Variables.md) [about_Jobs](About/about_Jobs.md) [about_Scopes](About/about_scopes.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Switch-Process.md

--- external help file: System.Management.Automation.dll-Help.xml Module Name: Microsoft.PowerShell.Core online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/switch-process?view=powershell-7.6&WT.mc_id=ps-gethelp ms.date: 01/20/2023 schema: 2.0.0 --- # Switch-Process ## SYNOPSIS On Linux and macOS, the cmdlet calls the `execv()` function to provide similar behavior as POSIX shells. ## SYNTAX ``` Switch-Process [[-WithCommand] <String[]>] [<CommonParameters>] ``` ## DESCRIPTION Some native Unix commands shell out to run something (like ssh) and use the `bash` built-in command `exec` to spawn a new process that replaces the current one. By default, `exec` isn't a valid command in PowerShell. This is affecting some known scripts like `copy-ssh-id` and some subcommands of AzCLI. The `Switch-Process` cmdlet calls the native `execv()` function to provide similar behavior as POSIX shells. This cmdlet and its alias, `exec`, were added in PowerShell 7.3.0. PowerShell 7.3.1 changed the `exec` alias to a function that wraps `Switch-Process`. The function allows you to pass parameters to the native command that might have erroneously bound to the **WithCommand** parameter. This cmdlet is only available for non-Windows systems. ## EXAMPLES ### Example 1 - Execute a command that depends on `exec` This example assumes that PowerShell is the default shell on a non-Windows system. `ssh-copy-id` is a popular bash script to deploy public keys on target machines for key-based authentication. The script depends on the bash command, `exec`. ```powershell ssh-copy-id user@host ``` With the `PSExec` feature enabled, the `ssh-copy-id` script succeeds. ## PARAMETERS ### -WithCommand Specifies the native executable (and any parameters) to be run. All additional values passed as arguments are passed as an array of strings to be executed with the first command. The target command must be a native executable, not a PowerShell command. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String[] ## OUTPUTS ### System.Object ## NOTES The `Switch-Process` cmdlet was created to provide `exec` compatibility is other POSIX shells. Under normal conditions, the cmdlet isn't intended to be used in PowerShell scripts. `Switch-Process` doesn't have feature parity with the built-in `exec` function in POSIX shells, such as like how file descriptors are handled, but should cover most cases. ## RELATED LINKS

#File: reference/7.6/Microsoft.PowerShell.Core/TabExpansion2.md

--- external help file: System.Management.Automation.dll-Help.xml Module Name: Microsoft.PowerShell.Core ms.date: 06/13/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/tabexpansion2?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 --- # TabExpansion2 ## SYNOPSIS A helper function that wraps the `CompleteInput()` method of the **CommandCompletion** class to provide tab completion for PowerShell scripts. ## SYNTAX ### ScriptInputSet (Default) ``` TabExpansion2 [-inputScript] <String> [[-cursorColumn] <Int32>] [[-options] <Hashtable>] [<CommonParameters>] ``` ### AstInputSet ``` TabExpansion2 [-ast] <Ast> [-tokens] <Token[]> [-positionOfCursor] <IScriptPosition> [[-options] <Hashtable>] [<CommonParameters>] ``` ## DESCRIPTION `TabExpansion2` is a built-in function that provides tab completion for user input. PowerShell calls this function when the user presses the <kbd>Tab</kbd> or <kbd>Ctrl</kbd>+<kbd>Space</kbd> key while typing a command. The function returns a list of possible completions for the current input. `TabExpansion2` isn't normally called directly by users. However, it can be useful for testing tab completion. To use `TabExpansion2`, you need to provide the current input script and the cursor position in the script. The function returns a **CommandCompletion** object that contains a list of possible completions for the current input. This input script can be a string or an abstract syntax tree (AST) that represents the script. You can override the default behavior of `TabExpansion2` by defining a custom function with the same name in your PowerShell session. This custom function can provide completions for custom commands or parameters. While it is possible to override `TabExpansion2`, it's not supported. You should create a custom function only if you have a specific need to customize the tab completion behavior. ## EXAMPLES ### Example 1 - Get tab completion for command parameter This example shows the same results you would get by entering `Format-Hex -<Tab>` at the PowerShell command prompt. The `TabExpansion2` function returns a **CommandCompletion** object that contains a list of possible completions for the `-` token. ```powershell TabExpansion2 -inputScript ($s = 'Format-Hex -') -cursorColumn $s.Length | Select-Object -ExpandProperty CompletionMatches ``` ```Output CompletionText ListItemText ResultType ToolTip -------------- ------------ ---------- ------- -Path Path ParameterName [string[]] Path -LiteralPath LiteralPath ParameterName [string[]] LiteralPath -InputObject InputObject ParameterName [psobject] InputObject -Encoding Encoding ParameterName [Encoding] Encoding -Count Count ParameterName [long] Count -Offset Offset ParameterName [long] Offset ``` ### Example 2 - Get tab completion for parameter values This example shows how to get tab completion for parameter values. In this example, we expect that **Stage** parameter has three possible values and that one of the values is `Three`. You can use this technique to test that tab completion for your function returns the expected results. ```powershell function Get-Data { param ( [ValidateSet('One', 'Two', 'Three')] [string]$Stage ) Write-Verbose "Retrieving data for stage $Stage" } $result = TabExpansion2 -inputScript ($line = 'Get-Data -Stage ') -cursorColumn $line.Length | Select-Object -ExpandProperty CompletionMatches $result.Count -eq 3 $result.CompletionText -contains 'Three' ``` ```Output True True ``` ## PARAMETERS ### -ast An abstract syntax tree (AST) object that represents the script that you want to expand using tab completion. ```yaml Type: System.Management.Automation.Language.Ast Parameter Sets: AstInputSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -cursorColumn The column number of the cursor in the input script string. The cursor position is used to determine the token that gets expanded by tab completion. ```yaml Type: System.Int32 Parameter Sets: ScriptInputSet Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -inputScript A string that represents the script that you want to expand using tab completion. ```yaml Type: System.String Parameter Sets: ScriptInputSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -options A hashtable of option values to pass to the `CompleteInput()` API. The API accepts the following boolean options: - `IgnoreHiddenShares` - When set to `$true`, ignore hidden UNC shares such as `\\COMPUTER\ADMIN$` and `\\COMPUTER\C$`. By default, PowerShell includes hidden shares. - `RelativePaths` - By default, PowerShell decides how to expand paths based on the input you provided. Setting this value to `$true` forces PowerShell to replace paths with relative paths. Setting this value to `$false`, forces PowerShell to replace them with absolute paths. - `LiteralPaths` - By default, PowerShell replace special file characters, such as square brackets and back-ticks, with their escaped equivalents. Setting this value to `$true` prevents the replacement. ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: Required: False Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -positionOfCursor The column number of the cursor in the input AST. The cursor position is used to determine the token that gets expanded by tab completion. ```yaml Type: System.Management.Automation.Language.IScriptPosition Parameter Sets: AstInputSet Aliases: Required: True Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -tokens An array of tokens parsed from the input script. The tokens are used to determine the token that gets expanded by tab completion. ```yaml Type: System.Management.Automation.Language.Token[] Parameter Sets: AstInputSet Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -ProgressAction -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None ## OUTPUTS ### System.Management.Automation.CommandCompletion ## NOTES ## RELATED LINKS [about_Built-in_Functions](./about/about_Built-in_Functions.md) [about_Tab_Expansion](./about/about_Tab_Expansion.md) [CompleteInput() method](xref:System.Management.Automation.CommandCompletion.CompleteInput*)

#File: reference/7.6/Microsoft.PowerShell.Core/Test-ModuleManifest.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 09/28/2021 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/test-modulemanifest?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Test-ModuleManifest --- # Test-ModuleManifest ## SYNOPSIS Verifies that a module manifest file accurately describes the contents of a module. ## SYNTAX ``` Test-ModuleManifest [-Path] <String> [<CommonParameters>] ``` ## DESCRIPTION The `Test-ModuleManifest` cmdlet verifies that the files that are listed in the module manifest (`.psd1`) file are actually in the specified paths. This cmdlet is designed to help module authors test their manifest files. Module users can also use this cmdlet in scripts and commands to detect errors before they run scripts that depend on the module. `Test-ModuleManifest` returns an object that represents the module. This is the same type of object that `Get-Module` returns. If any files are not in the locations specified in the manifest, the cmdlet also generates an error for each missing file. ## EXAMPLES ### Example 1: Test a manifest ```powershell Test-ModuleManifest -Path "$PSHOME\Modules\TestModule.psd1" ``` This command tests the `TestModule.psd1` module manifest. ### Example 2: Test a manifest by using the pipeline ```powershell "$PSHOME\Modules\TestModule.psd1" | Test-ModuleManifest ``` ```Output Test-ModuleManifest : The specified type data file 'C:\Windows\System32\Wi ndowsPowerShell\v1.0\Modules\TestModule\TestTypes.ps1xml' could not be processed because the file was not found. Please correct the path and try again. At line:1 char:34 + "$PSHOME\Modules\TestModule.psd1" | Test-ModuleManifest <<<< + CategoryInfo : ResourceUnavailable: (C:\Windows\System32\WindowsPowerShell\v1.0\Modules\TestModule\TestTypes.ps1xml:String) [Test-ModuleManifest], FileNotFoundException + FullyQualifiedErrorId : Modules_TypeDataFileNotFound,Microsoft.PowerShell.Commands.TestModuleManifestCommandName Name : TestModule Path : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\TestModule\TestModule.psd1 Description : Guid : 6f0f1387-cd25-4902-b7b4-22cff6aefa7b Version : 1.0 ModuleBase : C:\Windows\system32\WindowsPowerShell\v1.0\Modules\TestModule ModuleType : Manifest PrivateData : AccessMode : ReadWrite ExportedAliases : {} ExportedCmdlets : {} ExportedFunctions : {} ExportedVariables : {} NestedModules : {} ``` This command uses a pipeline operator (`|`) to send a path string to `Test-ModuleManifest`. The command output shows that the test failed, because the TestTypes.ps1xml file, which was listed in the manifest, was not found. ### Example 3: Write a function to test a module manifest ```powershell function Test-ManifestBool ($path) ``` ```Output {$a = dir $path | Test-ModuleManifest -ErrorAction SilentlyContinue; $?} ``` This function is like `Test-ModuleManifest`, but it returns a Boolean value. The function returns `$true` if the manifest passed the test and `$false` otherwise. The function uses the Get-ChildItem cmdlet, alias = dir, to get the module manifest specified by the `$path` variable. The command uses a pipeline operator (`|`) to pass the file object to `Test-ModuleManifest`. `Test-ModuleManifest` uses the **ErrorAction** common parameter with a value of SilentlyContinue to suppress the display of any errors that the command generates. It also saves the **PSModuleInfo** object that `Test-ModuleManifest` returns in the $a variable. Therefore, the object is not displayed. Then, in a separate command, the function displays the value of the `$?` automatic variable. If the previous command generates no error, the command displays `$true`, and `$false` otherwise. You can use this function in conditional statements, such as those that might precede an `Import-Module` command or a command that uses the module. ## PARAMETERS ### -Path Specifies a path and file name for the manifest file. Enter an optional path and name of the module manifest file that has the `.psd1` file name extension. The default location is the current directory. Wildcard characters are supported, but must resolve to a single module manifest file. This parameter is required. You can also pipe a path to `Test-ModuleManifest`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe the path to a module manifest to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSModuleInfo This cmdlet returns a **PSModuleInfo** object that represents the module. It returns this object even if the manifest has errors. ## NOTES ## RELATED LINKS [Export-ModuleMember](Export-ModuleMember.md) [Get-Module](Get-Module.md) [Import-Module](Import-Module.md) [New-Module](New-Module.md) [New-ModuleManifest](New-ModuleManifest.md) [Remove-Module](Remove-Module.md) [about_Modules](About/about_Modules.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Test-PSSessionConfigurationFile.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/test-pssessionconfigurationfile?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Test-PSSessionConfigurationFile --- # Test-PSSessionConfigurationFile ## SYNOPSIS Verifies the keys and values in a session configuration file. ## SYNTAX ``` Test-PSSessionConfigurationFile [-Path] <String> [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** This cmdlet verifies that a session configuration file contains valid keys and the values are of the correct type. For enumerated values, the cmdlet verifies that the specified values are valid. The cmdlet returns `$true` if the file passes all tests and `$false` if it does not. To find any errors, use the **Verbose** parameter. `Test-PSSessionConfigurationFile` verifies the session configuration files, such as those created by the `New-PSSessionConfigurationFile` cmdlet. For information about session configurations, see [about_Session_Configurations](About/about_Session_Configurations.md). For information about session configuration files, see [about_Session_Configuration_Files](About/about_Session_Configuration_Files.md). This cmdlet was introduced in PowerShell 3.0. ## EXAMPLES ### Example 1: Test a session configuration file ```powershell Test-PSSessionConfigurationFile -Path "FullLanguage.pssc" ``` ```Output True ``` ### Example 2: Test the session configuration file of a session configuration In this example, we test the configuration file used in the **Restricted** session configuration. The value of the **Path** parameter is the result of the `Get-PSSessionConfiguration` command that gets the **Restricted** session configuration. The path of the session configuration file is stored in the value of the **ConfigFilePath** property of the session configuration. ```powershell Test-PSSessionConfigurationFile -Path (Get-PSSessionConfiguration -Name Restricted).ConfigFilePath ``` ### Example 3: Test all session configuration files The function in this example tests all session configuration files on the local computer. The function uses the `Get-PSSessionConfiguration` cmdlet to get all session configurations. The code inside the `ForEach-Object` loop displays the file path and tests each of the session configurations. ```powershell function Test-AllConfigFiles { Get-PSSessionConfiguration | ForEach-Object { if ($_.ConfigFilePath) { $_.ConfigFilePath Test-PSSessionConfigurationFile -Verbose -Path $_.ConfigFilePath } } } Test-AllConfigFiles ``` ```Output C:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\Empty_6fd77bf6-e084-4372-bd8a-af3e207354d3.pssc True C:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\Full_1e9cb265-dae0-4bd3-89a9-8338a47698a1.pssc VERBOSE: The member 'AliasDefinitions' must contain the required key 'Description'. Add the require key to the fileC:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\Full_1e9cb265-dae0-4bd3-89a9-8338a47698a1.pssc. False C:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\NoLanguage_0c115179-ff2a-4f66-a5eb-e56e5692ba22.pssc True C:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\RestrictedLang_b6bd9474-0a6c-4e06-8722-c2c95bb10d3e.pssc True C:\WINDOWS\System32\WindowsPowerShell\v1.0\SessionConfig\RRS_3fb29420-2c87-46e5-a402-e21436331efc.pssc True ``` The **ConfigFilePath** property of a session configuration contains the path of the session configuration file that is used in the session configuration, if any. If the value of the **ConfigFilePath** property is populated (is true), the command gets (prints) the **ConfigFilePath** property value. Then it uses the `Test-PSSessionConfigurationFile` cmdlet to test the file in the **ConfigFilePath** value. The **Verbose** parameter returns the file error when the file fails the test. ## PARAMETERS ### -Path Specifies the path and filename of a session configuration file (.pssc). If you omit the path, the default is the current folder. Wildcard characters are supported, but they must resolve to a single file. You can also pipe a session configuration file path to `Test-PSSessionConfigurationFile`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a session configuration file path to this cmdlet. ## OUTPUTS ### System.Boolean ## NOTES This cmdlet is only available on Windows platforms. ## RELATED LINKS [Disable-PSSessionConfiguration](Disable-PSSessionConfiguration.md) [Enable-PSSessionConfiguration](Enable-PSSessionConfiguration.md) [Get-PSSessionConfiguration](Get-PSSessionConfiguration.md) [New-PSSessionConfigurationFile](New-PSSessionConfigurationFile.md) [New-PSSessionOption](New-PSSessionOption.md) [Register-PSSessionConfiguration](Register-PSSessionConfiguration.md) [Set-PSSessionConfiguration](Set-PSSessionConfiguration.md) [Test-PSSessionConfigurationFile](Test-PSSessionConfigurationFile.md) [Unregister-PSSessionConfiguration](Unregister-PSSessionConfiguration.md) [WSMan Provider](../Microsoft.WsMan.Management/About/about_WSMan_Provider.md) [about_Session_Configurations](About/about_Session_Configurations.md) [about_Session_Configuration_Files](About/about_Session_Configuration_Files.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Unregister-PSSessionConfiguration.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 12/09/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/unregister-pssessionconfiguration?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Unregister-PSSessionConfiguration --- # Unregister-PSSessionConfiguration ## SYNOPSIS Deletes registered session configurations from the computer. ## SYNTAX ``` Unregister-PSSessionConfiguration [-Name] <String> [-Force] [-NoServiceRestart] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Unregister-PSSessionConfiguration` cmdlet deletes registered session configurations from the computer. This cmdlet is designed for system administrators to manage customized session configurations for users. To make the change effective, `Unregister-PSSessionConfiguration` restarts the WinRM service. To prevent the restart, specify the **NoServiceRestart** parameter. If you accidentally delete the default `Microsoft.PowerShell` or `Microsoft.PowerShell32` session configurations, use the `Enable-PSRemoting` cmdlet to restore them. For more information, see [about_Session_Configurations](About/about_Session_Configurations.md). ## EXAMPLES ### Example 1: Delete a session configuration This example deletes the `MaintenanceShell` session configuration from the computer. ```powershell Unregister-PSSessionConfiguration -Name "MaintenanceShell" ``` ### Example 2: Delete a session configuration and restart the WinRM service In this example, we delete the `MaintenanceShell` configuration and restart the WinRM service. The **Force** parameter suppresses all user messages to restart the WinRM service without prompting. ```powershell Unregister-PSSessionConfiguration -Name MaintenanceShell -Force ``` ### Example 3: Delete all session configurations This examples show two ways to delete all the session configurations on the computer. Both commands have the same effect and can be used interchangeably. ```powershell Unregister-PSSessionConfiguration -Name * Get-PSSessionConfiguration -Name * | Unregister-PSSessionConfiguration ``` ### Example 4: Unregister without a restart This example shows the effect of using the **NoServiceRestart** parameter to prevent a service restart that would disrupt any sessions on the computer. ``` PS> Unregister-PSSessionConfiguration -Name "MaintenanceShell" -NoServiceRestart PS> Get-PSSessionConfiguration -Name "MaintenanceShell" Get-PSSessionConfiguration -Name MaintenanceShell : No Session Configuration matches criteria "MaintenanceShell". + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException PS> New-PSSession -ConfigurationName "MaintenanceShell" Id Name ComputerName State Configuration Availability -- ---- ------------ ----- ------------- ------------ 1 Session1 localhost Opened MaintenanceShell Available PS> Restart-Service winrm PS> New-PSSession -ConfigurationName MaintenanceShell [localhost] Connecting to remote server failed with the following error message : The WS-Management service cannot process the request. The resource URI (http://schemas.microsoft.com/powershell/MaintenanceShell) was not found in the WS-Management catalog. The catalog contains the metadata that describes resources, or logical endpoints. For more information, see the about_Remote_Troubleshooting Help topic. + CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [], PSRemotingTransportException + FullyQualifiedErrorId : PSSessionOpenFailed ``` The `Unregister-PSSessionConfiguration` deletes the `MaintenanceShell` session configuration. However, because the command uses the **NoServiceRestart** parameter, the WinRM service is not restarted and the change is not yet completely effective. Next, the `Get-PSSessionConfiguration` tries to get the `MaintenanceShell` session. Because the session has been removed from the WS-Management resource table, `Get-PSSessionConfiguration` cannot return it. The `New-PSSession` cmdlet creates a session using the `MaintenanceShell` configuration. The command succeeds. Next, we restart the WinRM service. Finally, the `New-PSSession` cmdlet tries to create a session that uses the `MaintenanceShell` configuration. This time, the session fails because the `MaintenanceShell` configuration was deleted when the WinRM service restarted. ## PARAMETERS ### -Force Indicates that the cmdlet does not prompt you for confirmation, and restarts the WinRM service without prompting. Restarting the service makes the configuration change effective. To prevent a restart and suppress the restart prompt, use the **NoServiceRestart** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies the names of the session configurations to delete. Enter one session configuration name or a configuration name pattern. Wildcard characters are permitted. This parameter is required. You can also pipe a session configurations to `Unregister-PSSessionConfiguration`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -NoServiceRestart Indicates that this cmdlet does not restart the WinRM service, and suppresses the prompt to restart the service. By default, when you run an `Unregister-PSSessionConfiguration` command, you are prompted to restart the WinRM service to make the change effective. Until the WinRM service is restarted, users can still use the unregistered session configuration, even though `Get-PSSessionConfiguration` does not find it. To restart the WinRM service without prompting, specify the **Force** parameter. To restart the WinRM service manually, use the `Restart-Service` cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### Microsoft.PowerShell.Commands.PSSessionConfigurationCommands#PSSessionConfiguration You can pipe a session configuration object to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES This cmdlet is only available on Windows platforms. To run this cmdlet you must start PowerShell by using the **Run as administrator** option. ## RELATED LINKS [Disable-PSSessionConfiguration](Disable-PSSessionConfiguration.md) [Enable-PSSessionConfiguration](Enable-PSSessionConfiguration.md) [Get-PSSessionConfiguration](Get-PSSessionConfiguration.md) [New-PSSessionConfigurationFile](New-PSSessionConfigurationFile.md) [New-PSSessionOption](New-PSSessionOption.md) [Register-PSSessionConfiguration](Register-PSSessionConfiguration.md) [Set-PSSessionConfiguration](Set-PSSessionConfiguration.md) [Test-PSSessionConfigurationFile](Test-PSSessionConfigurationFile.md) [Unregister-PSSessionConfiguration](Unregister-PSSessionConfiguration.md) [WSMan Provider](../Microsoft.WsMan.Management/About/about_WSMan_Provider.md) [about_Session_Configurations](About/about_Session_Configurations.md) [about_Session_Configuration_Files](About/about_Session_Configuration_Files.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Update-Help.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 11/14/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/update-help?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Update-Help --- # Update-Help ## SYNOPSIS Downloads and installs the newest help files on your computer. ## SYNTAX ### Path (Default) ``` Update-Help [[-Module] <String[]>] [-FullyQualifiedModule <ModuleSpecification[]>] [[-SourcePath] <String[]>] [-Recurse] [[-UICulture] <CultureInfo[]>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-Force] [-Scope <UpdateHelpScope>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath ``` Update-Help [[-Module] <String[]>] [-FullyQualifiedModule <ModuleSpecification[]>] [-LiteralPath <String[]>] [-Recurse] [[-UICulture] <CultureInfo[]>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-Force] [-Scope <UpdateHelpScope>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Update-Help` cmdlet downloads the newest help files for PowerShell modules and installs them on your computer. You need not restart PowerShell to make the change effective. You can use the `Get-Help` cmdlet to view the new help files immediately. `Update-Help` checks the version of the help files on your computer. If you don't have help files for a module or if your help files are outdated, `Update-Help` downloads the newest help files. The help files can be downloaded and installed from the internet or a file share. Without parameters, `Update-Help` updates the help files for modules that support updateable help and are loaded in the session or installed in a location included in the `$Env:PSModulePath`. For more information, see [about_Updatable_Help](./About/about_Updatable_Help.md). `Update-Help` checks the version of the help installed. If `Update-Help` can't find updated help files for a module it continues silently without displaying an error message. Use the **Force** parameter to skip the version check. Use the **Verbose** parameter to see status and progress details. Use the **Module** parameter to update help files for a particular module. You can also use `Update-Help` on computers that aren't connected to the internet. First, use the `Save-Help`cmdlet to download help files from the internet and save them in a shared folder that's accessible to the system not connected to the internet. Then use the **SourcePath** parameter of `Update-Help` to download the updated help files from the shared and install them on the computer. The `Update-Help` cmdlet was introduced in Windows PowerShell 3.0. > [!IMPORTANT] > `Update-Help` requires administrative privileges in PowerShell 6.0 and below. PowerShell 6.1 and > above set the default **Scope** to `CurrentUser`. Prior to PowerShell 6.1, the **Scope** parameter > wasn't available. > > You must be a member of the Administrators group on the computer to update the help files for the > core PowerShell modules. > > To download or update the help files for modules in the PowerShell installation directory > (`$PSHOME\Modules`), including the PowerShell Core modules, start PowerShell using the **Run as > administrator** option. For example: `Start-Process pwsh.exe -Verb RunAs`. ## EXAMPLES ### Example 1: Update help files for all modules The `Update-Help` cmdlet updates help files for installed modules that support Updatable Help. The user-interface (UI) culture language is set in the operating system. ```powershell Update-Help ``` ### Example 2: Update help files for specified modules The `Update-Help` cmdlet updates help files only for module names that begin with **Microsoft.PowerShell**. ```powershell Update-Help -Module Microsoft.PowerShell* ``` ### Example 3: Updating help on a system not set to the en-US locale The `Update-Help` cmdlet is designed to download help in multiple languages. However, when there is no help available for the language your system uses, an error message is displayed for the module and UI culture. In this example, `Update-Help` is being run on a system that's set to the `en-GB` locale. ```powershell Update-Help Microsoft.PowerShell.Utility -Force ``` ```Output Update-Help: Failed to update Help for the module(s) 'Microsoft.PowerShell.Utility' with UI culture(s) {en-GB} : The specified culture is not supported: en-GB. Specify a culture from the following list: {en-US}.. English-US help content is available and can be installed using: Update-Help -UICulture en-US. ``` The help files are always published for the `en-US` locale. To download the English help, run `Update-Help` with the **UICulture** parameter and specify the `en-US` locale. ### Example 4: Update help files on multiple computers from a file share In this example, updated help files are downloaded from the internet and saved in a file share. User credentials are needed that have permissions to access the file share and install updates. When a file share is used, it's possible to update computers that are behind firewalls or aren't connected to the internet. ```powershell Save-Help -DestinationPath \\Server01\Share\PSHelp -Credential Domain01\Admin01 Invoke-Command -ComputerName (Get-Content Servers.txt) -ScriptBlock { Update-Help -SourcePath \\Server01\Share\PSHelp -Credential Domain01\Admin01 } ``` The `Save-Help` command downloads the newest help files for all modules that support Updatable Help. The **DestinationPath** parameter saves the files in the `\\Server01\Share\PSHelp` file share. The **Credential** parameter specifies a user who has permission to access the file share. The `Invoke-Command` cmdlet runs remote `Update-Help` commands on multiple computers. The **ComputerName** parameter gets a list of remote computers from the **Servers.txt** file. The **ScriptBlock** parameter runs the `Update-Help` command and uses the **SourcePath** parameter to specify the file share containing the updated help files. The **Credential** parameter specifies a user who can access the file share and run the remote `Update-Help` command. ### Example 5: Get a list of updated help files The `Update-Help` cmdlet updates help for a specified module. The cmdlet uses the **Verbose** common parameter to display the list of help files that were updated. You can use **Verbose** to view output for all help files or help files for a specific module. Without the **Verbose** parameter, `Update-Help` doesn't display the results of the command. The **Verbose** parameter output is useful to verify that the help files were updated or if the latest version is installed. ```powershell Update-Help -Module Microsoft.PowerShell.Utility -Verbose ``` ### Example 6: Find modules that support Updatable Help This example lists modules that support Updatable Help. The command uses the module's **HelpInfoUri** property to identify modules that support Updatable Help. The **HelpInfoUri** property contains a URL that's redirected when the `Update-Help` cmdlet is run. ```powershell Get-Module -ListAvailable | Where-Object -Property HelpInfoUri ``` ```output Directory: C:\Program Files\PowerShell\6\Modules ModuleType Version Name PSEdition ExportedCommands ---------- ------- ---- --------- ---------------- Manifest 6.1.0.0 CimCmdlets Core {Get-CimAssociatedInstance... } Manifest 1.2.2.0 Microsoft.PowerShell.Archive Desk {Compress-Archive... } Manifest 6.1.0.0 Microsoft.PowerShell.Diagnostics Core {Get-WinEvent, New-WinEvent} Directory: C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules ModuleType Version Name PSEdition ExportedCommands ---------- ------- ---- --------- ---------------- Manifest 2.0.1.0 Appx Core,Desk {Add-AppxPackage, ... } Script 1.0.0.0 AssignedAccess Core,Desk {Clear-AssignedAccess, ... } Manifest 1.0.0.0 BitLocker Core,Desk {Unlock-BitLocker, ... } ``` ### Example 7: Inventory updated help files In this example, the script `Get-UpdateHelpVersion.ps1` creates an inventory of the Updatable Help files for each module and their version numbers. The script identifies modules that support Updatable Help using the **HelpInfoUri** property of modules. For modules that support Updatable Help, the script looks for and parses the help information file (*helpinfo.xml) to find the latest version number. The script uses the **PSCustomObject** class and a hash table to create a custom output object. ```powershell # Get-UpdateHelpVersion.ps1 param ( [Parameter(Mandatory=$false)] [string[]] $Module ) $HelpInfoNamespace = @{helpInfo='http://schemas.microsoft.com/powershell/help/2010/05'} if ($Module) { $Modules = Get-Module $Module -ListAvailable | where {$_.HelpInfoUri} } else { $Modules = Get-Module -ListAvailable | where {$_.HelpInfoUri} } foreach ($mModule in $Modules) { $mDir = $mModule.ModuleBase if (Test-Path $mDir\*helpinfo.xml) { $mName=$mModule.Name $mNodes = dir $mDir\*helpinfo.xml -ErrorAction SilentlyContinue | Select-Xml -Namespace $HelpInfoNamespace -XPath "//helpInfo:UICulture" foreach ($mNode in $mNodes) { $mCulture=$mNode.Node.UICultureName $mVer=$mNode.Node.UICultureVersion [pscustomobject]@{"ModuleName"=$mName; "Culture"=$mCulture; "Version"=$mVer} } } } ``` ```Output ModuleName Culture Version ---------- ------- ------- ActiveDirectory en-US 3.0.0.0 ADCSAdministration en-US 3.0.0.0 ADCSDeployment en-US 3.0.0.0 ADDSDeployment en-US 3.0.0.0 ADFS en-US 3.0.0.0 ``` ## PARAMETERS ### -Credential Specifies credentials of a user who has permission to access the file system location specified by **SourcePath**. This parameter is valid only when the **SourcePath** or **LiteralPath** parameter is used in the command. The **Credential** parameter enables you to run `Update-Help` commands with the **SourcePath** parameter on remote computers. By providing explicit credentials, you can run the command on a remote computer and access a file share on a third computer without encountering an access denied error or using CredSSP authentication to delegate credentials. Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. If you type a user name, you're prompted to enter the password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Indicates that this cmdlet doesn't follow the once-per-day limitation, skips version checking, and downloads files that exceed the 1 GB limit. Without this parameter, `Update-Help` runs only once in each 24-hour period. Downloads are limited to 1 GB of uncompressed content per module and help files are only installed when they're newer than the existing files on the computer. The once-per-day limit protects the servers that host the help files and makes it practical for you to add an `Update-Help` command to your PowerShell profile without incurring the resource cost of repeated connections or downloads. To update help for a module in multiple UI cultures without the **Force** parameter, include all UI cultures in the same command, such as: `Update-Help -Module PSScheduledJobs -UICulture en-US, fr-FR, pt-BR` ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FullyQualifiedModule The value can be a module name, a full module specification, or a path to a module file. When the value is a path, the path can be fully qualified or relative. A relative path is resolved relative to the script that contains the using statement. When the value is a name or module specification, PowerShell searches the **PSModulePath** for the specified module. A module specification is a hashtable that has the following keys. - `ModuleName` - **Required** Specifies the module name. - `GUID` - **Optional** Specifies the GUID of the module. - It's also **Required** to specify at least one of the three below keys. - `ModuleVersion` - Specifies a minimum acceptable version of the module. - `MaximumVersion` - Specifies the maximum acceptable version of the module. - `RequiredVersion` - Specifies an exact, required version of the module. This can't be used with the other Version keys. You can't specify the **FullyQualifiedModule** parameter in the same command as a **Module** parameter. ```yaml Type: Microsoft.PowerShell.Commands.ModuleSpecification[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -LiteralPath Specifies the folder for updated help files instead of downloading them from the internet. Use this parameter or **SourcePath** if you've used the `Save-Help` cmdlet to download help files to a directory. You can pipeline a directory object, such as from the `Get-Item` or `Get-ChildItem` cmdlets, to `Update-Help`. Unlike the value of **SourcePath**, the value of **LiteralPath** is used exactly as it's typed. No characters are interpreted as wildcard characters. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Module Updates help for the specified modules. Enter one or more module names or name patterns in a comma-separated list, or specify a file that lists one module name on each line. Wildcard characters are permitted. You can pipeline modules from the `Get-Module` cmdlet to the `Update-Help` cmdlet. The modules that you specify must be installed on the computer, but they don't have to be imported into the current session. You can specify any module in the session or any module that's installed in a location listed in the `$Env:PSModulePath` environment variable. A value of `*` (all) attempts to update help for all modules that are installed on the computer. Modules that don't support Updatable Help are included. This value might generate errors when the command encounters modules that don't support Updatable Help. Instead, run `Update-Help` without parameters. The **Module** parameter of the `Update-Help` cmdlet doesn't accept the full path of a module file or module manifest file. To update help for a module that isn't in a `$Env:PSModulePath` location, import the module into the current session before you run the `Update-Help` command. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Name Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Recurse Performs a recursive search for help files in the specified directory. This parameter is valid only when the command uses the **SourcePath** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Scope Specifies the system scope where help is updated. Updates at the **AllUsers** scope require administrative privileges on Windows systems. The `-Scope` parameter was introduced in PowerShell Core version 6.1. **CurrentUser** is the default scope for help files in PowerShell 6.1 and above. **AllUsers** can be specified to install or update help for all users. On Unix systems `sudo` privileges are required to update help for all users. For example: `sudo pwsh -c Update-Help` The acceptable values are: - CurrentUser - AllUsers ```yaml Type: Microsoft.PowerShell.Commands.UpdateHelpScope Parameter Sets: (All) Aliases: Required: False Position: Named Default value: CurrentUser Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -SourcePath Specifies a file system folder where `Update-Help` gets updated help files, instead of downloading them from the internet. Enter the path of a folder. Don't specify a file name or file name extension. You can pipeline a folder, such as one from the `Get-Item` or `Get-ChildItem` cmdlets, to `Update-Help`. By default, `Update-Help` downloads updated help files from the internet. Use **SourcePath** when you've used the `Save-Help` cmdlet to download updated help files to a directory. To specify a default value for **SourcePath**, go to **Group Policy**, **Computer Configuration**, and **Set the default source path for Update-Help**. This Group Policy setting prevents users from using `Update-Help` to download help files from the internet. For more information, see [about_Group_Policy_Settings](./About/about_Group_Policy_Settings.md). ```yaml Type: System.String[] Parameter Sets: Path Aliases: Path Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UICulture Specifies UI culture values for which this cmdlet gets updated help files. Enter one or more language codes, such as `es-ES`, a variable that contains culture objects, or a command that gets culture objects, such as a `Get-Culture` or `Get-UICulture` command. Wildcard characters are not permitted. By default, `Update-Help` gets help files in the UI culture set for the operating system or its fallback culture. If you specify the **UICulture** parameter, `Update-Help` only looks for help for the specified language. Beginning in PowerShell 7.4, you can use a partial language code, such as `en` to download help in English for any region. > [!NOTE] > Ubuntu 18.04 changed the default locale setting to `C.UTF.8`, which isn't a recognized UI > culture. `Update-Help` silently fails to download help unless you use this parameter with a > supported locale like `en-US`. This could occur on any platform that uses an unsupported value. ```yaml Type: System.Globalization.CultureInfo[] Parameter Sets: (All) Aliases: Required: False Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseDefaultCredentials Indicates that `Update-Help` runs the command, including the internet download, using the credentials of the current user. By default, the command runs without explicit credentials. This parameter is effective only when the web download uses NT LAN Manager (NTLM), negotiate, or Kerberos-based authentication. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.IO.DirectoryInfo You can pipe a directory path object to this cmdlet. ### System.Management.Automation.PSModuleInfo You can pipe a module object to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES To update help for the core PowerShell modules, that contain the commands that are installed with PowerShell, or any module in the `$PSHOME\Modules` directory, start PowerShell with the option to **Run as administrator**. Only members of the Administrators group on the computer can update help for the core PowerShell modules, the commands that are installed together with PowerShell, and for modules in the `$PSHOME\Modules` folder. If you don't have permission to update help files, you can read the help files online. For example, `Get-Help Update-Help -Online`. Modules are the smallest unit of updatable help. You can't update help for a particular cmdlet. To find the module containing a particular cmdlet, use the **ModuleName** property of the `Get-Command` cmdlet, for example, `(Get-Command Update-Help).ModuleName`. Because help files are installed in the module directory, the `Update-Help` cmdlet can install updated help file only for modules that are installed on the computer. However, the `Save-Help` cmdlet can save help for modules that aren't installed on the computer. The `Update-Help` cmdlet was introduced in Windows PowerShell 3.0. It doesn't work in earlier versions of PowerShell. On computers that have both Windows PowerShell 2.0 and Windows PowerShell 3.0, use the `Update-Help` cmdlet in a Windows PowerShell 3.0 session to download and update help files. The help files are available to both Windows PowerShell 2.0 and Windows PowerShell 3.0. The `Update-Help` and `Save-Help` cmdlets use the following ports to download help files: Port 80 for HTTP and port 443 for HTTPS. `Update-Help` supports all modules and the core PowerShell snap-ins. It doesn't support any other snap-ins. To update help for a module in a location that isn't listed in the `$Env:PSModulePath` environment variable, import the module into the current session and then run an `Update-Help` command. Run `Update-Help` without parameters or use the **Module** parameter to specify the module name. The **Module** parameter of the `Update-Help` and `Save-Help` cmdlets doesn't accept the full path of a module file or module manifest file. Any module can support Updatable Help. For instructions for supporting Updatable Help in the modules that you author, see [Supporting Updatable Help](/powershell/scripting/developer/module/supporting-updatable-help). The `Update-Help` and `Save-Help` cmdlets aren't supported on Windows Preinstallation Environment (Windows PE). ## RELATED LINKS [Get-Culture](../Microsoft.PowerShell.Utility/Get-Culture.md) [Get-Help](Get-Help.md) [Get-Module](Get-Module.md) [Get-UICulture](../Microsoft.PowerShell.Utility/Get-UICulture.md) [Start-Job](Start-Job.md) [Save-Help](Save-Help.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Wait-Job.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 09/29/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/wait-job?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Wait-Job --- # Wait-Job ## SYNOPSIS Waits until one or all of the PowerShell jobs running in the session are in a terminating state. ## SYNTAX ### SessionIdParameterSet (Default) ``` Wait-Job [-Any] [-Timeout <Int32>] [-Force] [-Id] <Int32[]> [<CommonParameters>] ``` ### JobParameterSet ``` Wait-Job [-Job] <Job[]> [-Any] [-Timeout <Int32>] [-Force] [<CommonParameters>] ``` ### NameParameterSet ``` Wait-Job [-Any] [-Timeout <Int32>] [-Force] [-Name] <String[]> [<CommonParameters>] ``` ### InstanceIdParameterSet ``` Wait-Job [-Any] [-Timeout <Int32>] [-Force] [-InstanceId] <Guid[]> [<CommonParameters>] ``` ### StateParameterSet ``` Wait-Job [-Any] [-Timeout <Int32>] [-Force] [-State] <JobState> [<CommonParameters>] ``` ### FilterParameterSet ``` Wait-Job [-Any] [-Timeout <Int32>] [-Force] [-Filter] <Hashtable> [<CommonParameters>] ``` ## DESCRIPTION The `Wait-Job` cmdlet waits for a job to be in a terminating state before continuing execution. The terminating states are: - Completed - Failed - Stopped - Suspended - Disconnected You can wait until a specified job, or all jobs are in a terminating state. You can also set a maximum wait time for the job using the **Timeout** parameter, or use the **Force** parameter to wait for a job in the `Suspended` or `Disconnected` states. When the commands in the job are complete, `Wait-Job` returns a job object and continues execution. You can use the `Wait-Job` cmdlet to wait for jobs started by using the `Start-Job` cmdlet or the **AsJob** parameter of the `Invoke-Command` cmdlet. For more information about jobs, see [about_Jobs](./about/about_Jobs.md). Starting in Windows PowerShell 3.0, the `Wait-Job` cmdlet also waits for custom job types, such as workflow jobs and instances of scheduled jobs. To enable `Wait-Job` to wait for jobs of a particular type, import the module that supports the custom job type into the session before you run the `Get-Job` cmdlet, either by using the `Import-Module` cmdlet or by using or getting a cmdlet in the module. For information about a particular custom job type, see the documentation of the custom job type feature. ## EXAMPLES ### Example 1: Wait for all jobs ```powershell Get-Job | Wait-Job ``` This command waits for all of the jobs running in the session to finish. ### Example 2: Wait for jobs started on remote computers by using Start-Job ```powershell $s = New-PSSession Server01, Server02, Server03 Invoke-Command -Session $s -ScriptBlock {Start-Job -Name Date1 -ScriptBlock {Get-Date}} $done = Invoke-Command -Session $s -Command {Wait-Job -Name Date1} $done.Count ``` ```Output 3 ``` This example shows how to use the `Wait-Job` cmdlet with jobs started on remote computers by using the `Start-Job` cmdlet. Both `Start-Job` and `Wait-Job` commands are submitted to the remote computer by using the `Invoke-Command` cmdlet. This example uses `Wait-Job` to determine whether a `Get-Date` command running as a job on three different computers is finished. The first command creates a Windows PowerShell session (**PSSession**) on each of the three remote computers and stores them in the `$s` variable. The second command uses `Invoke-Command` to run `Start-Job` in each of the three sessions in `$s`. All of the jobs are named Date1. The third command uses `Invoke-Command` to run `Wait-Job`. This command waits for the `Date1` jobs on each computer to finish. It stores the resulting collection (**array**) of **job** objects in the `$done` variable. The fourth command uses the **Count** property of the array of job objects in the `$done` variable to determine how many of the jobs are finished. ### Example 3: Determine when the first job finishes ```powershell $s = New-PSSession -ComputerName (Get-Content -Path .\Machines.txt) $c = 'Get-EventLog -LogName System | Where-Object {$PSItem.EntryType -eq "error" --and $PSItem.Source -eq "LSASRV"} | Out-File -FilePath Errors.txt' Invoke-Command -Session $s -ScriptBlock {Start-Job -ScriptBlock {$Using:c} Invoke-Command -Session $s -ScriptBlock {Wait-Job -Any} ``` This example uses the **Any** parameter of `Wait-Job` to determine when the first of many jobs running in the current session are in a terminating state. It also shows how to use the `Wait-Job` cmdlet to wait for remote jobs to finish. The first command creates a **PSSession** on each of the computers listed in the Machines.txt file and stores the **PSSession** objects in the `$s` variable. The command uses the `Get-Content` cmdlet to get the contents of the file. The `Get-Content` command is enclosed in parentheses to make sure that it runs before the `New-PSSession` command. The second command stores a `Get-EventLog` command string, in quotation marks, in the `$c` variable. The third command uses `Invoke-Command` cmdlet to run `Start-Job` in each of the sessions in `$s`. The `Start-Job` command starts a job that runs the `Get-EventLog` command in the `$c` variable. The command uses the `Using:` scope modifier to indicate that the `$c` variable was defined on the local computer. The `Using:` scope modifier is introduced in Windows PowerShell 3.0. For more information about the `Using:` scope modifier, see [about_Remote_Variables](./about/about_Remote_Variables.md). The fourth command uses `Invoke-Command` to run a `Wait-Job` command in the sessions. It uses the **Any** parameter to wait until the first job on the remote computers is terminating state. ### Example 4: Set a wait time for jobs on remote computers ```powershell PS> $s = New-PSSession -ComputerName Server01, Server02, Server03 PS> $jobs = Invoke-Command -Session $s -ScriptBlock {Start-Job -ScriptBlock {Get-Date}} PS> $done = Invoke-Command -Session $s -ScriptBlock {Wait-Job -Timeout 30} PS> ``` This example shows how to use the **Timeout** parameter of `Wait-Job` to set a maximum wait time for the jobs running on remote computers. The first command creates a **PSSession** on each of three remote computers (Server01, Server02, and Server03), and then stores the **PSSession** objects in the `$s` variable. The second command uses `Invoke-Command` to run `Start-Job` in each of the **PSSession** objects in `$s`. It stores the resulting job objects in the `$jobs` variable. The third command uses `Invoke-Command` to run `Wait-Job` in each of the sessions in `$s`. The `Wait-Job` command determines whether all of the commands have completed within 30 seconds. It uses the **Timeout** parameter with a value of 30 to establish the maximum wait time, and then stores the results of the command in the `$done` variable. In this case, after 30 seconds, only the command on the Server02 computer has completed. `Wait-Job` ends the wait, returns the object that represents the job that was completed, and displays the command prompt. The `$done` variable contains a job object that represents the job that ran on Server02. ### Example 5: Wait until one of several jobs finishes ```powershell Wait-Job -Id 1,2,5 -Any ``` This command identifies three jobs by their IDs and waits until any one of them are in a terminating state. Execution continues when the first job finishes. ### Example 6: Wait for a period, then allow job to continue in background ```powershell Wait-Job -Name "DailyLog" -Timeout 120 ``` This command waits 120 seconds (two minutes) for the DailyLog job to finish. If the job does not finish in the next two minutes, execution continues, and the job continues to run in the background. ### Example 7: Wait for a job by name ```powershell Wait-Job -Name "Job3" ``` This command uses the job name to identify the job for which to wait. ### Example 8: Wait for jobs on local computer started with Start-Job ```powershell $j = Start-Job -ScriptBlock {Get-ChildItem -Filter *.ps1| Where-Object {$PSItem.LastWriteTime -gt ((Get-Date) - (New-TimeSpan -Days 7))}} $j | Wait-Job ``` This example shows how to use the `Wait-Job` cmdlet with jobs started on the local computer by using `Start-Job`. These commands start a job that gets the Windows PowerShell script files that were added or updated in the last week. The first command uses `Start-Job` to start a job on the local computer. The job runs a `Get-ChildItem` command that gets all of the files that have a `.ps1` file name extension that were added or updated in the last week. The third command uses `Wait-Job` to wait until the job is in a terminating state. When the job finishes, the command displays the job object, which contains information about the job. ### Example 9: Wait for jobs started on remote computers by using Invoke-Command ```powershell $s = New-PSSession -ComputerName Server01, Server02, Server03 $j = Invoke-Command -Session $s -ScriptBlock {Get-Process} -AsJob $j | Wait-Job ``` This example shows how to use `Wait-Job` with jobs started on remote computers by using the **AsJob** parameter of `Invoke-Command`. When using **AsJob**, the job is created on the local computer and the results are automatically returned to the local computer, even though the job runs on the remote computers. This example uses `Wait-Job` to determine whether a `Get-Process` command running in the sessions on three remote computers is in a terminating state. The first command creates **PSSession** objects on three computers and stores them in the `$s` variable. The second command uses `Invoke-Command` to run `Get-Process` in each of the three sessions in `$s`. The command uses the **AsJob** parameter to run the command asynchronously as a job. The command returns a job object, just like the jobs started by using `Start-Job`, and the job object is stored in the `$j` variable. The third command uses a pipeline operator (`|`) to send the job object in `$j` to the `Wait-Job` cmdlet. An `Invoke-Command` command is not required in this case, because the job resides on the local computer. ### Example 10: Wait for a job that has an ID ```powershell Get-Job ``` ```Output Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 1 Job1 Completed True localhost,Server01.. Get-Service 4 Job4 Completed True localhost dir | where ``` ```powershell Wait-Job -Id 1 ``` This command waits for the job with an ID value of 1. ## PARAMETERS ### -Any Indicates that this cmdlet returns the job object and continues execution when any job finishes. By default, `Wait-Job` waits until all of the specified jobs are complete before it displays the prompt. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Filter Specifies a hash table of conditions. This cmdlet waits for jobs that satisfy all of the conditions in the hash table. Enter a hash table where the keys are job properties and the values are job property values. This parameter works only on custom job types, such as workflow jobs and scheduled jobs. It does not work on standard jobs, such as those created by using the `Start-Job` cmdlet. For information about support for this parameter, see the help topic for the job type. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Collections.Hashtable Parameter Sets: FilterParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Force Indicates that this cmdlet continues to wait for jobs in the Suspended or Disconnected state. By default, `Wait-Job` returns, or ends the wait, when jobs are in one of the following states: - Completed - Failed - Stopped - Suspended - Disconnected This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies an array of IDs of jobs for which this cmdlet waits. The ID is an integer that uniquely identifies the job in the current session. It is easier to remember and type than the instance ID, but it is unique only in the current session. You can type one or more IDs, separated by commas. To find the ID of a job, type `Get-Job`. ```yaml Type: System.Int32[] Parameter Sets: SessionIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InstanceId Specifies an array of instance IDs of jobs for which this cmdlet waits. The default is all jobs. An instance ID is a GUID that uniquely identifies the job on the computer. To find the instance ID of a job, use `Get-Job`. ```yaml Type: System.Guid[] Parameter Sets: InstanceIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Job Specifies the jobs for which this cmdlet waits. Enter a variable that contains the job objects or a command that gets the job objects. You can also use a pipeline operator to send job objects to the `Wait-Job` cmdlet. By default, `Wait-Job` waits for all jobs created in the current session. ```yaml Type: System.Management.Automation.Job[] Parameter Sets: JobParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Name Specifies friendly names of jobs for which this cmdlet waits. ```yaml Type: System.String[] Parameter Sets: NameParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -State Specifies a job state. This cmdlet waits only for jobs in the specified state. The acceptable values for this parameter are: - NotStarted - Running - Completed - Failed - Stopped - Blocked - Suspended - Disconnected - Suspending - Stopping For more information about job states, see [JobState Enumeration](/dotnet/api/system.management.automation.jobstate). ```yaml Type: System.Management.Automation.JobState Parameter Sets: StateParameterSet Aliases: Accepted values: NotStarted, Running, Completed, Failed, Stopped, Blocked, Suspended, Disconnected, Suspending, Stopping, AtBreakpoint Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Timeout Specifies the maximum wait time for each job, in seconds. The default value, -1, indicates that the cmdlet waits until the job finishes. The timing starts when you submit the `Wait-Job` command, not the `Start-Job` command. If this time is exceeded, the wait ends and execution continues, even if the job is still running. The command does not display any error message. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: TimeoutSec Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.RemotingJob You can pipe a job object to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSRemotingJob This cmdlet returns job objects that represent the jobs in a terminating state. If the wait ends because the value of the **Timeout** parameter is exceeded, `Wait-Job` does not return any objects. ## NOTES PowerShell includes the following aliases for `Wait-Job`: - All platforms: - `wjb` By default, `Wait-Job` returns, or ends the wait, when jobs are in one of the following states: - Completed - Failed - Stopped - Suspended - Disconnected To direct `Wait-Job` to continue to wait for Suspended and Disconnected jobs, use the **Force** parameter. ## RELATED LINKS [Get-Job](Get-Job.md) [Invoke-Command](Invoke-Command.md) [Receive-Job](Receive-Job.md) [Remove-Job](Remove-Job.md) [Start-Job](Start-Job.md) [Stop-Job](Stop-Job.md)

#File: reference/7.6/Microsoft.PowerShell.Core/Where-Object.md

--- external help file: System.Management.Automation.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Core ms.date: 04/23/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.core/where-object?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Where-Object --- # Where-Object ## SYNOPSIS Selects objects from a collection based on their property values. ## SYNTAX ### EqualSet (Default) ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] [-EQ] [<CommonParameters>] ``` ### ScriptBlockSet ``` Where-Object [-InputObject <PSObject>] [-FilterScript] <ScriptBlock> [<CommonParameters>] ``` ### MatchSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -Match [<CommonParameters>] ``` ### CaseSensitiveEqualSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -CEQ [<CommonParameters>] ``` ### NotEqualSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -NE [<CommonParameters>] ``` ### CaseSensitiveNotEqualSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -CNE [<CommonParameters>] ``` ### GreaterThanSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -GT [<CommonParameters>] ``` ### CaseSensitiveGreaterThanSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -CGT [<CommonParameters>] ``` ### LessThanSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -LT [<CommonParameters>] ``` ### CaseSensitiveLessThanSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -CLT [<CommonParameters>] ``` ### GreaterOrEqualSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -GE [<CommonParameters>] ``` ### CaseSensitiveGreaterOrEqualSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -CGE [<CommonParameters>] ``` ### LessOrEqualSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -LE [<CommonParameters>] ``` ### CaseSensitiveLessOrEqualSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -CLE [<CommonParameters>] ``` ### LikeSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -Like [<CommonParameters>] ``` ### CaseSensitiveLikeSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -CLike [<CommonParameters>] ``` ### NotLikeSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -NotLike [<CommonParameters>] ``` ### CaseSensitiveNotLikeSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -CNotLike [<CommonParameters>] ``` ### CaseSensitiveMatchSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -CMatch [<CommonParameters>] ``` ### NotMatchSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -NotMatch [<CommonParameters>] ``` ### CaseSensitiveNotMatchSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -CNotMatch [<CommonParameters>] ``` ### ContainsSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -Contains [<CommonParameters>] ``` ### CaseSensitiveContainsSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -CContains [<CommonParameters>] ``` ### NotContainsSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -NotContains [<CommonParameters>] ``` ### CaseSensitiveNotContainsSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -CNotContains [<CommonParameters>] ``` ### InSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -In [<CommonParameters>] ``` ### CaseSensitiveInSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -CIn [<CommonParameters>] ``` ### NotInSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -NotIn [<CommonParameters>] ``` ### CaseSensitiveNotInSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -CNotIn [<CommonParameters>] ``` ### IsSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -Is [<CommonParameters>] ``` ### IsNotSet ``` Where-Object [-InputObject <PSObject>] [-Property] <String> [[-Value] <Object>] -IsNot [<CommonParameters>] ``` ### Not ``` Where-Object [-InputObject <PSObject>] [-Property] <String> -Not [<CommonParameters>] ``` ## DESCRIPTION The `Where-Object` cmdlet selects objects that have particular property values from the collection of objects that are passed to it. For example, you can use the `Where-Object` cmdlet to select files that were created after a certain date, events with a particular ID, or computers that use a particular version of Windows. Starting in Windows PowerShell 3.0, there are two different ways to construct a `Where-Object` command. - **Script block syntax**. You can use a script block to specify the property name, a comparison operator, and a property value. `Where-Object` returns all objects for which the script block statement is true. For example, the following command gets processes where the value of the **PriorityClass** property equals `Normal`. `Get-Process | Where-Object {$_.PriorityClass -eq "Normal"}` All PowerShell comparison operators are valid in the script block format. For more information, see [about_Comparison_Operators](./About/about_Comparison_Operators.md). - **Simplified syntax**. To enable the simiplified syntax, `Where-Object` includes 31 switch parameters that represent the comparison operators. The simplified syntax is easier to read and write than the script block syntax. You can combine one of the switch parameters with the **Property** and **Value** parameters to create a command that filters objects based on the values of their properties. For example, the following commands also get processes that have a priority class of `Normal`. These commands are equivalent and you can use them interchangeably. `Get-Process | Where-Object -Property PriorityClass -Value Normal -EQ` `Get-Process | Where-Object PriorityClass -EQ Normal` As shown in the example, the parameter names **Property** and **Value** are optional. The **Property** parameter is a positional parameter mapped to position `0`. The **Value** parameter is a positional parameter mapped to position `1`. The switch parameter, used to specify the comparison, can be used in any position. The simplfied syntax was introduced in Windows PowerShell 3.0. For more information, see [about_Simplified_Syntax](About/about_Simplified_Syntax.md). When you provide a single **Property** to `Where-Object`, the cmdlet treats the value of the property as a boolean expression. When the value of the property's **Length** isn't zero, the expression evaluates to `$true`. For example: `('hi', '', 'there') | Where-Object Length` The previous example is functionally equivalent to: - `('hi', '', 'there') | Where-Object Length -GT 0` - `('hi', '', 'there') | Where-Object { $_.Length -gt 0 }` For more information about how PowerShell evaluates booleans, see [about_Booleans](about/about_Booleans.md). ## EXAMPLES ### Example 1: Get stopped services These commands get a list of all services that are stopped. The `$_` automatic variable represents each object that's passed to the `Where-Object` cmdlet. The first command uses the script block format, the second command uses the comparison statement format. The commands filter the services the same way and return the same output. Only the syntax is different. ```powershell Get-Service | Where-Object { $_.Status -eq "Stopped" } Get-Service | Where-Object Status -EQ "Stopped" ``` ### Example 2: Get processes based on working set These commands list processes that have a working set greater than 250 megabytes (MB). The commands filter the processes the same way and return the same output. Only the syntax is different. ```powershell Get-Process | Where-Object { $_.WorkingSet -gt 250MB } Get-Process | Where-Object WorkingSet -GT 250MB ``` ### Example 3: Get processes based on process name These commands get the processes that have a **ProcessName** property value that begins with the letter `p`. The `-match` operator and **Match** parameter let you use regular expression matches. The commands filter the processes the same way and return the same output. Only the syntax is different. ```powershell Get-Process | Where-Object { $_.ProcessName -match "^p.*" } Get-Process | Where-Object ProcessName -Match "^p.*" ``` ### Example 4: Use the comparison statement format This example shows how to use the new comparison statement format of the `Where-Object` cmdlet. The first command uses the comparison statement format. It doesn't use any aliases and includes the name for every parameter. The second command is the more natural use of the comparison command format. The command substitutes the `where` alias for the `Where-Object` cmdlet name and omits all optional parameter names. The commands filter the processes the same way and return the same output. Only the syntax is different. ```powershell Get-Process | Where-Object -Property Handles -GE -Value 1000 Get-Process | where Handles -GE 1000 ``` ### Example 5: Get commands based on properties This example shows how to write commands that return items that are true or false or have any value for a specified property. Each example shows both the script block and comparison statement formats for the command. The commands filter their input the same way and return the same output. Only the syntax is different. ```powershell # Use Where-Object to get commands that have any value for the OutputType # property of the command. This omits commands that do not have an OutputType # property and those that have an OutputType property, but no property value. Get-Command | Where-Object OutputType Get-Command | Where-Object { $_.OutputType } ``` ```powershell # Use Where-Object to get objects that are containers. This gets objects that # have the **PSIsContainer** property with a value of $true and excludes all # others. Get-ChildItem | Where-Object PSIsContainer Get-ChildItem | Where-Object { $_.PSIsContainer } ``` ```powershell # Finally, use the -not operator (!) to get objects that are not containers. # This gets objects that do have the **PSIsContainer** property and those # that have a value of $false for the **PSIsContainer** property. Get-ChildItem | Where-Object -Not PSIsContainer Get-ChildItem | Where-Object { !$_.PSIsContainer } ``` ### Example 6: Use multiple conditions ```powershell Get-Module -ListAvailable | Where-Object { ($_.Name -notlike "Microsoft*" -and $_.Name -notlike "PS*") -and $_.HelpInfoUri } ``` This example shows how to create a `Where-Object` command with multiple conditions. This command gets non-core modules that support the Updatable Help feature. The command uses the **ListAvailable** parameter of the `Get-Module` cmdlet to get all modules on the computer. A pipeline operator (`|`) sends the modules to the `Where-Object` cmdlet, which gets modules whose names don't begin with `Microsoft` or `PS`, and have a value for the **HelpInfoURI** property, which tells PowerShell where to find updated help files for the module. The `-and` logical operator connects the comparison statements. The example uses the script block command format. Logical operators, such as `-and`,`-or`, and `-not` are valid only in script blocks. You can't use them in the comparison statement format of a `Where-Object` command. - For more information about PowerShell logical operators, see [about_Logical_Operators](./About/about_logical_operators.md). - For more information about the Updatable Help feature, see [about_Updatable_Help](./About/about_Updatable_Help.md). ## PARAMETERS ### -CContains Indicates that this cmdlet gets objects from a collection if the property value of the object is an exact match for the specified value. This operation is case-sensitive. For example: `Get-Process | Where-Object ProcessName -CContains "svchost"` **CContains** refers to a collection of values and is true if the collection contains an item that is an exact match for the specified value. If the input is a single object, PowerShell converts it to a collection of one object. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CaseSensitiveContainsSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CEQ Indicates that this cmdlet gets objects if the property value is the same as the specified value. This operation is case-sensitive. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CaseSensitiveEqualSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CGE Indicates that this cmdlet gets objects if the property value is greater than or equal to the specified value. This operation is case-sensitive. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CaseSensitiveGreaterOrEqualSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CGT Indicates that this cmdlet gets objects if the property value is greater than the specified value. This operation is case-sensitive. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CaseSensitiveGreaterThanSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CIn Indicates that this cmdlet gets objects if the property value includes the specified value. This operation is case-sensitive. For example: `Get-Process | Where-Object -Value "svchost" -CIn ProcessName` **CIn** resembles **CContains**, except that the property and value positions are reversed. For example, the following statements are both true. `"abc", "def" -CContains "abc"` `"abc" -CIn "abc", "def"` This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CaseSensitiveInSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CLE Indicates that this cmdlet gets objects if the property value is less-than or equal to the specified value. This operation is case-sensitive. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CaseSensitiveLessOrEqualSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CLike Indicates that this cmdlet gets objects if the property value matches a value that includes wildcard characters (`*`). This operation is case-sensitive. For example: `Get-Process | Where-Object ProcessName -CLike "*host"` This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CaseSensitiveLikeSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CLT Indicates that this cmdlet gets objects if the property value is less-than the specified value. This operation is case-sensitive. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CaseSensitiveLessThanSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CMatch Indicates that this cmdlet gets objects if the property value matches the specified regular expression. This operation is case-sensitive. When the input is a single object, the matched value is saved in the `$Matches` automatic variable. For example: `Get-Process | Where-Object ProcessName -CMatch "Shell"` This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CaseSensitiveMatchSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CNE Indicates that this cmdlet gets objects if the property value is different than the specified value. This operation is case-sensitive. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CaseSensitiveNotEqualSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CNotContains Indicates that this cmdlet gets objects if the property value of the object isn't an exact match for the specified value. This operation is case-sensitive. For example: `Get-Process | Where-Object ProcessName -CNotContains "svchost"` **NotContains** and **CNotContains** refer to a collection of values and are true when the collection doesn't contain any items that are an exact match for the specified value. If the input is a single object, PowerShell converts it to a collection of one object. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CaseSensitiveNotContainsSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CNotIn Indicates that this cmdlet gets objects if the property value isn't an exact match for the specified value. This operation is case-sensitive. For example: `Get-Process | Where-Object -Value "svchost" -CNotIn -Property ProcessName` **NotIn** and **CNotIn** operators resemble **NotContains** and **CNotContains**, except that the property and value positions are reversed. For example, the following statements are true. `"abc", "def" -CNotContains "Abc"` `"abc" -CNotIn "Abc", "def"` ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CaseSensitiveNotInSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CNotLike Indicates that this cmdlet gets objects if the property value doesn't match a value that includes wildcard characters. This operation is case-sensitive. For example: `Get-Process | Where-Object ProcessName -CNotLike "*host"` This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CaseSensitiveNotLikeSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CNotMatch Indicates that this cmdlet gets objects if the property value doesn't match the specified regular expression. This operation is case-sensitive. When the input is a single object, the matched value is saved in the `$Matches` automatic variable. For example: `Get-Process | Where-Object ProcessName -CNotMatch "Shell"` This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CaseSensitiveNotMatchSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Contains Indicates that this cmdlet gets objects if any item in the property value of the object is an exact match for the specified value. For example: `Get-Process | Where-Object ProcessName -Contains "Svchost"` If the input is a single object, PowerShell converts it to a collection of one object. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ContainsSet Aliases: IContains Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -EQ Indicates that this cmdlet gets objects if the property value is the same as the specified value. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: EqualSet Aliases: IEQ Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FilterScript Specifies the script block that's used to filter the objects. Enclose the script block in braces (`{}`). The parameter name, **FilterScript**, is optional. ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: ScriptBlockSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -GE Indicates that this cmdlet gets objects if the property value is greater than or equal to the specified value. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: GreaterOrEqualSet Aliases: IGE Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -GT Indicates that this cmdlet gets objects if the property value is greater than the specified value. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: GreaterThanSet Aliases: IGT Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -In Indicates that this cmdlet gets objects if the property value matches any of the specified values. For example: `Get-Process | Where-Object -Property ProcessName -In -Value "Svchost", "TaskHost", "WsmProvHost"` If the input is a single object, PowerShell converts it to a collection of one object. If the property value of an object is an array, PowerShell uses reference equality to determine a match. `Where-Object` returns the object only if the value of the **Property** parameter and any value of **Value** are the same instance of an object. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: InSet Aliases: IIn Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects to filter. You can also pipe the objects to `Where-Object`. When you use the **InputObject** parameter with `Where-Object`, instead of piping command results to `Where-Object`, the cmdlet treats the **InputObject** as a single object. This is true even if the value is a collection that's the result of a command, such as `-InputObject (Get-Process)`. Because **InputObject** can't return individual properties from an array or collection of objects, we recommend that, if you use `Where-Object` to filter a collection of objects for those objects that have specific values in defined properties, you use `Where-Object` in the pipeline, as shown in the examples in this topic. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Is Indicates that this cmdlet gets objects if the property value is an instance of the specified .NET type. Enclose the type name in square brackets. For example, `Get-Process | Where-Object StartTime -Is [datetime]` This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: IsSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -IsNot Indicates that this cmdlet gets objects if the property value isn't an instance of the specified .NET type. For example, `Get-Process | where StartTime -IsNot [datetime]` This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: IsNotSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LE Indicates that this cmdlet gets objects if the property value is less than or equal to the specified value. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: LessOrEqualSet Aliases: ILE Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Like Indicates that this cmdlet gets objects if the property value matches a value that includes wildcard characters (`*`). For example: `Get-Process | Where-Object ProcessName -Like "*host"` This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: LikeSet Aliases: ILike Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LT Indicates that this cmdlet gets objects if the property value is less than the specified value. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: LessThanSet Aliases: ILT Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Match Indicates that this cmdlet gets objects if the property value matches the specified regular expression. When the input is a single object, the matched value is saved in the `$Matches` automatic variable. For example: `Get-Process | Where-Object ProcessName -Match "shell"` This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: MatchSet Aliases: IMatch Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NE Indicates that this cmdlet gets objects if the property value is different than the specified value. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: NotEqualSet Aliases: INE Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Not Indicates that this cmdlet gets objects if the property doesn't exist or has a value of `$null` or `$false`. For example: `Get-Service | Where-Object -Not "DependentServices"` This parameter was introduced in Windows PowerShell 6.1. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Not Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NotContains Indicates that this cmdlet gets objects if none of the items in the property value is an exact match for the specified value. For example: `Get-Process | Where-Object ProcessName -NotContains "Svchost"` **NotContains** refers to a collection of values and is true if the collection doesn't contain any items that are an exact match for the specified value. If the input is a single object, PowerShell converts it to a collection of one object. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: NotContainsSet Aliases: INotContains Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NotIn Indicates that this cmdlet gets objects if the property value isn't an exact match for any of the specified values. For example: `Get-Process | Where-Object -Value "svchost" -NotIn -Property ProcessName` If the value of **Value** is a single object, PowerShell converts it to a collection of one object. If the property value of an object is an array, PowerShell uses reference equality to determine a match. `Where-Object` returns the object only if the value of **Property** and any value of **Value** aren't the same instance of an object. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: NotInSet Aliases: INotIn Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NotLike Indicates that this cmdlet gets objects if the property value doesn't match a value that includes wildcard characters (`*`). For example: `Get-Process | Where-Object ProcessName -NotLike "*host"` This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: NotLikeSet Aliases: INotLike Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NotMatch Indicates that this cmdlet gets objects when the property value doesn't match the specified regular expression. When the input is a single object, the matched value is saved in the `$Matches` automatic variable. For example: `Get-Process | Where-Object ProcessName -NotMatch "powershell"` This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: NotMatchSet Aliases: INotMatch Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Property Specifies the name of a property of the input object. The property must be an instance property, not a static property. This is a positional parameter, so the name, **Property**, is optional. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String Parameter Sets: EqualSet, LessOrEqualSet, CaseSensitiveEqualSet, NotEqualSet, CaseSensitiveNotEqualSet, GreaterThanSet, CaseSensitiveGreaterThanSet, LessThanSet, CaseSensitiveLessThanSet, GreaterOrEqualSet, CaseSensitiveGreaterOrEqualSet, CaseSensitiveLessOrEqualSet, LikeSet, CaseSensitiveLikeSet, NotLikeSet, CaseSensitiveNotLikeSet, MatchSet, CaseSensitiveMatchSet, NotMatchSet, CaseSensitiveNotMatchSet, ContainsSet, CaseSensitiveContainsSet, NotContainsSet, CaseSensitiveNotContainsSet, InSet, CaseSensitiveInSet, NotInSet, CaseSensitiveNotInSet, IsSet, IsNotSet, Not Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Value Specifies a property value. The parameter name, **Value**, is optional. This parameter accepts wildcard characters when used with the following comparison parameters: - **CLike** - **CNotLike** - **Like** - **NotLike** This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: EqualSet, CaseSensitiveGreaterOrEqualSet, CaseSensitiveEqualSet, NotEqualSet, CaseSensitiveNotEqualSet, GreaterThanSet, CaseSensitiveGreaterThanSet, LessThanSet, CaseSensitiveLessThanSet, GreaterOrEqualSet, LessOrEqualSet, CaseSensitiveLessOrEqualSet, LikeSet, CaseSensitiveLikeSet, NotLikeSet, CaseSensitiveNotLikeSet, MatchSet, CaseSensitiveMatchSet, NotMatchSet, CaseSensitiveNotMatchSet, ContainsSet, CaseSensitiveContainsSet, NotContainsSet, CaseSensitiveNotContainsSet, InSet, CaseSensitiveInSet, NotInSet, CaseSensitiveNotInSet, IsSet, IsNotSet Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### System.Object This cmdlet returns the selected items from the input object set. ## NOTES PowerShell includes the following aliases for `Where-Object`: - All Platforms: - `?` - `where` Starting in Windows PowerShell 4.0, `Where` and `ForEach` methods were added for use with collections. You can read more about these methods here [about_Arrays](./About/about_Arrays.md) ## RELATED LINKS [Compare-Object](../Microsoft.PowerShell.Utility/Compare-Object.md) [ForEach-Object](ForEach-Object.md) [Group-Object](../Microsoft.PowerShell.Utility/Group-Object.md) [Measure-Object](../Microsoft.PowerShell.Utility/Measure-Object.md) [New-Object](../Microsoft.PowerShell.Utility/New-Object.md) [Select-Object](../Microsoft.PowerShell.Utility/Select-Object.md) [Sort-Object](../Microsoft.PowerShell.Utility/Sort-Object.md) [Tee-Object](../Microsoft.PowerShell.Utility/Tee-Object.md) [about_Booleans](./About/about_Booleans.md)

#File: reference/7.6/Microsoft.PowerShell.Diagnostics/Get-Counter.md

--- external help file: Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Diagnostics ms.date: 05/08/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.diagnostics/get-counter?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Counter --- # Get-Counter ## SYNOPSIS Gets performance counter data from local and remote computers. ## SYNTAX ### GetCounterSet (Default) ``` Get-Counter [[-Counter] <String[]>] [-SampleInterval <Int32>] [-MaxSamples <Int64>] [-Continuous] [-ComputerName <String[]>] [<CommonParameters>] ``` ### ListSetSet ``` Get-Counter [-ListSet] <String[]> [-ComputerName <String[]>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Get-Counter` cmdlet gets performance counter data directly from the performance monitoring instrumentation in the Windows family of operating systems. `Get-Counter` gets performance data from a local computer or remote computers. You can use the `Get-Counter` parameters to specify one or more computers, list the performance counter sets and the instances they contain, set the sample intervals, and specify the maximum number of samples. Without parameters, `Get-Counter` gets performance counter data for a set of system counters. Many counter sets are protected by access control lists (ACL). To see all counter sets, open PowerShell with the **Run as administrator** option. This cmdlet was reintroduced in PowerShell 7. > [!NOTE] > Performance counter names are localized. The examples shown here use the English names of the > performance objects, counters, and instances. The names will be different on a system that uses > another language. Use the `Get-Counter -ListSet` command to see the localized names. ## EXAMPLES ### Example 1: Get the counter set list This example gets the local computer's list of counter sets. ```powershell Get-Counter -ListSet * ``` ```Output CounterSetName : Processor MachineName : . CounterSetType : MultiInstance Description : The Processor performance object consists of counters that measure aspects ... computer that performs arithmetic and logical computations, initiates ... computer can have multiple processors. The processor object represents ... Paths : {\Processor(*)\% Processor Time, \Processor(*)\% User Time, ... PathsWithInstances : {\Processor(0)\% Processor Time, \Processor(1)\% Processor Time, ... Counter : {\Processor(*)\% Processor Time, \Processor(*)\% User Time, ... ``` `Get-Counter` uses the **ListSet** parameter with an asterisk (`*`) to get the list of counter sets. The dot (`.`) in the **MachineName** column represents the local computer. ### Example 2: Specify the SampleInterval and MaxSamples This examples gets the counter data for all processors on the local computer. Data is collected at two-second intervals until there are three samples. ```powershell Get-Counter -Counter "\Processor(_Total)\% Processor Time" -SampleInterval 2 -MaxSamples 3 ``` ```Output Timestamp CounterSamples --------- -------------- 6/18/2019 14:39:56 \\Computer01\processor(_total)\% processor time : 20.7144271584086 6/18/2019 14:39:58 \\Computer01\processor(_total)\% processor time : 10.4391790575511 6/18/2019 14:40:01 \\Computer01\processor(_total)\% processor time : 37.5968799396998 ``` `Get-Counter` uses the **Counter** parameter to specify the counter path `\Processor(_Total)\% Processor Time`. The **SampleInterval** parameter sets a two-second interval to check the counter. **MaxSamples** determines that three is the maximum number of times to check the counter. ### Example 3: Get continuous samples of a counter This examples gets continuous samples for a counter every second. To stop the command, press <kbd>CTRL</kbd>+<kbd>C</kbd>. To specify a longer interval between samples, use the **SampleInterval** parameter. ```powershell Get-Counter -Counter "\Processor(_Total)\% Processor Time" -Continuous ``` ```Output Timestamp CounterSamples --------- -------------- 6/19/2019 15:35:03 \\Computer01\processor(_total)\% processor time : 43.8522842937022 6/19/2019 15:35:04 \\Computer01\processor(_total)\% processor time : 29.7896844697383 6/19/2019 15:35:05 \\Computer01\processor(_total)\% processor time : 29.4962645638135 6/19/2019 15:35:06 \\Computer01\processor(_total)\% processor time : 25.5901500127408 ``` `Get-Counter` uses the **Counter** parameter to specify the `\Processor\% Processor Time` counter. The **Continuous** parameter specifies to get samples every second until the command is stopped with <kbd>CTRL</kbd>+<kbd>C</kbd>. ### Example 4: Alphabetical list of counter sets This example uses the pipeline to get the counter list set and then sort the list in alphabetical order. ```powershell Get-Counter -ListSet * | Sort-Object -Property CounterSetName | Format-Table CounterSetName, CounterSetType -AutoSize ``` ```Output CounterSetName CounterSetType -------------- -------------- .NET CLR Data SingleInstance .NET Data Provider for SqlServer SingleInstance AppV Client Streamed Data Percentage SingleInstance Authorization Manager Applications SingleInstance BitLocker MultiInstance Bluetooth Device SingleInstance Cache SingleInstance Client Side Caching SingleInstance ``` `Get-Counter` uses the **ListSet** parameter with an asterisk (`*`) to get a complete list of counter sets. The **CounterSet** objects are sent down the pipeline. `Sort-Object` uses the **Property** parameter to specify that the objects are sorted by **CounterSetName**. The objects are sent down the pipeline to `Format-Table`. The **AutoSize** parameter adjusts the column widths to minimize truncation. The dot (`.`) in the **MachineName** column represents the local computer. ### Example 5: Run a background job to get counter data In this example, `Start-Job` runs a `Get-Counter` command as a background job on the local computer. To view the performance counter output from the job, use the `Receive-Job` cmdlet. ```powershell Start-Job -ScriptBlock {Get-Counter -Counter "\LogicalDisk(_Total)\% Free Space" -MaxSamples 1000} ``` ```Output Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 1 Job1 BackgroundJob Running True localhost Get-Counter -Counter ``` `Start-Job` uses the **ScriptBlock** parameter to run a `Get-Counter` command. `Get-Counter` uses the **Counter** parameter to specify the counter path `\LogicalDisk(_Total)\% Free Space`. The **MaxSamples** parameter specifies to get 1000 samples of the counter. ### Example 6: Get counter data from multiple computers This example uses a variable to get performance counter data from two computers. ```powershell $DiskReads = "\LogicalDisk(C:)\Disk Reads/sec" $DiskReads | Get-Counter -ComputerName Server01, Server02 -MaxSamples 10 ``` ```Output Timestamp CounterSamples --------- -------------- 6/21/2019 10:51:04 \\Server01\logicaldisk(C:)\disk reads/sec : 0 \\Server02\logicaldisk(C:)\disk reads/sec : 0.983050344269146 ``` The `$DiskReads` variable stores the `\LogicalDisk(C:)\Disk Reads/sec` counter path. The `$DiskReads` variable is sent down the pipeline to `Get-Counter`. **Counter** is the first position parameter and accepts the path stored in `$DiskReads`. **ComputerName** specifies the two computers and **MaxSamples** specifies to get 10 samples from each computer. ### Example 7: Get a counter's instance values from multiple random computers This example gets the value of a performance counter on 50 random, remote computers in the enterprise. The **ComputerName** parameter uses random computer names stored in a variable. To update the computer names in the variable, recreate the variable. An alternative for the server names in the **ComputerName** parameter is to use a text file. For example: `-ComputerName (Get-Random (Get-Content -Path C:\Servers.txt) -Count 50)` The counter path includes an asterisk (`*`) in the instance name to get the data for each of the remote computer's processors. ```powershell $Servers = Get-Random (Get-Content -Path C:\Servers.txt) -Count 50 $Counter = "\Processor(*)\% Processor Time" Get-Counter -Counter $Counter -ComputerName $Servers ``` ```Output Timestamp CounterSamples --------- -------------- 6/20/2019 12:20:35 \\Server01\processor(0)\% processor time : 6.52610319637854 \\Server01\processor(1)\% processor time : 3.41030663625782 \\Server01\processor(2)\% processor time : 9.64189975649925 \\Server01\processor(3)\% processor time : 1.85240835619747 \\Server01\processor(_total)\% processor time : 5.35768447160776 ``` The `Get-Random` cmdlet uses `Get-Content` to select 50 random computer names from the `Servers.txt` file. The remote computer names are stored in the `$Servers` variable. The `\Processor(*)\% Processor Time` counter's path is stored in the `$Counter` variable. `Get-Counter` uses the **Counter** parameter to specify the counters in the `$Counter` variable. The **ComputerName** parameter specifies the computer names in the `$Servers` variable. ### Example 8: Use the Path property to get formatted path names This example uses the **Path** property of a counter set to find the formatted path names for the performance counters. The pipeline is used with the `Where-Object` cmdlet to find a subset of the path names. To find a counter sets complete list of counter paths, remove the pipeline (`|`) and `Where-Object` command. The `$_` is an automatic variable for the current object in the pipeline. For more information, see [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md). ```powershell (Get-Counter -ListSet Memory).Paths | Where-Object { $_ -like "*Cache*" } ``` ```Output \Memory\Cache Faults/sec \Memory\Cache Bytes \Memory\Cache Bytes Peak \Memory\System Cache Resident Bytes \Memory\Standby Cache Reserve Bytes \Memory\Standby Cache Normal Priority Bytes \Memory\Standby Cache Core Bytes \Memory\Long-Term Average Standby Cache Lifetime (s) ``` `Get-Counter` uses the **ListSet** parameter to specify the **Memory** counter set. The command is enclosed in parentheses so that the **Paths** property returns each path as a string. The objects are sent down the pipeline to `Where-Object`. `Where-Object` uses the variable `$_` to process each object and uses the `-like` operator to find matches for the string `*Cache*`. The asterisks (`*`) are wildcards for any characters. ### Example 9: Use the PathsWithInstances property to get formatted path names This example gets the formatted path names that include the instances for the **PhysicalDisk** performance counters. ```powershell (Get-Counter -ListSet PhysicalDisk).PathsWithInstances ``` ```Output \PhysicalDisk(0 C:)\Current Disk Queue Length \PhysicalDisk(_Total)\Current Disk Queue Length \PhysicalDisk(0 C:)\% Disk Time \PhysicalDisk(_Total)\% Disk Time \PhysicalDisk(0 C:)\Avg. Disk Queue Length \PhysicalDisk(_Total)\Avg. Disk Queue Length \PhysicalDisk(0 C:)\% Disk Read Time \PhysicalDisk(_Total)\% Disk Read Time ``` `Get-Counter` uses the **ListSet** parameter to specify the **PhysicalDisk** counter set. The command is enclosed in parentheses so that the **PathsWithInstances** property returns each path instance as a string. ### Example 10: Get a single value for each counter in a counter set In this example, a single value is returned for each performance counter in the local computer's **Memory** counter set. ```powershell $MemCounters = (Get-Counter -ListSet Memory).Paths Get-Counter -Counter $MemCounters ``` ```Output Timestamp CounterSamples --------- -------------- 6/19/2019 12:05:00 \\Computer01\memory\page faults/sec : 868.772077545597 \\Computer01\memory\available bytes : 9031176192 \\Computer01\memory\committed bytes : 8242982912 \\Computer01\memory\commit limit : 19603333120 ``` `Get-Counter` uses the **ListSet** parameter to specify the **Memory** counter set. The command is enclosed in parentheses so that the **Paths** property returns each path as a string. The paths are stored in the `$MemCounters` variable. `Get-Counter` uses the **Counter** parameter to specify the counter paths in the `$MemCounters` variable. ### Example 11: Display an object's property values The property values in the **PerformanceCounterSample** object represent each data sample. In this example we use the properties of the **CounterSamples** object to examine, select, sort, and group the data. ```powershell $Counter = "\\Server01\Process(Idle)\% Processor Time" $Data = Get-Counter $Counter $Data.CounterSamples | Format-List -Property * ``` ```Output Path : \\Server01\process(idle)\% processor time InstanceName : idle CookedValue : 198.467899571389 RawValue : 14329160321003 SecondValue : 128606459528326201 MultipleCount : 1 CounterType : Timer100Ns Timestamp : 6/19/2019 12:20:49 Timestamp100NSec : 128606207528320000 Status : 0 DefaultScale : 0 TimeBase : 10000000 ``` The counter path is stored in the `$Counter` variable. `Get-Counter` gets one sample of the counter values and stores the results in the `$Data` variable. The `$Data` variable uses the **CounterSamples** property to get the object's properties. The object is sent down the pipeline to `Format-List`. The **Property** parameter uses an asterisk (`*`) wildcard to select all the properties. ### Example 12: Performance counter array values In this example, a variable stores each performance counter. The **CounterSamples** property is an array that can display specific counter values. To display each counter sample, use `$Counter.CounterSamples`. ```powershell $Counter = Get-Counter -Counter "\Processor(*)\% Processor Time" $Counter.CounterSamples[0] ``` ```Output Path InstanceName CookedValue ---- ------------ ----------- \\Computer01\processor(0)\% processor time 0 1.33997091699662 ``` `Get-Counter` uses the **Counter** parameter to specify the counter `\Processor(*)\% Processor Time`. The values are stored in the `$Counter` variable. `$Counter.CounterSamples[0]` displays the array value for the first counter value. ### Example 13: Compare performance counter values This example finds the amount of processor time used by each processor on the local computer. The **CounterSamples** property is used to compare the counter data against a specified value. To display each counter sample, use `$Counter.CounterSamples`. ```powershell $Counter = Get-Counter -Counter "\Processor(*)\% Processor Time" $Counter.CounterSamples | Where-Object { $_.CookedValue -lt "20" } ``` ```Output Path InstanceName CookedValue ---- ------------ ----------- \\Computer01\processor(0)\% processor time 0 12.6398025240208 \\Computer01\processor(1)\% processor time 1 15.7598095767344 ``` `Get-Counter` uses the **Counter** parameter to specify the counter `\Processor(*)\% Processor Time`. The values are stored in the `$Counter` variable. The objects stored in `$Counter.CounterSamples` are sent down the pipeline. `Where-Object` uses a script block to compare each objects value against a specified value of `20`. The `$_.CookedValue` is a variable for the current object in the pipeline. Counters with a **CookedValue** that is less than 20 are displayed. ### Example 14: Sort performance counter data This example shows how to sort performance counter data. The example finds the processes on the computer that are using the most processor time during the sample. ```powershell $Procs = Get-Counter -Counter "\Process(*)\% Processor Time" $Procs.CounterSamples | Sort-Object -Property CookedValue -Descending | Format-Table -Property Path, InstanceName, CookedValue -AutoSize ``` ```Output Path InstanceName CookedValue ---- ------------ ----------- \\Computer01\process(_total)\% processor time _total 395.464129650573 \\Computer01\process(idle)\% processor time idle 389.356575524695 \\Computer01\process(mssense)\% processor time mssense 3.05377706293879 \\Computer01\process(csrss#1)\% processor time csrss 1.52688853146939 \\Computer01\process(microsoftedgecp#10)\% processor time microsoftedgecp 1.52688853146939 \\Computer01\process(runtimebroker#5)\% processor time runtimebroker 0 \\Computer01\process(settingsynchost)\% processor time settingsynchost 0 \\Computer01\process(microsoftedgecp#16)\% processor time microsoftedgecp 0 ``` `Get-Counter` uses the **Counter** parameter to specify the `\Process(*)\% Processor Time` counter for all the processes on the local computer. The result is stored in the `$Procs` variable. The `$Procs` variable with the **CounterSamples** property sends the **PerformanceCounterSample** objects down the pipeline. `Sort-Object` uses the **Property** parameter to sort the objects by **CookedValue** in **Descending** order. `Format-Table` uses the **Property** parameter to select the columns for the output. The **AutoSize** parameter adjusts the column widths to minimize truncation. ## PARAMETERS ### -ComputerName Specifies one computer name or a comma-separated array of **remote** computer names. Use the NetBIOS name, an IP address, or the computer's fully qualified domain name. To get performance counter data from the **local** computer, exclude the **ComputerName** parameter. For output such as a **ListSet** that contains the **MachineName** column, a dot (`.`) indicates the local computer. `Get-Counter` doesn't rely on PowerShell remoting. You can use the **ComputerName** parameter even if your computer isn't configured to run remote commands. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Cn Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Continuous When **Continuous** is specified, `Get-Counter` gets samples until you press <kbd>CTRL</kbd>+<kbd>C</kbd>. Samples are obtained every second for each specified performance counter. Use the **SampleInterval** parameter to increase the interval between continuous samples. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: GetCounterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Counter Specifies the path to one or more counter paths. Paths are input as a comma-separated array, a variable, or values from a text file. You can send counter path strings down the pipeline to `Get-Counter`. Counter paths use the following syntax: `\\ComputerName\CounterSet(Instance)\CounterName` `\CounterSet(Instance)\CounterName` For example: `\\Server01\Processor(*)\% User Time` `\Processor(*)\% User Time` The `\\ComputerName` is optional in a performance counter path. If the counter path doesn't include the computer name, `Get-Counter` uses the local computer. An asterisk (`*`) in the instance is a wildcard character to get all instances of the counter. ```yaml Type: System.String[] Parameter Sets: GetCounterSet Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -ListSet Lists the performance counter sets on the computers. Use an asterisk (`*`) to specify all counter sets. Enter one name or a comma-separated string of counter set names. You can send counter set names down the pipeline. To get a counter sets formatted counter paths, use the **ListSet** parameter. The **Paths** and **PathsWithInstances** properties of each counter set contain the individual counter paths formatted as a string. You can save the counter path strings in a variable or use the pipeline to send the string to another `Get-Counter` command. For example to send each **Processor** counter path to `Get-Counter`: `Get-Counter -ListSet Processor | Get-Counter` > [!NOTE] > In PowerShell 7, `Get-Counter` can't retrieve the **Description** property of the counter set. The > **Description** is set to `$null`. ```yaml Type: System.String[] Parameter Sets: ListSetSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: True ``` ### -MaxSamples Specifies the number of samples to get from each specified performance counter. To get a constant stream of samples, use the **Continuous** parameter. If the **MaxSamples** parameter isn't specified, `Get-Counter` only gets one sample for each specified counter. To collect a large data set, run `Get-Counter` as a PowerShell background job. For more information, see [about_Jobs](../Microsoft.PowerShell.Core/About/about_Jobs.md). ```yaml Type: System.Int64 Parameter Sets: GetCounterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SampleInterval Specifies the number of seconds between samples for each specified performance counter. If the **SampleInterval** parameter isn't specified, `Get-Counter` uses a one-second interval. ```yaml Type: System.Int32 Parameter Sets: GetCounterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String[] `Get-Counter` accepts pipeline input for counter paths and counter set names. ## OUTPUTS ### Microsoft.PowerShell.Commands.GetCounter.CounterSet With the **ListSet** parameter, this cmdlet returns **CounterSet** objects. ### Microsoft.PowerShell.Commands.GetCounter.PerformanceCounterSampleSet By default and with the **Counter** parameter, this cmdlet returns **PerformanceCounterSampleSet** objects. ## NOTES If no parameters are specified, `Get-Counter` gets one sample for each specified performance counter. Use the **MaxSamples** and **Continuous** parameters to get more samples. `Get-Counter` uses a one-second interval between samples. Use the **SampleInterval** parameter to increase the interval. The **MaxSamples** and **SampleInterval** values apply to all the counters on each computer in the command. To set different values for different counters, enter separate `Get-Counter` commands. In PowerShell 7, when using the **ListSet** parameter, `Get-Counter` can't retrieve the **Description** property of the counter set. The **Description** is set to `$null`. ## RELATED LINKS [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md) [about_Jobs](../Microsoft.PowerShell.Core/About/about_Jobs.md) [Format-List](../Microsoft.PowerShell.Utility/Format-List.md) [Format-Table](../Microsoft.PowerShell.Utility/Format-Table.md) [Get-Member](../Microsoft.PowerShell.Utility/Get-Member.md) [Receive-Job](../Microsoft.PowerShell.Core/Receive-Job.md) [Start-Job](../Microsoft.PowerShell.Core/Start-Job.md) [Where-Object](..//Microsoft.PowerShell.Core/Where-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Diagnostics/Get-WinEvent.md

--- external help file: Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Diagnostics ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.diagnostics/get-winevent?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-WinEvent --- # Get-WinEvent ## SYNOPSIS Gets events from event logs and event tracing log files on local and remote computers. ## SYNTAX ### GetLogSet (Default) ``` Get-WinEvent [[-LogName] <String[]>] [-MaxEvents <Int64>] [-ComputerName <String>] [-Credential <PSCredential>] [-FilterXPath <String>] [-Force] [-Oldest] [<CommonParameters>] ``` ### ListLogSet ``` Get-WinEvent [-ListLog] <String[]> [-ComputerName <String>] [-Credential <PSCredential>] [-Force] [<CommonParameters>] ``` ### ListProviderSet ``` Get-WinEvent [-ListProvider] <String[]> [-ComputerName <String>] [-Credential <PSCredential>] [<CommonParameters>] ``` ### GetProviderSet ``` Get-WinEvent [-ProviderName] <String[]> [-MaxEvents <Int64>] [-ComputerName <String>] [-Credential <PSCredential>] [-FilterXPath <String>] [-Force] [-Oldest] [<CommonParameters>] ``` ### FileSet ``` Get-WinEvent [-Path] <String[]> [-MaxEvents <Int64>] [-Credential <PSCredential>] [-FilterXPath <String>] [-Oldest] [<CommonParameters>] ``` ### HashQuerySet ``` Get-WinEvent [-MaxEvents <Int64>] [-ComputerName <String>] [-Credential <PSCredential>] [-FilterHashtable] <Hashtable[]> [-Force] [-Oldest] [<CommonParameters>] ``` ### XmlQuerySet ``` Get-WinEvent [-MaxEvents <Int64>] [-ComputerName <String>] [-Credential <PSCredential>] [-FilterXml] <XmlDocument> [-Oldest] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Get-WinEvent` cmdlet gets events from event logs, including classic logs, such as the **System** and **Application** logs. The cmdlet gets data from event logs that are generated by the Windows Event Log technology introduced in Windows Vista and events in log files generated by **Event Tracing for Windows (ETW)**. By default, `Get-WinEvent` returns event information in the order of newest to oldest. `Get-WinEvent` lists event logs and event log providers. To interrupt the command, press <kbd>CTRL</kbd>+<kbd>C</kbd>. You can get events from selected logs or from logs generated by selected event providers. And, you can combine events from multiple sources in a single command. `Get-WinEvent` allows you to filter events using XPath queries, structured XML queries, and hash table queries. If you're not running PowerShell as an Administrator, you might see error messages that you cannot retrieve information about a log. ## EXAMPLES ### Example 1: Get all the logs from a local computer This command gets all the event logs on the local computer. Logs are listed in the order that `Get-WinEvent` gets them. Classic logs are retrieved first, followed by the new Windows Event logs. It's possible for a log's **RecordCount** to be null, which is blank, or zero. ```powershell Get-WinEvent -ListLog * ``` ```Output LogMode MaximumSizeInBytes RecordCount LogName ------- ------------------ ----------- ------- Circular 15532032 14500 Application Circular 1052672 117 Azure Information Protection Circular 1052672 3015 CxAudioSvcLog Circular 20971520 ForwardedEvents Circular 20971520 0 HardwareEvents ``` The `Get-WinEvent` cmdlet gets log information from the computer. The **ListLog** parameter uses the asterisk (`*`) wildcard to display information about each log. ### Example 2: Get the classic Setup log This command gets an **EventLogConfiguration** object that represents the classic **Setup** log. The object includes information about the log, such as file size, provider, file path, and whether the log is enabled. ```powershell Get-WinEvent -ListLog Setup | Format-List -Property * ``` ```Output FileSize : 69632 IsLogFull : False LastAccessTime : 3/13/2019 09:41:46 LastWriteTime : 3/13/2019 09:41:46 OldestRecordNumber : 1 RecordCount : 23 LogName : Setup LogType : Operational LogIsolation : Application IsEnabled : True IsClassicLog : False SecurityDescriptor : O:BAG:SYD: ... LogFilePath : %SystemRoot%\System32\Winevt\Logs\Setup.evtx MaximumSizeInBytes : 1052672 LogMode : Circular OwningProviderName : Microsoft-Windows-Eventlog ProviderNames : {Microsoft-Windows-WUSA, Microsoft-Windows-ActionQueue... ProviderLevel : ProviderKeywords : ProviderBufferSize : 64 ProviderMinimumNumberOfBuffers : 0 ProviderMaximumNumberOfBuffers : 64 ProviderLatency : 1000 ProviderControlGuid : ``` The `Get-WinEvent` cmdlet uses the **ListLog** parameter to specify the **Setup** log. The object is sent down the pipeline to the `Format-List` cmdlet. `Format-List` uses the **Property** parameter with the asterisk (`*`) wildcard to display each property. ### Example 3: Configure the classic Security log This command gets an **EventLogConfiguration** object that represents the classic **Security** log. The object is then used to configure settings for the log, such as max file size, file path, and whether the log is enabled. ```powershell $log = Get-WinEvent -ListLog Security $log.MaximumSizeInBytes = 1gb try{ $log.SaveChanges() Get-WinEvent -ListLog Security | Format-List -Property * }catch [System.UnauthorizedAccessException]{ $ErrMsg = 'You do not have permission to configure this log!' $ErrMsg += ' Try running this script with administrator privileges. ' $ErrMsg += $_.Exception.Message Write-Error $ErrMsg } ``` ```Output FileSize : 69632 IsLogFull : False LastAccessTime : 3/13/2019 09:41:46 LastWriteTime : 3/13/2019 09:41:46 OldestRecordNumber : 1 RecordCount : 23 LogName : Security LogType : Administrative LogIsolation : Custom IsEnabled : True IsClassicLog : True SecurityDescriptor : O:BAG:SYD: ... LogFilePath : %SystemRoot%\System32\Winevt\Logs\Security.evtx MaximumSizeInBytes : 1073741824 LogMode : Circular OwningProviderName : ProviderNames : {Microsoft-Windows-WUSA, Microsoft-Windows-ActionQueue... ProviderLevel : ProviderKeywords : ProviderBufferSize : 64 ProviderMinimumNumberOfBuffers : 0 ProviderMaximumNumberOfBuffers : 64 ProviderLatency : 1000 ProviderControlGuid : ``` The `Get-WinEvent` cmdlet uses the **ListLog** parameter to specify the **Security** log. The object is saved to a variable. The **MaximumSizeInBytes** property is set to 1 gigabyte on the object. The **SaveChanges** method is called to push the change to the system inside of a try block to handle access violations. The `Get-WinEvent` cmdlet is called again on the **Security** log and piped to the `Format-List` cmdlet to verify that the **MaximumSizeInBytes** property has been saved on the machine. ### Example 4: Get event logs from a server This command only gets event logs on the local computer that contain events. It's possible for a log's **RecordCount** to be null or zero. The example uses the `$_` variable. For more information, see [about_Automatic_Variables](../Microsoft.PowerShell.Core/about/about_automatic_variables.md). ```powershell Get-WinEvent -ListLog * -ComputerName localhost | Where-Object { $_.RecordCount } ``` ```Output LogMode MaximumSizeInBytes RecordCount LogName ------- ------------------ ----------- ------- Circular 15532032 14546 Application Circular 1052672 117 Azure Information Protection Circular 1052672 2990 CxAudioSvcLog Circular 1052672 9 MSFTVPN Setup Circular 1052672 282 OAlerts ``` The `Get-WinEvent` cmdlet gets log information from the computer. The **ListLog** parameter uses the asterisk (`*`) wildcard to display information about each log. The **ComputerName** parameter specifies to get the logs from the local computer, **localhost**. The objects are sent down the pipeline to the `Where-Object` cmdlet. `Where-Object` uses `$_.RecordCount` to return only logs that contain data. `$_` is a variable that represents the current object in the pipeline. **RecordCount** is a property of the object with a non-null value. ### Example 5: Get event logs from multiple servers This example gets objects that represent the **Application** event logs on three computers: Server01, Server02, and Server03. The `foreach` keyword is used because the **ComputerName** parameter accepts only one value. For more information, see [about_Foreach](../Microsoft.PowerShell.Core/about/about_Foreach.md). ```powershell $S = 'Server01', 'Server02', 'Server03' foreach ($Server in $S) { Get-WinEvent -ListLog Application -ComputerName $Server | Select-Object LogMode, MaximumSizeInBytes, RecordCount, LogName, @{Name='ComputerName'; Expression={$Server}} | Format-Table -AutoSize } ``` ```Output LogMode MaximumSizeInBytes RecordCount LogName ComputerName ------- ------------------ ----------- ------- ------------ Circular 15532032 14577 Application Server01 Circular 15532032 9689 Application Server02 Circular 15532032 5309 Application Server03 ``` The variable `$S` stores the names three servers: **Server01**, **Server02**, and **Server03**. The `foreach` statement uses a loop to process each server, `($Server in $S)`. The script block in the curly braces (`{ }`) runs the `Get-WinEvent` command. The **ListLog** parameter specifies the **Application** log. The **ComputerName** parameter uses the variable `$Server` to get log information from each server. The objects are sent down the pipeline to the `Select-Object` cmdlet. `Select-Object` gets the properties **LogMode**, **MaximumSizeInBytes**, **RecordCount**, **LogName**, and uses a calculated expression to display the **ComputerName** using the `$Server` variable. The objects are sent down the pipeline to the `Format-Table` cmdlet to display the output in the PowerShell console. The **AutoSize** parameter formats the output to fit the screen. ### Example 6: Get event log providers and log names This command gets the event log providers and the logs to which they write. ```powershell Get-WinEvent -ListProvider * ``` ```Output Name : .NET Runtime LogLinks : {Application} Opcodes : {} Tasks : {} Name : .NET Runtime Optimization Service LogLinks : {Application} Opcodes : {} Tasks : {} ``` The `Get-WinEvent` cmdlet gets log information from the computer. The **ListProvider** parameter uses the asterisk (`*`) wildcard to display information about each provider. In the output, the **Name** is the provider and **LogLinks** is the log that the provider writes to. ### Example 7: Get all event log providers that write to a specific log This command gets all of the providers that write to the **Application** log. ```powershell (Get-WinEvent -ListLog Application).ProviderNames ``` ```Output .NET Runtime .NET Runtime Optimization Service Application Application Error Application Hang Application Management ``` The `Get-WinEvent` cmdlet gets log information from the computer. The **ListLog** parameter uses **Application** to get objects for that log. **ProviderNames** is a property of the object and displays the providers that write to the **Application** log. ### Example 8: Get event log provider names that contain a specific string This command gets the event log providers with names that include a specific string in the provider's name. ```powershell Get-WinEvent -ListProvider *Policy* ``` ```Output Name : Group Policy Applications LogLinks : {Application} Opcodes : {} Tasks : {} Name : Group Policy Client LogLinks : {Application} Opcodes : {} Tasks : {} Name : Group Policy Data Sources LogLinks : {Application} Opcodes : {} Tasks : {} ``` The `Get-WinEvent` cmdlet gets log information from the computer. The **ListProvider** parameter uses the asterisk (`*`) wildcard to find **Policy** anywhere within the provider's name. ### Example 9: Get Event Ids that the event provider generates This command lists the Event Ids that the **Microsoft-Windows-GroupPolicy** event provider generates along with the event description. ```powershell (Get-WinEvent -ListProvider Microsoft-Windows-GroupPolicy).Events | Format-Table Id, Description ``` ```Output Id Description -- ----------- 1500 The Group Policy settings for the computer were processed successfully... 1501 The Group Policy settings for the user were processed successfully... 4115 Group Policy Service started. 4116 Started the Group Policy service initialization phase. 4117 Group Policy Session started. ``` The `Get-WinEvent` cmdlet gets log information from the computer. The **ListProvider** parameter specifies the provider, **Microsoft-Windows-GroupPolicy**. The expression is wrapped in parentheses and uses the **Events** property to get objects. The objects are sent down the pipeline to the `Format-Table` cmdlet. `Format-Table` displays the **Id** and **Description** of the event objects. ### Example 10: Get log information from event object properties This example shows how to get information about a log's contents using event object properties. Event objects are stored in a variable and then grouped and counted by **Event Id** and **Level**. ```powershell $Event = Get-WinEvent -LogName 'Windows PowerShell' $Event.Count $Event | Group-Object -Property Id -NoElement | Sort-Object -Property Count -Descending $Event | Group-Object -Property LevelDisplayName -NoElement ``` ```Output 195 Count Name ----- ---- 147 600 22 400 21 601 3 403 2 103 Count Name ----- ---- 2 Warning 193 Information ``` The `Get-WinEvent` cmdlet uses the **LogName** parameter to specify the **Windows PowerShell** event log. The event objects are stored in the `$Event` variable. The **Count** property of `$Event`shows the total number of logged events. The `$Event` variable is sent down the pipeline to the `Group-Object` cmdlet. `Group-Object` uses the **Property** parameter to specify the **Id** property and counts the objects by the event Id value. The **NoElement** parameter removes other properties from the objects output. The grouped objects are sent down the pipeline to the `Sort-Object` cmdlet. `Sort-Object` uses the **Property** parameter to sort the objects by **Count**. The **Descending** parameter displays the output by count, from highest to lowest. In the output, the **Count** column contains the total number of each event. The **Name** column contains the grouped event Id numbers. The `$Event` variable is sent down the pipeline to the `Group-Object` cmdlet. `Group-Object` uses the **Property** parameter to specify the **LevelDisplayName** property and counts the objects by **LevelDisplayName**. The objects are grouped by the levels such as **Warning** and **Information**. The **NoElement** parameter removes other properties from the output. In the output, the **Count** column contains the total number of each event. The **Name** column contains the grouped **LevelDisplayName**. ### Example 11: Get error events that have a specified string in their name This example uses a comma-separated string of log names. The output is grouped by the level such as error or warning and the log name. ```powershell Get-WinEvent -LogName *PowerShell*, Microsoft-Windows-Kernel-WHEA* | Group-Object -Property LevelDisplayName, LogName -NoElement | Format-Table -AutoSize ``` ```Output Count Name ----- ---- 1 Error, PowerShellCore/Operational 26 Information, Microsoft-Windows-Kernel-WHEA/Operational 488 Information, Microsoft-Windows-PowerShell/Operational 77 Information, PowerShellCore/Operational 9835 Information, Windows PowerShell 19 Verbose, PowerShellCore/Operational 444 Warning, Microsoft-Windows-PowerShell/Operational 512 Warning, PowerShellCore/Operational ``` The `Get-WinEvent` cmdlet gets log information from the computer. The **LogName** parameter uses a comma-separated string with the asterisk (`*`) wildcard to specify the log names. The objects are sent down the pipeline to the `Group-Object` cmdlet. `Group-Object` uses the **Property** parameter to group the objects by **LevelDisplayName** and **LogName**. The **NoElement** parameter removes other properties from the output. The grouped objects are sent down the pipeline to the `Format-Table` cmdlet. `Format-Table` uses the **AutoSize** parameter to format the columns. The **Count** column contains the total number of each event. The **Name** column contains the grouped **LevelDisplayName** and **LogName**. ### Example 12: Get events from an archived event log `Get-WinEvent` can get event information from saved log files. This sample uses an archived PowerShell log that is stored on the local computer. ```powershell Get-WinEvent -Path 'C:\Test\Windows PowerShell.evtx' ``` ```Output ProviderName: PowerShell TimeCreated Id LevelDisplayName Message ----------- -- ---------------- ------- 3/15/2019 13:54:13 403 Information Engine state is changed from Available to Stopped... 3/15/2019 13:54:13 400 Information Engine state is changed from None to Available... 3/15/2019 13:54:13 600 Information Provider "Variable" is Started... 3/15/2019 13:54:13 600 Information Provider "Function" is Started... 3/15/2019 13:54:13 600 Information Provider "FileSystem" is Started... ``` The `Get-WinEvent` cmdlet gets log information from the computer. The **Path** parameter specifies the directory and file name. ### Example 13: Get a specific number of events from an archived event log These commands get a specific number of events from an archived event log. `Get-WinEvent` has parameters that can get a maximum number of events or the oldest events. This sample uses an archived PowerShell log that is stored in **C:\Test\PowerShellCore Operational.evtx**. ```powershell Get-WinEvent -Path 'C:\Test\PowerShellCore Operational.evtx' -MaxEvents 100 ``` ```Output ProviderName: PowerShellCore TimeCreated Id LevelDisplayName Message ----------- -- ---------------- ------- 3/15/2019 09:54:54 4104 Warning Creating Scriptblock text (1 of 1):... 3/15/2019 09:37:13 40962 Information PowerShell console is ready for user input 3/15/2019 07:56:24 4104 Warning Creating Scriptblock text (1 of 1):... ... 3/7/2019 10:53:22 40961 Information PowerShell console is starting up 3/7/2019 10:53:22 8197 Verbose Runspace state changed to Opening 3/7/2019 10:53:22 8195 Verbose Opening RunspacePool ``` The `Get-WinEvent` cmdlet gets log information from the computer. The **Path** parameter specifies the directory and filename. The **MaxEvents** parameter specifies that 100 records are displayed, from newest to oldest. ### Example 14: Event Tracing for Windows Event Tracing for Windows (ETW) writes events to the log as events occur. The events are stored in the order of oldest to newest. An archived ETW file is saved as an `.etl` such as **TraceLog.etl**. The events are listed in the order in which they are written to the log, so the *Oldest* parameter is required. ```powershell Get-WinEvent -Path 'C:\Tracing\TraceLog.etl' -Oldest | Sort-Object -Property TimeCreated -Descending | Select-Object -First 100 ``` The `Get-WinEvent` cmdlet gets log information from the archived file. The **Path** parameter specifies the directory and file name. The **Oldest** parameter is used to output events in the order they are written, oldest to newest. The objects are sent down the pipeline to the `Sort-Object` cmdlet `Sort-Object` sorts the objects in descending order by the value of the **TimeCreated** property. The objects are sent down the pipeline to the `Select-Object` cmdlet that displays the 100 newest events. ### Example 15: Get events from an event trace log This example shows how to get the events from an event trace log file (`.etl`) and an archived Windows PowerShell log file (`.evtx`). You can combine multiple file types in a single command. Because the files contain the same type of **.NET Framework** object, **EventLogRecord**, you can filter them with the same properties. The command requires the **Oldest** parameter because it is reading from an `.etl` file, but the **Oldest** parameter applies to each file. ```powershell Get-WinEvent -Path 'C:\Tracing\TraceLog.etl', 'C:\Test\Windows PowerShell.evtx' -Oldest | Where-Object { $_.Id -eq '403' } ``` The `Get-WinEvent` cmdlet gets log information from the archived files. The **Path** parameter uses a comma-separated list to specify each files directory and file name. The **Oldest** parameter is used to output events in the order they are written, oldest to newest. The objects are sent down the pipeline to the `Where-Object` cmdlet. `Where-Object` uses a script block to find events with an **Id** of **403**. The `$_` variable represents the current object in the pipeline and **Id** is the Event Id property. ### Example 16: Filter event log results This example shows a variety of methods to filter and select events from an event log. All of these commands get events that occurred in the last 24-hours from the **Windows PowerShell** event log. The filter methods are more efficient than using the `Where-Object` cmdlet. Filters are applied as the objects are retrieved. `Where-Object` retrieves all of the objects, then applies filters to all of the objects. ```powershell # Using the Where-Object cmdlet: $Yesterday = (Get-Date) - (New-TimeSpan -Day 1) Get-WinEvent -LogName 'Windows PowerShell' | Where-Object { $_.TimeCreated -ge $Yesterday } # Using the FilterHashtable parameter: $Yesterday = (Get-Date) - (New-TimeSpan -Day 1) Get-WinEvent -FilterHashtable @{ LogName='Windows PowerShell'; Level=3; StartTime=$Yesterday } # Using the FilterXML parameter: $xmlQuery = @' <QueryList> <Query Id="0" Path="Windows PowerShell"> <Select Path="System">*[System[(Level=3) and TimeCreated[timediff(@SystemTime) &amp;lt;= 86400000]]]</Select> </Query> </QueryList> '@ Get-WinEvent -FilterXML $xmlQuery # Using the FilterXPath parameter: $XPath = '*[System[Level=3 and TimeCreated[timediff(@SystemTime) &amp;lt;= 86400000]]]' Get-WinEvent -LogName 'Windows PowerShell' -FilterXPath $XPath ``` ### Example 17: Use FilterHashtable to get events from the Application log This example uses the **FilterHashtable** parameter to get events from the **Application** log. The hash table uses **key/value** pairs. For more information about the **FilterHashtable** parameter, see [Creating Get-WinEvent queries with FilterHashtable](/powershell/scripting/samples/Creating-Get-WinEvent-queries-with-FilterHashtable). For more information about hash tables, see [about_Hash_Tables](../Microsoft.PowerShell.Core/about/about_hash_tables.md). ```powershell $Date = (Get-Date).AddDays(-2) Get-WinEvent -FilterHashtable @{ LogName='Application'; StartTime=$Date; Id='1003' } ``` The `Get-Date` cmdlet uses the **AddDays** method to get a date that is two days before the current date. The date object is stored in the `$Date` variable. The `Get-WinEvent` cmdlet gets log information. The **FilterHashtable** parameter is used to filter the output. The **LogName** key specifies the value as the **Application** log. The **StartTime** key uses the value stored in the `$Date` variable. The **Id** key uses an Event Id value, **1003**. ### Example 18: Use FilterHashtable to get application errors This example uses the **FilterHashtable** parameter to find Internet Explorer application errors that occurred within the last week. ```powershell $StartTime = (Get-Date).AddDays(-7) Get-WinEvent -FilterHashtable @{ LogName='Application' ProviderName='Application Error' Data='iexplore.exe' StartTime=$StartTime } ``` The `Get-Date` cmdlet uses the **AddDays** method to get a date that is seven days before the current date. The date object is stored in the `$StartTime` variable. The `Get-WinEvent` cmdlet gets log information. The **FilterHashtable** parameter is used to filter the output. The **LogName** key specifies the value as the **Application** log. The **ProviderName** key uses the value, **Application Error**, which is the event's **Source**. The **Data** key uses the value **iexplore.exe** The **StartTime** key uses the value stored in `$StartTime` variable. ### Example 19: Use SuppressHashFilter to filter application errors Like Example 16 above, this example uses the **FilterHashtable** parameter to get events from the **Application** log. However, we add the **SuppressHashFilter** key to filter out **Information** level events. ```powershell $Date = (Get-Date).AddDays(-2) $filter = @{ LogName='Application' StartTime=$Date SuppressHashFilter=@{Level=4} } Get-WinEvent -FilterHashtable $filter ``` In this example, `Get-WinEvent` gets all events from the **Application** log for the last two days except those that have a **Level** of 4 (Information). ## PARAMETERS ### -ComputerName Specifies the name of the computer that this cmdlet gets events from the event logs. Type the NetBIOS name, an IP address, or the fully qualified domain name (FQDN) of the computer. The default value is the local computer, **localhost**. This parameter accepts only one computer name at a time. To get event logs from remote computers, configure the firewall port for the event log service to allow remote access. This cmdlet does not rely on PowerShell remoting. You can use the **ComputerName** parameter even if your computer is not configured to run remote commands. ```yaml Type: System.String Parameter Sets: GetLogSet, ListLogSet, ListProviderSet, GetProviderSet, HashQuerySet, XmlQuerySet Aliases: Cn Required: False Position: Named Default value: Local computer Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to perform this action. The default value is the current user. Type a user name, such as **User01** or **Domain01\User01**. Or, enter a **PSCredential** object, such as one generated by the `Get-Credential` cmdlet. If you type a user name, you are prompted for a password. If you type only the parameter name, you are prompted for both a username and a password. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: False Accept wildcard characters: False ``` ### -FilterHashtable Specifies a query in hash table format to select events from one or more event logs. The query contains a hash table with one or more **key/value** pairs. Hash table queries have the following rules: - Keys and values are case-insensitive. - Wildcard characters are valid only in the values associated with the **LogName** and **ProviderName** keys. - Each key can be listed only once in each hash table. - The **Path** value takes paths to `.etl`, `.evt`, and `.evtx` log files. - The **LogName**, **Path**, and **ProviderName** keys can be used in the same query. - The **UserID** key can take a valid security identifier (SID) or a domain account name that can be used to construct a valid **System.Security.Principal.NTAccount** object. - The **Data** value takes event data in an unnamed field. For example, events in classic event logs. - `<named-data>` key represents a named event data field. When `Get-WinEvent` cannot interpret a **key/value** pair, it interprets the key as a case-sensitive name for the event data in the event. The valid `Get-WinEvent` **key/value** pairs are as follows: - **LogName**=`<String[]>` - **ProviderName**=`<String[]>` - **Path**=`<String[]>` - **Keywords**=`<Long[]>` - **ID**=`<Int32[]>` - **Level**=`<Int32[]>` - **StartTime**=`<DateTime>` - **EndTime**=`<DateTime>` - **UserID**=`<SID>` - **Data**=`<String[]>` - `<named-data>`=`<String[]>` - **SuppressHashFilter**=`<Hashtable>` ```yaml Type: System.Collections.Hashtable[] Parameter Sets: HashQuerySet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FilterXml Specifies a structured XML query that this cmdlet selects events from one or more event logs. To generate a valid XML query, use the **Create Custom View** and **Filter Current Log** features in Windows Event Viewer. Use the items in the dialog box to create a query, and then click the XML tab to view the query in XML format. You can copy the XML from the XML tab into the value of the **FilterXml** parameter. For more information about the Event Viewer features, see Event Viewer Help. Use an XML query to create a complex query that contains several XPath statements. The XML format also allows you to use a **Suppress XML** element that excludes events from the query. For more information about the XML schema for event log queries, see [Query Schema](/windows/win32/wes/queryschema-schema) and the XML Event Queries section of [Event Selection](/previous-versions/aa385231(v=vs.85)). You may also create a **Suppress** element using the **FilterHashtable** parameter. ```yaml Type: System.Xml.XmlDocument Parameter Sets: XmlQuerySet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FilterXPath Specifies an XPath query that this cmdlet select events from one or more logs. For more information about the XPath language, see [XPath Reference](/previous-versions/dotnet/netframework-4.0/ms256115(v=vs.100)) and the Selection Filters section of [Event Selection](/previous-versions/aa385231(v=vs.85)). ```yaml Type: System.String Parameter Sets: GetLogSet, GetProviderSet, FileSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Gets debug and analytic logs, in addition to other event logs. The **Force** parameter is required to get a debug or analytic log when the value of the Name parameter includes wildcard characters. By default, the `Get-WinEvent` cmdlet excludes these logs unless you specify the full name of a debug or analytic log. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: GetLogSet, ListLogSet, GetProviderSet, HashQuerySet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ListLog Specifies the event logs. Enter the event log names in a comma-separated list. Wildcards are permitted. To get all the logs, use the asterisk (`*`) wildcard. ```yaml Type: System.String[] Parameter Sets: ListLogSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -ListProvider Specifies the event log providers that this cmdlet gets. An event log provider is a program or service that writes events to the event log. Enter the provider names in a comma-separated list. Wildcards are permitted. To get the providers of all the event logs on the computer, use the asterisk (`*`) wildcard. ```yaml Type: System.String[] Parameter Sets: ListProviderSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LogName Specifies the event logs that this cmdlet get events from. Enter the event log names in a comma-separated list. Wildcards are permitted. You can also pipe log names to the `Get-WinEvent` cmdlet. > [!NOTE] > PowerShell does not limit the amount of logs you can request. However, the `Get-WinEvent` cmdlet > queries the Windows API which has a limit of 256. This can make it difficult to filter through all > of your logs at one time. You can work around this by using a `foreach` loop to iterate through each > log like this: `Get-WinEvent -ListLog * | ForEach-Object{ Get-WinEvent -LogName $_.LogName }` ```yaml Type: System.String[] Parameter Sets: GetLogSet Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -MaxEvents Specifies the maximum number of events that are returned. Enter an integer such as 100. The default is to return all the events in the logs or files. ```yaml Type: System.Int64 Parameter Sets: GetLogSet, GetProviderSet, FileSet, HashQuerySet, XmlQuerySet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Oldest Indicate that this cmdlet gets the events in oldest-first order. By default, events are returned in newest-first order. This parameter is required to get events from `.etl` and `.evt` files and from debug and analytic logs. In these files, events are recorded in oldest-first order, and the events can be returned only in oldest-first order. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: GetLogSet, GetProviderSet, FileSet, HashQuerySet, XmlQuerySet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to the event log files that this cmdlet get events from. Enter the paths to the log files in a comma-separated list, or use wildcard characters to create file path patterns. `Get-WinEvent` supports files with the `.evt`, `.evtx`, and `.etl` file name extensions. You can include events from different files and file types in the same command. ```yaml Type: System.String[] Parameter Sets: FileSet Aliases: PSPath Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -ProviderName Specifies, as a string array, the event log providers from which this cmdlet gets events. Enter the provider names in a comma-separated list, or use wildcard characters to create provider name patterns. An event log provider is a program or service that writes events to the event log. It is not a PowerShell provider. ```yaml Type: System.String[] Parameter Sets: GetProviderSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a **LogName** (string) to this cmdlet. ### System.Xml.XmlDocument You can pipe a **FilterXML** query to this cmdlet. ### System.Collections.Hashtable You can pipe a **FilterHashtable** query to this cmdlet. ## OUTPUTS ### System.Diagnostics.Eventing.Reader.EventLogConfiguration With the **ListLog** parameter, this cmdlet returns **EventLogConfiguration** objects. ### System.Diagnostics.Eventing.Reader.EventLogRecord By default, this cmdlet returns **EventLogRecord** objects. ### System.Diagnostics.Eventing.Reader.ProviderMetadata With the **ListProvider** parameter, this cmdlet returns **ProviderMetadata** objects. ## NOTES `Get-WinEvent` is designed to replace the `Get-EventLog` cmdlet on computers running Windows Vista and later versions of Windows. `Get-EventLog` gets events only in classic event logs. `Get-EventLog` is retained for backward compatibility. The `Get-WinEvent` and `Get-EventLog` cmdlets are not supported in Windows Pre-installation Environment (Windows PE). ## RELATED LINKS [about_Automatic_Variables](../Microsoft.PowerShell.Core/about/about_automatic_variables.md) [about_Foreach](../Microsoft.PowerShell.Core/about/about_Foreach.md) [about_Hash_Tables](../Microsoft.PowerShell.Core/about/about_hash_tables.md) [Creating Get-WinEvent queries with FilterHashtable](/powershell/scripting/samples/Creating-Get-WinEvent-queries-with-FilterHashtable) [Format-Table](../Microsoft.PowerShell.Utility/Format-Table.md) [Group-Object](../Microsoft.PowerShell.Utility/Group-Object.md) [Sort-Object](../Microsoft.PowerShell.Utility/Sort-Object.md) [Where-Object](../Microsoft.PowerShell.Core/Where-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Diagnostics/Microsoft.PowerShell.Diagnostics.md

--- Download Help Link: https://aka.ms/powershell75-help Help Version: 7.6.0.0 Locale: en-US Module Guid: ca046f10-ca64-4740-8ff9-2565dba61a4f Module Name: Microsoft.PowerShell.Diagnostics ms.date: 06/09/2017 schema: 2.0.0 title: Microsoft.PowerShell.Diagnostics --- # Microsoft.PowerShell.Diagnostics Module ## Description This section contains the help topics for the cmdlets that are installed with the PowerShell Microsoft.PowerShell.Diagnostics module, which contains cmdlets that manage data from event logs. This module is only available on the Windows platform. ## Microsoft.PowerShell.Diagnostics Cmdlets ### [Get-Counter](Get-Counter.md) Gets performance counter data from local and remote computers. ### [Get-WinEvent](Get-WinEvent.md) Gets events from event logs and event tracing log files on local and remote computers. ### [New-WinEvent](New-WinEvent.md) Creates a new Windows event for the specified event provider.

#File: reference/7.6/Microsoft.PowerShell.Diagnostics/New-WinEvent.md

--- external help file: Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Diagnostics ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.diagnostics/new-winevent?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-WinEvent --- # New-WinEvent ## SYNOPSIS Creates a new Windows event for the specified event provider. ## SYNTAX ``` New-WinEvent [-ProviderName] <String> [-Id] <Int32> [-Version <Byte>] [[-Payload] <Object[]>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `New-WinEvent` cmdlet creates an Event Tracing for Windows (ETW) event for an event provider. You can use this cmdlet to add events to ETW channels from PowerShell. ## EXAMPLES ### Example 1 - Create a new event ```powershell New-WinEvent -ProviderName Microsoft-Windows-PowerShell -Id 45090 -Payload @("Workflow", "Running") ``` This command uses the `New-WinEvent` cmdlet to create event 45090 for the Microsoft-Windows-PowerShell provider. ### Example 2 - Get the template for an event In this example, `Get-WinEvent` is used to get the template for event id 8007 from the Group Policy event provider. Notice that the event has two formats. In version 0, the **IsMachine** field is a boolean value. In version 1, the **IsMachine** field is an unsigned integer value. ```powershell (Get-WinEvent -ListProvider Microsoft-Windows-GroupPolicy).Events | Where-Object Id -EQ 8007 ``` ```Output Id : 8007 Version : 0 LogLink : System.Diagnostics.Eventing.Reader.EventLogLink Level : System.Diagnostics.Eventing.Reader.EventLevel Opcode : System.Diagnostics.Eventing.Reader.EventOpcode Task : System.Diagnostics.Eventing.Reader.EventTask Keywords : {} Template : <template xmlns="http://schemas.microsoft.com/win/2004/08/events"> <data name="PolicyElaspedTimeInSeconds" inType="win:UInt32" outType="xs:unsignedInt"/> <data name="ErrorCode" inType="win:UInt32" outType="win:HexInt32"/> <data name="PrincipalSamName" inType="win:UnicodeString" outType="xs:string"/> <data name="IsMachine" inType="win:Boolean" outType="xs:boolean"/> <data name="IsConnectivityFailure" inType="win:Boolean" outType="xs:boolean"/> </template> Description : Completed periodic policy processing for user %3 in %1 seconds. Id : 8007 Version : 1 LogLink : System.Diagnostics.Eventing.Reader.EventLogLink Level : System.Diagnostics.Eventing.Reader.EventLevel Opcode : System.Diagnostics.Eventing.Reader.EventOpcode Task : System.Diagnostics.Eventing.Reader.EventTask Keywords : {} Template : <template xmlns="http://schemas.microsoft.com/win/2004/08/events"> <data name="PolicyElaspedTimeInSeconds" inType="win:UInt32" outType="xs:unsignedInt"/> <data name="ErrorCode" inType="win:UInt32" outType="win:HexInt32"/> <data name="PrincipalSamName" inType="win:UnicodeString" outType="xs:string"/> <data name="IsMachine" inType="win:UInt32" outType="xs:unsignedInt"/> <data name="IsConnectivityFailure" inType="win:Boolean" outType="xs:boolean"/> </template> Description : Completed periodic policy processing for user %3 in %1 seconds. ``` The **Description** property contains the message that gets written to the event log. The `%3` and `%1` value are placeholders for the values passed into the template. The `%3` string is replace with the value passed to the **PrincipalSamName** field. The `%1` string is replaced with value passed to the **PolicyElaspedTimeInSeconds** field. ### Example 3 - Create a new event using a versioned template This example shows how to create an event using a specific template version. ```powershell $Payload = @(300, [uint32]'0x8001011f', $Env:USERNAME, 0, 1) New-WinEvent -ProviderName Microsoft-Windows-GroupPolicy -Id 8007 -Version 1 -Payload $Payload Get-WinEvent -ProviderName Microsoft-Windows-GroupPolicy -MaxEvents 1 ``` ```Output ProviderName: Microsoft-Windows-GroupPolicy TimeCreated Id LevelDisplayName Message ----------- -- ---------------- ------- 5/4/2022 8:40:24 AM 8007 Information Completed periodic policy processing for user User1 in 300 seconds ``` If the values in the payload do not match the types in the template, the event is logged but the payload contains an error. ## PARAMETERS ### -Id Specifies an event Id that is registered in the event provider. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Payload The payload is an array of values passed as positional arguments to the event template. The values are inserted into the template to construct the message for the event. Events can have multiple template versions that use different formats. If the values in the payload do not match the types in the template, the event is logged but the payload contains an error. ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProviderName Specifies the event provider that writes the event to an event log, such as "Microsoft-Windows-PowerShell". An ETW event provider is a logical entity that writes events to ETW sessions. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Version Specifies the version number of the event. PowerShell converts the number to the required Byte type. The value specifies the version of the event when different versions of the same event are defined. ```yaml Type: System.Byte Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES After the provider writes the event to an eventlog, you can use the `Get-WinEvent` cmdlet to get the event from the event log. ## RELATED LINKS [Get-WinEvent](Get-WinEvent.md)

#File: reference/7.6/Microsoft.PowerShell.Host/Microsoft.PowerShell.Host.md

--- Download Help Link: https://aka.ms/powershell75-help Help Version: 7.6.0.0 Locale: en-US Module Guid: 56d66100-99a0-4ffc-a12d-eee9a6718aef Module Name: Microsoft.PowerShell.Host ms.date: 06/09/2017 schema: 2.0.0 title: Microsoft.PowerShell.Host --- # Microsoft.PowerShell.Host Module ## Description This section contains the help topics for the cmdlets that are installed with the PowerShell Microsoft.PowerShell.Host module. The Host module contains cmdlets that manage data from host programs. ## Microsoft.PowerShell.Host Cmdlets ### [Start-Transcript](Start-Transcript.md) Creates a record of all or part of a PowerShell session to a text file. ### [Stop-Transcript](Stop-Transcript.md) Stops a transcript.

#File: reference/7.6/Microsoft.PowerShell.Host/Start-Transcript.md

--- external help file: Microsoft.PowerShell.ConsoleHost.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Host ms.date: 02/18/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.host/start-transcript?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Start-Transcript --- # Start-Transcript ## SYNOPSIS Creates a record of all or part of a PowerShell session to a text file. ## SYNTAX ### ByPath (Default) ``` Start-Transcript [[-Path] <String>] [-Append] [-Force] [-NoClobber] [-IncludeInvocationHeader] [-UseMinimalHeader] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ByLiteralPath ``` Start-Transcript [[-LiteralPath] <String>] [-Append] [-Force] [-NoClobber] [-IncludeInvocationHeader] [-UseMinimalHeader] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ByOutputDirectory ``` Start-Transcript [[-OutputDirectory] <String>] [-Append] [-Force] [-NoClobber] [-IncludeInvocationHeader] [-UseMinimalHeader] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Start-Transcript` cmdlet creates a record of all or part of a PowerShell session to a text file. The transcript includes all command that the user types and all output that appears on the console. By default, `Start-Transcript` stores the transcript in the following location using the default name: - On Windows: `$HOME\Documents` - On Linux or macOS: `$HOME` The default filename is `PowerShell_transcript.<computername>.<random>.<timestamp>.txt`. Starting in Windows PowerShell 5.0, `Start-Transcript` includes the hostname in the generated file name of all transcripts. The filename also includes random characters in names to prevent potential overwrites or duplication when you start two or more transcripts simultaneously. Including the computer name is useful if you store your transcripts in a centralized location. The random character string prevents guessing of the filename to gain unauthorized access to the file. If the target file doesn't have a Byte Order Mark (BOM), `Start-Transcript` defaults to `Utf8NoBom` encoding in the target file. ## EXAMPLES ### Example 1: Start a transcript file with default settings ```powershell Start-Transcript ``` This command starts a transcript in the default file location. ### Example 2: Start a transcript file at a specific location ```powershell Start-Transcript -Path "C:\transcripts\transcript0.txt" -NoClobber ``` This command starts a transcript in the `Transcript0.txt` file in `C:\transcripts`. **NoClobber** parameter prevents any existing files from being overwritten. If the `Transcript0.txt` file already exists, the command fails. ### Example 3: Start a transcript file with a unique name and store it on a file share The following example creates a transcript file with a name unique enough to be stored on in a shared location. The filename is constructed from the user's name, the hostname of the computer running PowerShell, the version of PowerShell, and the date and time. The transcript is stored in the `\\Server01\Transcripts` file share. ```powershell $sharePath = '\\Server01\Transcripts' $username = $Env:USERNAME $hostname = hostname $version = $PSVersionTable.PSVersion.ToString() $datetime = Get-Date -F 'yyyyMMddHHmmss' $filename = "Transcript-${username}-${hostname}-${version}-${datetime}.txt" $Transcript = Join-Path -Path $sharePath -ChildPath $filename Start-Transcript ``` The full path to the transcript file is stored in the `$Transcript` preference variable. For more information about the `$Transcript` preference variable, see [about_Preference_Variables](../Microsoft.PowerShell.Core/About/about_Preference_Variables.md#transcript). ## PARAMETERS ### -Append Indicates that this cmdlet adds the new transcript to the end of an existing file. Use the **Path** parameter to specify the file. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Allows the cmdlet to append the transcript to an existing read-only file. When used on a read-only file, the cmdlet changes the file permission to read-write. The cmdlet can't override security restrictions when this parameter is used. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -IncludeInvocationHeader Indicates that this cmdlet logs the time stamp when commands are run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies a location to the transcript file. Unlike the **Path** parameter, the value of the **LiteralPath** parameter is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks inform PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String Parameter Sets: ByLiteralPath Aliases: PSPath, LP Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NoClobber Indicates that this cmdlet doesn't overwrite an existing file. By default, if a transcript file exists in the specified path, `Start-Transcript` overwrites the file without warning. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: NoOverwrite Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OutputDirectory Specifies a specific path and folder in which to save a transcript. PowerShell automatically assigns the transcript name. ```yaml Type: System.String Parameter Sets: ByOutputDirectory Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies a location to the transcript file. Enter a path to a `.txt` file. Wildcards aren't permitted. If any of the directories in the path don't exist, the command fails. If you don't specify a path, `Start-Transcript` uses the path in the value of the `$Transcript` global variable. If you haven't created this variable, `Start-Transcript` stores the transcripts in the default location and filename. ```yaml Type: System.String Parameter Sets: ByPath Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseMinimalHeader Prepend a short header to the transcript, instead of the detailed header included by default. This parameter was added in PowerShell 6.2. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns a string containing a confirmation message and the path to the output file. ## NOTES To stop a transcript, use the `Stop-Transcript` cmdlet. To record an entire session, add the `Start-Transcript` command to your profile. For more information, see [about_Profiles](../Microsoft.PowerShell.Core/About/about_Profiles.md). ## RELATED LINKS [Stop-Transcript](Stop-Transcript.md) [about_Preference_Variables](../Microsoft.PowerShell.Core/About/about_Preference_Variables.md#transcript)

#File: reference/7.6/Microsoft.PowerShell.Host/Stop-Transcript.md

--- external help file: Microsoft.PowerShell.ConsoleHost.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Host ms.date: 01/04/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.host/stop-transcript?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Stop-Transcript --- # Stop-Transcript ## SYNOPSIS Stops a transcript. ## SYNTAX ``` Stop-Transcript [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Stop-Transcript` cmdlet stops a transcript that was started by the `Start-Transcript` cmdlet. Alternatively, you can end a session to stop a transcript. ## EXAMPLES ### Example 1: Stop all transcripts ```powershell Stop-Transcript ``` This command stops all transcripts. ## PARAMETERS ### -Confirm Prompts you for confirmation before running the cmdlet. This parameter was added in PowerShell 7.4. ```yaml Type: SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. This parameter was added in PowerShell 7.4. ```yaml Type: SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns a string that contains a status message and the path to the output file. ## NOTES If a transcript hasn't been started, the command fails. ## RELATED LINKS [Start-Transcript](Start-Transcript.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Add-Content.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 10/31/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/add-content?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Add-Content --- # Add-Content ## SYNOPSIS Adds content to the specified items, such as adding words to a file. ## SYNTAX ### Path (Default) ``` Add-Content [-Path] <string[]> [-Value] <Object[]> [-PassThru] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-NoNewline] [-Encoding <Encoding>] [-AsByteStream] [-Stream <string>] [<CommonParameters>] ``` ### LiteralPath ``` Add-Content [-Value] <Object[]> -LiteralPath <string[]> [-PassThru] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-NoNewline] [-Encoding <Encoding>] [-AsByteStream] [-Stream <string>] [<CommonParameters>] ``` ## DESCRIPTION The `Add-Content` cmdlet appends content to a specified item or file. Content can be passed in from the pipeline or specified by using the **Value** parameter. If you need to create files or directories for the following examples, see [New-Item](New-Item.md). ## EXAMPLES ### Example 1: Add a string to all text files with an exception This example appends a value to text files in the current directory but excludes files based on their file name. ```powershell Add-Content -Path .\*.txt -Exclude help* -Value 'End of file' ``` The **Path** parameter specifies all `.txt` files in the current directory, but the **Exclude** parameter ignores file names that match the specified pattern. The **Value** parameter specifies the text string that's written to the files. Use [Get-Content](Get-Content.md) to display the contents of these files. ### Example 2: Add a date to the end of the specified files This example appends the date to files in the current directory and displays the date in the PowerShell console. ```powershell Add-Content -Path .\DateTimeFile1.log, .\DateTimeFile2.log -Value (Get-Date) -PassThru Get-Content -Path .\DateTimeFile1.log ``` ```Output Tuesday, May 14, 2019 8:24:27 AM Tuesday, May 14, 2019 8:24:27 AM 5/14/2019 8:24:27 AM ``` The `Add-Content` cmdlet creates two new files in the current directory. The **Value** parameter contains the output of the `Get-Date` cmdlet. The **PassThru** parameter outputs the added contents to the pipeline. Because there is no other cmdlet to receive the output, it's displayed in the PowerShell console. The `Get-Content` cmdlet displays the updated file, `DateTimeFile1.log`. ### Example 3: Add the contents of a specified file to another file This example gets the content from a file and stores the content in a variable. The variable is used to append the content into another file. ```powershell $From = Get-Content -Path .\CopyFromFile.txt Add-Content -Path .\CopyToFile.txt -Value $From Get-Content -Path .\CopyToFile.txt ``` - The `Get-Content` cmdlet gets the contents of `CopyFromFile.txt` and stores the contents in the `$From` variable. - The `Add-Content` cmdlet updates the `CopyToFile.txt` file using the contents of the `$From` variable. - The `Get-Content` cmdlet displays CopyToFile.txt. ### Example 4: Add the contents of a specified file to another file using the pipeline This example gets the content from a file and pipes it to the `Add-Content` cmdlet. ```powershell Get-Content -Path .\CopyFromFile.txt | Add-Content -Path .\CopyToFile.txt Get-Content -Path .\CopyToFile.txt ``` The `Get-Content` cmdlet gets the contents of `CopyFromFile.txt`. The results are piped to the `Add-Content` cmdlet, which updates the `CopyToFile.txt`. The last `Get-Content` cmdlet displays `CopyToFile.txt`. ### Example 5: Create a new file and copy content This example creates a new file and copies an existing file's content into the new file. ```powershell Add-Content -Path .\NewFile.txt -Value (Get-Content -Path .\CopyFromFile.txt) Get-Content -Path .\NewFile.txt ``` - The `Add-Content` cmdlet uses the **Path** and **Value** parameters to create a new file in the current directory. - The `Get-Content` cmdlet gets the contents of an existing file, `CopyFromFile.txt` and passes it to the **Value** parameter. The parentheses around the `Get-Content` cmdlet ensure that the command finishes before the `Add-Content` command begins. - The `Get-Content` cmdlet displays the contents of the new file, `NewFile.txt`. ### Example 6: Add content to a read-only file This command adds a value to the file even if the **IsReadOnly** file attribute is set to **True**. The steps to create a read-only file are included in the example. ```powershell New-Item -Path .\IsReadOnlyTextFile.txt -ItemType File Set-ItemProperty -Path .\IsReadOnlyTextFile.txt -Name IsReadOnly -Value $true Get-ChildItem -Path .\IsReadOnlyTextFile.txt Add-Content -Path .\IsReadOnlyTextFile.txt -Value 'Add value to read-only text file' -Force Get-Content -Path .\IsReadOnlyTextFile.txt ``` ```Output Mode LastWriteTime Length Name ---- ------------- ------ ---- -ar-- 1/28/2019 13:35 0 IsReadOnlyTextFile.txt ``` - The `New-Item` cmdlet uses the **Path** and **ItemType** parameters to create the file `IsReadOnlyTextFile.txt` in the current directory. - The `Set-ItemProperty` cmdlet uses the **Name** and **Value** parameters to change the file's **IsReadOnly** property to True. - The `Get-ChildItem` cmdlet shows the file is empty (`0`) and has the read-only attribute (`r`). - The `Add-Content` cmdlet uses the **Path** parameter to specify the file. The **Value** parameter includes the text string to append to the file. The **Force** parameter writes the text to the read-only file. - The `Get-Content` cmdlet uses the **Path** parameter to display the file's contents. To remove the read-only attribute, use the `Set-ItemProperty` command with the **Value** parameter set to `False`. ### Example 7: Use Filters with Add-Content You can specify a filter to the `Add-Content` cmdlet. When using filters to qualify the **Path** parameter, you need to include a trailing asterisk (`*`) to indicate the contents of the path. The following command adds the word "Done" the content of all `*.txt` files in the `C:\Temp` directory. ```powershell Add-Content -Path C:\Temp\* -Filter *.txt -Value "Done" ``` ## PARAMETERS ### -AsByteStream Specifies that the content should be read as a stream of bytes. This parameter was introduced in PowerShell 6.0. A warning occurs when you use the **AsByteStream** parameter with the **Encoding** parameter. The **AsByteStream** parameter ignores any encoding and the output is returned as a stream of bytes. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential > [!NOTE] > This parameter isn't supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Encoding Specifies the type of encoding for the target file. The default value is `utf8NoBOM`. Encoding is a dynamic parameter that the FileSystem provider adds to the `Add-Content` cmdlet. This parameter works only in file system drives. The acceptable values for this parameter are as follows: - `ascii`: Uses the encoding for the ASCII (7-bit) character set. - `ansi`: Uses the encoding for the for the current culture's ANSI code page. This option was added in PowerShell 7.4. - `bigendianunicode`: Encodes in UTF-16 format using the big-endian byte order. - `bigendianutf32`: Encodes in UTF-32 format using the big-endian byte order. - `oem`: Uses the default encoding for MS-DOS and console programs. - `unicode`: Encodes in UTF-16 format using the little-endian byte order. - `utf7`: Encodes in UTF-7 format. - `utf8`: Encodes in UTF-8 format. - `utf8BOM`: Encodes in UTF-8 format with Byte Order Mark (BOM) - `utf8NoBOM`: Encodes in UTF-8 format without Byte Order Mark (BOM) - `utf32`: Encodes in UTF-32 format. Beginning with PowerShell 6.2, the **Encoding** parameter also allows numeric IDs of registered code pages (like `-Encoding 1251`) or string names of registered code pages (like `-Encoding "windows-1251"`). For more information, see the .NET documentation for [Encoding.CodePage](/dotnet/api/system.text.encoding.codepage?view=netcore-2.2). Starting with PowerShell 7.4, you can use the `Ansi` value for the **Encoding** parameter to pass the numeric ID for the current culture's ANSI code page without having to specify it manually. > [!NOTE] > **UTF-7*** is no longer recommended to use. As of PowerShell 7.1, a warning is written if you > specify `utf7` for the **Encoding** parameter. ```yaml Type: System.Text.Encoding Parameter Sets: (All) Aliases: Accepted values: ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 Required: False Position: Named Default value: UTF8NoBOM Accept pipeline input: False Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they're retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Overrides the read-only attribute, allowing you to add content to a read-only file. For example, **Force** overrides the read-only attribute but it doesn't change file permissions. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -NoNewline Indicates that this cmdlet doesn't add a new line or carriage return to the content. The string representations of the input objects are concatenated to form the output. No spaces or newlines are inserted between the output strings. No newline is added after the last output string. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns an object representing the added content. By default, this cmdlet doesn't generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to the items that receive the additional content. Wildcard characters are permitted. The paths must be paths to items, not to containers. For example, you must specify a path to one or more files, not a path to a directory. If you specify multiple paths, use commas to separate the paths. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Stream > [!NOTE] > This Parameter is only available on Windows. Specifies an alternative data stream for content. If the stream doesn't exist, this cmdlet creates it. Wildcard characters aren't supported. **Stream** is a dynamic parameter that the FileSystem provider adds to `Add-Content`. This parameter works only in file system drives. You can use the `Add-Content` cmdlet to change the content of any alternate data stream, such as `Zone.Identifier`. However, we don't recommend this as a way to eliminate security checks that block files that are downloaded from the Internet. If you verify that a downloaded file is safe, use the `Unblock-File` cmdlet. This parameter was introduced in PowerShell 3.0. As of PowerShell 7.2, `Add-Content` can target alternative data streams on both files and directories. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Value Specifies the content to be added. Type a quoted string, such as **This data is for internal use only**, or specify an object that contains content, such as the **DateTime** object that `Get-Date` generates. You can't specify the contents of a file by typing its path, because the path is just a string. You can use a `Get-Content` command to get the content and pass it to the **Value** parameter. ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Object You can pipe values to `Add-Content`. ### System.Management.Automation.PSCredential You can pipe credentials to `Add-Content`. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.String When you use the **PassThru** parameter, this cmdlet returns a **System.String** object representing the content. ## NOTES PowerShell includes the following aliases for `Add-Content`: - Windows: - `ac` - When you pipe an object to `Add-Content`, the object is converted to a string before it's added to the item. The object type determines the string format, but the format might be different than the default display of the object. To control the string format, use the formatting parameters of the sending cmdlet. - The `Add-Content` cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [about_Aliases](../Microsoft.PowerShell.Core/About/about_Aliases.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md) [Clear-Content](Clear-Content.md) [Get-Content](Get-Content.md) [Get-Item](Get-Item.md) [New-Item](New-Item.md) [Set-Content](Set-Content.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Clear-Content.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 02/14/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/clear-content?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Clear-Content --- # Clear-Content ## SYNOPSIS Deletes the contents of an item, but does not delete the item. ## SYNTAX ### Path (Default) - FileSystem provider ``` Clear-Content [-Path] <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Force] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [-Stream <String>] [<CommonParameters>] ``` ### LiteralPath - FileSystem provider ``` Clear-Content -LiteralPath <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Force] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [-Stream <String>] [<CommonParameters>] ``` ### Path (Default) - All providers ``` Clear-Content [-Path] <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Force] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath - All providers ``` Clear-Content -LiteralPath <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Force] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Clear-Content` cmdlet deletes the contents of an item, such as deleting the text from a file, but it does not delete the item. As a result, the item exists, but it is empty. `Clear-Content` is similar to `Clear-Item`, but it works on items with contents, instead of items with values. ## EXAMPLES ### Example 1: Delete all content from a directory ```powershell Clear-Content "..\SmpUsers\*\init.txt" ``` This command deletes all of the content from the `init.txt` files in all subdirectories of the `SmpUsers` directory. The files are not deleted, but they are empty. ### Example 2: Delete content of all files with a wildcard ```powershell Clear-Content -Path "*" -Filter "*.log" -Force ``` This command deletes the contents of all files in the current directory with the `.log` file name extension, including files with the read-only attribute. The asterisk (`*`) in the path represents all items in the current directory. The **Force** parameter makes the command effective on read-only files. Using a filter to restrict the command to files with the `.log` file name extension instead of specifying `*.log` in the path makes the operation faster. ### Example 3: Clear all data from a stream This example shows how the `Clear-Content` cmdlet clears the content from an alternate data stream while leaving the stream intact. The first command uses the `Get-Content` cmdlet to get the content of the `Zone.Identifier` stream in the `Copy-Script.ps1` file, which was downloaded from the internet. The second command uses the `Clear-Content` cmdlet to clear the content. The third command repeats the first command. It verifies that the content is cleared, but the stream remains. If the stream were deleted, the command would generate an error. You can use a method like this one to clear the content of an alternate data stream. However, it is not the recommended way to eliminate security checks that block files that are downloaded from the Internet. If you verify that a downloaded file is safe, use the `Unblock-File` cmdlet. ```powershell Get-Content C:\Test\Copy-Script.ps1 -Stream Zone.Identifier ``` ```Output [ZoneTransfer] ZoneId=3 ``` ```powershell Clear-Content C:\Test\Copy-Script.ps1 -Stream Zone.Identifier Get-Content C:\Test\Copy-Script.ps1 -Stream Zone.Identifier ``` ```Output ``` ## PARAMETERS ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. To impersonate another > user, or elevate your credentials when running this cmdlet, use `Invoke-Command`. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, strings that this cmdlet omits from the path to the content. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter in the provider's format or language. The value of this parameter qualifies the **Path** parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Forces the command to run without asking for user confirmation. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, content that this cmdlet clears. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies the paths to the items from which content is deleted. Unlike the **Path** parameter, the value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks (`'`). Single quotation marks tell having PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the paths to the items from which content is deleted. Wildcards are permitted. The paths must be paths to items, not to containers. For example, you must specify a path to one or more files, not a path to a directory. Wildcards are permitted. This parameter is required, but the parameter name (**Path**) is optional. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Stream This is a dynamic parameter made available by the **FileSystem** provider. This parameter is only available on Windows. Specifies an alternative data stream for content. If the stream does not exist, this cmdlet creates it. Wildcard characters are not supported. You can use the `Clear-Content` cmdlet to change the content of any alternate data stream, such as `Zone.Identifier`. However, we do not recommend this as a way to eliminate security checks that block files that are downloaded from the internet. If you verify that a downloaded file is safe, use the `Unblock-File` cmdlet. This parameter was introduced in PowerShell 3.0. As of PowerShell 7.2, `Clear-Content` can clear the content of alternative data streams from directories as well as files. For more information, see [about_FileSystem_Provider](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Clear-Content`: - All platforms: - `clc` You can use `Clear-Content` with the PowerShell FileSystem provider and with other providers that manipulate content. To clear items that are not considered to be content, such as items managed by the PowerShell Certificate or Registry providers, use `Clear-Item`. The `Clear-Content` cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Add-Content](Add-Content.md) [Get-Content](Get-Content.md) [Get-Item](Get-Item.md) [Set-Content](Set-Content.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Clear-Item.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/clear-item?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Clear-Item --- # Clear-Item ## SYNOPSIS Clears the contents of an item, but does not delete the item. ## SYNTAX ### Path (Default) ``` Clear-Item [-Path] <String[]> [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath ``` Clear-Item -LiteralPath <String[]> [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Clear-Item` cmdlet clears the content of an item, but it does not delete the item. For example, the `Clear-Item` cmdlet can delete the value of a variable, but it does not delete the variable. The value that used to represent a cleared item is defined by each PowerShell provider. This cmdlet is similar to `Clear-Content`, but it works on aliases and variables, instead of files. ## EXAMPLES ### Example 1: Clear the value of a variable This command clears the value of the variable named `TestVar1`. The variable remains and is valid, but its value is set to `$null`. The variable name is prefixed with `Variable:` to indicate the PowerShell Variable provider. The alternate commands show that, to get the same result, you can switch to the PowerShell `Variable:` drive and then run the `Clear-Item` command. ```powershell Clear-Item Variable:TestVar1 ``` ``` Set-Location Variable: PS Variable:\> Clear-Item TestVar1 ``` ### Example 2: Clear all registry entries This command clears all registry entries in the "MyKey" subkey, but only after prompting you to confirm your intent. It does not delete the "MyKey" subkey or affect any other registry keys or entries. You can use the **Include** and **Exclude** parameters to identify particular registry keys, but you cannot use them to identify registry entries. - To delete particular registry entries, use the `Remove-ItemProperty` cmdlet. - To delete the value of a registry entry, use the `Clear-ItemProperty cmdlet`. ```powershell Clear-Item HKLM:\Software\MyCompany\MyKey -Confirm ``` ## PARAMETERS ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Indicates that the cmdlet clears items that cannot otherwise be changed, such as read- only aliases. The cmdlet cannot clear constants. Implementation varies from provider to provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). The cmdlet cannot override security restrictions, even when the **Force** parameter is used. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the path to the items being cleared. Wildcard characters are permitted. This parameter is required, but the parameter name **Path** is optional. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a path string to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Clear-Item`: - All platforms: - `cli` - The `Clear-Item` cmdlet is supported only by several PowerShell providers, including the **Alias**, **Environment**, **Function**, **Registry**, and **Variable** providers. As such, you can use `Clear-Item` to delete the content of items in the provider namespaces. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). - You cannot use `Clear-Item` to delete the contents of a file, because the PowerShell FileSystem provider does not support this cmdlet. To clear files, use the `Clear-Content`. ## RELATED LINKS [Copy-Item](Copy-Item.md) [Get-Item](Get-Item.md) [Invoke-Item](Invoke-Item.md) [Move-Item](Move-Item.md) [New-Item](New-Item.md) [Remove-Item](Remove-Item.md) [Rename-Item](Rename-Item.md) [Set-Item](Set-Item.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Clear-ItemProperty.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/clear-itemproperty?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Clear-ItemProperty --- # Clear-ItemProperty ## SYNOPSIS Clears the value of a property but does not delete the property. ## SYNTAX ### Path (Default) ``` Clear-ItemProperty [-Path] <String[]> [-Name] <String> [-PassThru] [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath ``` Clear-ItemProperty -LiteralPath <String[]> [-Name] <String> [-PassThru] [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Clear-ItemProperty` cmdlet clears the value of a property, but it does not delete the property. You can use this cmdlet to delete the data from a registry value. ## EXAMPLES ### Example 1: Clear the value of registry key This command clears the data in the "Options" registry value in the "MyApp" subkey of `HKEY_LOCAL_MACHINE\Software\MyCompany`. ```powershell Clear-ItemProperty -Path "HKLM:\Software\MyCompany\MyApp" -Name "Options" ``` ## PARAMETERS ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Indicates that this cmdlet deletes properties from items that cannot otherwise be accessed by the user. Implementation varies from provider to provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies the name of the property to be cleared, such as the name of a registry value. Wildcard characters are permitted. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to the property being cleared. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a path string to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSCustomObject When you use the **PassThru** parameter, this cmdlet returns a **PSCustomObject** object representing the cleared item property. ## NOTES PowerShell includes the following aliases for `Clear-ItemProperty`: - All platforms: - `clp` - You can use `Clear-ItemProperty` to delete the data in registry values without deleting the value. If the data type of the value is Binary or DWORD, clearing the data sets the value to zero. Otherwise, the value is empty. - The `Clear-ItemProperty` cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Copy-ItemProperty](Copy-ItemProperty.md) [Get-ItemProperty](Get-ItemProperty.md) [Move-ItemProperty](Move-ItemProperty.md) [New-ItemProperty](New-ItemProperty.md) [Rename-ItemProperty](Rename-ItemProperty.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Clear-RecycleBin.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 01/05/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/clear-recyclebin?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Clear-RecycleBin --- # Clear-RecycleBin ## SYNOPSIS Clears the contents of the current user's recycle bin. ## SYNTAX ### All ``` Clear-RecycleBin [[-DriveLetter] <String[]>] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Clear-RecycleBin` cmdlet deletes the content of the current user's recycle bin. This action is like using Windows **Empty Recycle Bin**. This cmdlet was readded in PowerShell 7. ## EXAMPLES ### 1: Clear all recycle bins In this example, the current user's recycle bins for all drives are cleared. ```powershell Clear-RecycleBin ``` ```Output Confirm Are you sure you want to perform this action? Performing the operation "Clear-RecycleBin" on target "All of the contents of the Recycle Bin". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): ``` `Clear-RecycleBin` prompts the user for confirmation. ### 2: Clear a specified recycle bin This example clears the recycle bin for a specified drive letter. ```powershell Clear-RecycleBin -DriveLetter C ``` `Clear-RecycleBin` uses the **DriveLetter** parameter to specify the recycle bin on the `C` volume. The user is prompted for confirmation to run the command. ### 3: Clear all recycle bins without confirmation This example doesn't prompt for confirmation to clear the recycle bins. ```powershell Clear-RecycleBin -Force ``` `Clear-RecycleBin` uses the **Force** parameter and doesn't prompt the user for confirmation to clear all recycle bins. An alternative is to replace `-Force` with `-Confirm:$false`. ## PARAMETERS ### -DriveLetter Specifies the recycle bin to clear for a single drive letter or an array of drive letters. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Force Specifies that the user isn't prompted for confirmation to clear a recycle bin. The **Force** parameter also overrides the **WhatIf** and **Confirm** parameters. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts for user confirmation before running the cmdlet. The user is prompted for confirmation even if the **Confirm** parameter isn't specified. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if `Clear-RecycleBin` runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ### None This cmdlet returns no output. ## NOTES This cmdlet is only available on Windows platforms. ## RELATED LINKS

#File: reference/7.6/Microsoft.PowerShell.Management/Convert-Path.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 09/25/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/convert-path?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Convert-Path --- # Convert-Path ## SYNOPSIS Converts a path from a PowerShell path to a PowerShell provider path. ## SYNTAX ### Path (Default) ``` Convert-Path [-Path] <String[]> [<CommonParameters>] ``` ### LiteralPath ``` Convert-Path -LiteralPath <String[]> [<CommonParameters>] ``` ## DESCRIPTION The `Convert-Path` cmdlet converts a path from a PowerShell path to a PowerShell provider path. ## EXAMPLES ### Example 1: Convert the working directory to a standard file system path This example converts the current working directory, which is represented by a dot (`.`), to a standard FileSystem path. ``` PS C:\> Convert-Path . C:\ ``` ### Example 2: Convert a provider path to a standard registry path This example converts the PowerShell provider path to a standard registry path. ```powershell PS C:\> Convert-Path HKLM:\Software\Microsoft HKEY_LOCAL_MACHINE\Software\Microsoft ``` ### Example 3: Convert a path to a string This example converts the path to the home directory of the current provider, which is the FileSystem provider, to a string. ```powershell PS C:\> Convert-Path ~ C:\Users\User01 ``` ### Example 4: Convert paths for hidden items By default, `Convert-Path` does not return hidden items. This example uses the **Force** parameter to find hidden items. The `Get-Item` command confirms that the `.git` folder is hidden. Using `Convert-Path` without the **Force** parameter returns only the visible items. Adding the **Force** parameter returns all items, including hidden items. ```powershell PS> Get-Item .git -Force Directory: D:\Git\PS-Docs\PowerShell-Docs Mode LastWriteTime Length Name ---- ------------- ------ ---- d--h- 9/25/2024 4:46 PM .git PS> Convert-Path .git* D:\Git\PS-Docs\PowerShell-Docs\.github D:\Git\PS-Docs\PowerShell-Docs\.gitattributes D:\Git\PS-Docs\PowerShell-Docs\.gitignore PS> Convert-Path .git* -Force D:\Git\PS-Docs\PowerShell-Docs\.git D:\Git\PS-Docs\PowerShell-Docs\.github D:\Git\PS-Docs\PowerShell-Docs\.gitattributes D:\Git\PS-Docs\PowerShell-Docs\.gitignore ``` ## PARAMETERS ### -Force Allows the cmdlet to get items that otherwise can't be accessed by the user, such as hidden or system files. The **Force** parameter doesn't override security restrictions. Implementation varies among providers. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). This parameter was added in PowerShell 7.5-preview.5. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies, as a string array, the path to be converted. The value of the **LiteralPath** parameter is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the PowerShell path to be converted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a path, but not a literal path, to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns a string that contains the converted path. ## NOTES PowerShell includes the following aliases for `Convert-Path`: - All platforms: - `cvpa` The cmdlets that contain the Path noun manipulate path names and return the names in a concise format that all PowerShell providers can interpret. They're designed for use in programs and scripts where you want to display all or part of a path in a particular format. Use them like you would use **Dirname**, **Normpath**, **Realpath**, **Join**, or other path manipulators. You can use the path cmdlets with several providers, including the **FileSystem**, **Registry**, and **Certificate** providers. This cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). `Convert-Path` only converts existing paths. It can't be used to convert a location that doesn't exist yet. ## RELATED LINKS [Join-Path](Join-Path.md) [Resolve-Path](Resolve-Path.md) [Split-Path](Split-Path.md) [Test-Path](Test-Path.md) [Get-PSProvider](Get-PSProvider.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Copy-Item.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 11/04/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/copy-item?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Copy-Item --- # Copy-Item ## SYNOPSIS Copies an item from one location to another. ## SYNTAX ### Path (Default) - FileSystem provider ``` Copy-Item [-Path] <String[]> [[-Destination] <String>] [-Container] [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Recurse] [-PassThru] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [-FromSession <PSSession>] [-ToSession <PSSession>] [<CommonParameters>] ``` ### LiteralPath - FileSystem provider ``` Copy-Item -LiteralPath <String[]> [[-Destination] <String>] [-Container] [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Recurse] [-PassThru] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [-FromSession <PSSession>] [-ToSession <PSSession>] [<CommonParameters>] ``` ### Path (Default) - All providers ``` Copy-Item [-Path] <string[]> [[-Destination] <string>] [-Container] [-Force] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-PassThru] [-Credential <pscredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath - All providers ``` Copy-Item [[-Destination] <string>] -LiteralPath <string[]> [-Container] [-Force] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-PassThru] [-Credential <pscredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Copy-Item` cmdlet copies an item from one location to another location in the same namespace. For instance, it can copy a file to a folder, but it can't copy a file to a certificate drive. This cmdlet doesn't cut or delete the items being copied. The particular items that the cmdlet can copy depend on the PowerShell provider that exposes the item. For instance, it can copy files and directories in a file system drive and registry keys and entries in the registry drive. This cmdlet can copy and rename items in the same command. To rename an item, enter the new name in the value of the **Destination** parameter. To rename an item and not copy it, use the `Rename-Item` cmdlet. ## EXAMPLES ### Example 1: Copy a file to the specified directory This example copies the `mar1604.log.txt` file to the `C:\Presentation` directory. The original file isn't deleted. ```powershell Copy-Item "C:\Wabash\Logfiles\mar1604.log.txt" -Destination "C:\Presentation" ``` ### Example 2: Copy directory contents to an existing directory This example copies the contents of the `C:\Logfiles` directory into the existing `C:\Drawings` directory. The `Logfiles` directory isn't copied. If the `Logfiles` directory has files in subdirectories, those subdirectories are copied with their file trees intact. By default, the **Container** parameter is set to **True**, which preserves the directory structure. ```powershell Copy-Item -Path "C:\Logfiles\*" -Destination "C:\Drawings" -Recurse ``` > [!NOTE] > If the path `C:\Drawings` doesn't exist the cmdlet copies all the files from the `Logfiles` > folder tree into a single folder `C:\Drawings`, overwriting any files with the same name. ### Example 3: Copy directory and contents to a new directory This example copies the contents of the `C:\Logfiles` source directory and creates a new destination directory. The new destination directory, `\Logs` is created in `C:\Drawings`. To include the source directory's name, copy to an existing destination directory as shown in **Example 2**. Or, name the new destination directory with the same as the source directory. ```powershell Copy-Item -Path "C:\Logfiles" -Destination "C:\Drawings\Logs" -Recurse ``` > [!NOTE] > If the **Path** includes `\*`, all the directory's file contents, including the subdirectory > trees, are copied to the new destination directory. For example: > > `Copy-Item -Path "C:\Logfiles\*" -Destination "C:\Drawings\Logs" -Recurse` ### Example 4: Copy a file to the specified directory and rename the file This example uses the `Copy-Item` cmdlet to copy the `Get-Widget.ps1` script from the `\\Server01\Share` directory to the `\\Server12\ScriptArchive` directory. As part of the copy operation, the command changes the item name from `Get-Widget.ps1` to `Get-Widget.ps1.txt`, so it can be safely attached to email messages. ```powershell Copy-Item "\\Server01\Share\Get-Widget.ps1" -Destination "\\Server12\ScriptArchive\Get-Widget.ps1.txt" ``` ### Example 5: Copy a file to a remote computer A session is created to the remote computer named **Server01** with the credential of `Contoso\User01` and stores the results in the variable named `$Session`. The `Copy-Item` cmdlet copies `test.log` from the `D:\Folder001` folder to the `C:\Folder001_Copy` folder on the remote computer using the session information stored in the `$Session` variable. The original file isn't deleted. ```powershell $Session = New-PSSession -ComputerName "Server01" -Credential "Contoso\User01" Copy-Item "D:\Folder001\test.log" -Destination "C:\Folder001_Copy\" -ToSession $Session ``` ### Example 6: Copy a folder to a remote computer A session is created to the remote computer named **Server01** with the credential of `Contoso\User01` and stores the results in the variable named `$Session`. The `Copy-Item` cmdlet copies the `D:\Folder002` folder to the `C:\Folder002_Copy` directory on the remote computer using the session information stored in the `$Session` variable. Any subfolders or files aren't copied without using the **Recurse** switch. The operation creates the `Folder002_Copy` folder if it doesn't already exist. ```powershell $Session = New-PSSession -ComputerName "Server02" -Credential "Contoso\User01" Copy-Item "D:\Folder002\" -Destination "C:\Folder002_Copy\" -ToSession $Session ``` ### Example 7: Recursively copy the entire contents of a folder to a remote computer A session is created to the remote computer named **Server01** with the credential of `Contoso\User01` and stores the results in the variable named `$Session`. The `Copy-Item` cmdlet copies the entire contents from the `D:\Folder003` folder to the `C:\Folder003_Copy` directory on the remote computer using the session information stored in the `$Session` variable. The subfolders are copied with their file trees intact. The operation creates the `Folder003_Copy` folder if it doesn't already exist. ```powershell $Session = New-PSSession -ComputerName "Server04" -Credential "Contoso\User01" Copy-Item "D:\Folder003\" -Destination "C:\Folder003_Copy\" -ToSession $Session -Recurse ``` ### Example 8: Copy a file to a remote computer and then rename the file A session is created to the remote computer named **Server01** with the credential of `Contoso\User01` and stores the results in the variable named `$Session`. The `Copy-Item` cmdlet copies `scriptingexample.ps1` from the `D:\Folder004` folder to the `C:\Folder004_Copy` folder on the remote computer using the session information stored in the `$Session` variable. The original file isn't deleted. ```powershell $Session = New-PSSession -ComputerName "Server04" -Credential "Contoso\User01" Copy-Item "D:\Folder004\scriptingexample.ps1" -Destination "C:\Folder004_Copy\scriptingexample_copy.ps1" -ToSession $Session ``` ### Example 9: Copy a remote file to the local computer A session is created to the remote computer named **Server01** with the credential of `Contoso\User01` and stores the results in the variable named `$Session`. The `Copy-Item` cmdlet copies `test.log` from the remote `C:\MyRemoteData\` to the local `D:\MyLocalData` folder using the session information stored in the `$Session` variable. The original file isn't deleted. ```powershell $Session = New-PSSession -ComputerName "Server01" -Credential "Contoso\User01" Copy-Item "C:\MyRemoteData\test.log" -Destination "D:\MyLocalData\" -FromSession $Session ``` ### Example 10: Copy the entire contents of a remote folder to the local computer A session is created to the remote computer named **Server01** with the credential of `Contoso\User01` and stores the results in the variable named `$Session`. The `Copy-Item` cmdlet copies the entire contents from the remote `C:\MyRemoteData\scripts` folder to the local `D:\MyLocalData` folder using the session information stored in the `$Session` variable. If the scripts folder has files in subfolders, those subfolders are copied with their file trees intact. ```powershell $Session = New-PSSession -ComputerName "Server01" -Credential "Contoso\User01" Copy-Item "C:\MyRemoteData\scripts" -Destination "D:\MyLocalData\" -FromSession $Session ``` ### Example 11: Recursively copy the entire contents of a remote folder to the local computer A session is created to the remote computer named **Server01** with the credential of `Contoso\User01` and stores the results in the variable named `$Session`. The `Copy-Item` cmdlet copies the entire contents from the remote `C:\MyRemoteData\scripts` folder to the local `D:\MyLocalData\scripts` folder using the session information stored in the `$Session` variable. Because the **Recurse** parameter is used, the operation creates the scripts folder if it doesn't already exist. If the scripts folder has files in subfolders, those subfolders are copied with their file trees intact. ```powershell $Session = New-PSSession -ComputerName "Server01" -Credential "Contoso\User01" Copy-Item "C:\MyRemoteData\scripts" -Destination "D:\MyLocalData\scripts" -FromSession $Session -Recurse ``` ### Example 12: Recursively copy files from a folder tree into the current folder This example shows how to copy files from a multilevel folder structure into a single flat folder. The first three commands show the existing folder structure and the contents of two files, both names `file3.txt`. ```powershell PS C:\temp\test> (Get-ChildItem C:\temp\tree -Recurse).FullName C:\temp\tree\subfolder C:\temp\tree\file1.txt C:\temp\tree\file2.txt C:\temp\tree\file3.txt C:\temp\tree\subfolder\file3.txt C:\temp\tree\subfolder\file4.txt C:\temp\tree\subfolder\file5.txt PS C:\temp\test> Get-Content C:\temp\tree\file3.txt This is file3.txt in the root folder PS C:\temp\test> Get-Content C:\temp\tree\subfolder\file3.txt This is file3.txt in the subfolder PS C:\temp\test> Copy-Item -Path C:\temp\tree -Filter *.txt -Recurse -Container:$false PS C:\temp\test> (Get-ChildItem . -Recurse).FullName C:\temp\test\subfolder C:\temp\test\file1.txt C:\temp\test\file2.txt C:\temp\test\file3.txt C:\temp\test\file4.txt C:\temp\test\file5.txt PS C:\temp\test> Get-Content .\file3.txt This is file3.txt in the subfolder ``` The `Copy-Item` cmdlet has the **Container** parameter set to `$false`. This causes the contents of the source folder to be copied but doesn't preserve the folder structure. Notice that files with the same name are overwritten in the destination folder. ### Example 13: Using filters to copy items without recursion This example shows the results using the **Include** parameter to select the items to be copied. This example uses the following folder structure containing the files to be copied: - `D:\temp\tree\example.ps1` - `D:\temp\tree\example.txt` - `D:\temp\tree\examples\` - `D:\temp\tree\examples\example_1.txt` - `D:\temp\tree\examples\example_2.txt` - `D:\temp\tree\examples\subfolder\` - `D:\temp\tree\examples\subfolder\test.txt` In this example, `Copy-Item` is called with a wildcard for both the **Path** and **Include** parameters. Specifying a wildcard for the **Path** parameter ensures that it processes all files and folders that match `D:\temp\tree\*`. The **Include** parameter filters the list of items to process, limiting the operation to only those paths that begin with `ex`. ```powershell PS D:\temp\test\out> Copy-Item -Path D:\temp\tree\* -Include ex* PS D:\temp\test\out> (Get-ChildItem -Recurse).FullName D:\temp\out\examples D:\temp\out\example.ps1 D:\temp\out\example.txt ``` The **Include** parameter is applied to the contents of `D:\temp\tree` folder to copy all items that match `ex*`. Notice that, without recursion, the `D:\temp\out\examples` folder is copied, but none of its contents are copied. ### Example 14: Using filters to copy items with recursion This example shows the results using the **Include** parameter to select the items to be copied. This example uses the following folder structure containing the files to be copied: - `D:\temp\tree\example.ps1` - `D:\temp\tree\example.txt` - `D:\temp\tree\examples\` - `D:\temp\tree\examples\example_1.txt` - `D:\temp\tree\examples\example_2.txt` - `D:\temp\tree\examples\subfolder\` - `D:\temp\tree\examples\subfolder\test.txt` In this example, `Copy-Item` is called with a wildcard for both the **Path** and **Include** parameters. Specifying a wildcard for the **Path** parameter ensures that it processes all the files and folders that match `D:\temp\tree\*`. The **Include** parameter filters the list of items to process, limiting the operation to only those paths that begin with `ex`. ```powershell D:\temp\out> Copy-Item -Path D:\temp\tree\* -Include ex* -Recurse D:\temp\out> (Get-ChildItem -Recurse).FullName D:\temp\out\examples D:\temp\out\example.ps1 D:\temp\out\example.txt D:\temp\out\examples\subfolder D:\temp\out\examples\example_1.txt D:\temp\out\examples\example_2.txt D:\temp\out\examples\subfolder\test.txt ``` The **Include** parameter is applied to the contents of `D:\temp\tree` folder to copy all items that match `ex*`. Notice that, with recursion, the `D:\temp\out\examples` folder is copied along with all the files and subfolders. The copy includes files that _do not_ match the include filter. When using `Copy-Item`, the filters only apply to the top-level specified by the **Path** parameter. Then recursion is applied to those matching items. > [!NOTE] > The behavior of the **Exclude** parameter is the same as described in this example, except that > it limits the operation to only those paths that don't match the pattern. ### Example 15: Limit the files to recursively copy from a wildcard-specified path This example shows how to limit the files recursively copied from a wildcard-matching path into another folder. Example 13 shows that, because the **Include** parameter only filters on the paths resolved for a wildcard-specifying **Path**, the **Include** parameter can't be used to limit the files recursively copied from a folder. Instead, you can use `Get-ChildItem` to find the items you want to copy and pass those items to `Copy-Item`. This example uses the following folder structure containing the files to be copied: - `D:\temp\tree\example.ps1` - `D:\temp\tree\example.txt` - `D:\temp\tree\examples\` - `D:\temp\tree\examples\example_1.txt` - `D:\temp\tree\examples\example_2.txt` - `D:\temp\tree\examples\subfolder\` - `D:\temp\tree\examples\subfolder\test.txt` To copy all items that begin with `ex*`, use `Get-ChildItem` with the **Recurse** and **Filter** parameters and pipe the results to `Copy-Item`. ```powershell D:\temp\out> Get-ChildItem -Path D:\temp\tree -Recurse -Filter ex* | Copy-Item D:\temp\out> (Get-ChildItem -Recurse).FullName D:\temp\out\examples D:\temp\out\example_1.txt D:\temp\out\example_2.txt D:\temp\out\example.ps1 D:\temp\out\example.txt ``` Unlike the `Copy-Item`, the **Filter** parameter for `Get-ChildItem` applies to the items discovered during recursion. This enables you to find, filter, and then copy items recursively. ## PARAMETERS ### -Container Indicates that this cmdlet preserves container objects during the copy operation. By default, the **Container** parameter is set to **True**. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: True Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential > [!NOTE] > This parameter isn't supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Destination Specifies the path to the new location. The default is the current directory. To rename the item being copied, specify a new name in the value of the **Destination** parameter. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: Current directory Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies one or more path elements or patterns, such as `"*.txt"`, to limit this cmdlet's operation. The value of this parameter filters against the wildcard-matching result of the **Path** parameter, not the final results. This parameter is only effective when the **Path** is specified with one or more wildcards. Since this parameter only filters on the paths resolved for the **Path** parameter, it doesn't filter any items discovered when recursing through child folders with the **Recurse** parameter. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they're retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Indicates that this cmdlet copies items that can't otherwise be changed, such as copying over a read-only file or alias. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -FromSession This is a dynamic parameter made available by the **FileSystem** provider. Specify the **PSSession** object from which a remote file is being copied. When you use this parameter, the **Path** and **LiteralPath** parameters refer to the local path on the remote machine. For more information, see [about_FileSystem_Provider](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md). ```yaml Type: System.Management.Automation.Runspaces.PSSession Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies one or more path elements or patterns, such as `"*.txt"`, to limit this cmdlet's operation. The value of this parameter filters against the wildcard-matching result of the **Path** parameter, not the final results. This parameter is only effective when the **Path** is specified with one or more wildcards. Since this parameter only filters on the paths resolved for the **Path** parameter, it doesn't filter any items discovered when recursing through child folders with the **Recurse** parameter. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Returns an object that represents the item with which you're working. By default, this cmdlet doesn't generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies, as a string array, the path to the items to copy. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Recurse Indicates that this cmdlet does a recursive copy. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ToSession This is a dynamic parameter made available by the **FileSystem** provider. Specify the **PSSession** object to which a remote file is being copied. When you use this parameter, the **Destination** parameter refers to the local path on the remote machine. For more information, see [about_FileSystem_Provider](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md). ```yaml Type: System.Management.Automation.Runspaces.PSSession Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSObject When you use the **PassThru** parameter, this cmdlet returns an object representing the copied item. ## NOTES PowerShell includes the following aliases for `Copy-Item`: - All platforms: - `copy` - `cpi` - Windows: - `cp` This cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md) [Clear-Item](Clear-Item.md) [Get-Item](Get-Item.md) [Get-PSProvider](Get-PSProvider.md) [Invoke-Item](Invoke-Item.md) [Move-Item](Move-Item.md) [New-Item](New-Item.md) [Remove-Item](Remove-Item.md) [Rename-Item](Rename-Item.md) [Set-Item](Set-Item.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Copy-ItemProperty.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/copy-itemproperty?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Copy-ItemProperty --- # Copy-ItemProperty ## SYNOPSIS Copies a property and value from a specified location to another location. ## SYNTAX ### Path (Default) ``` Copy-ItemProperty [-Path] <String[]> [-Name] <String> [-Destination] <String> [-PassThru] [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath ``` Copy-ItemProperty -LiteralPath <String[]> [-Name] <String> [-Destination] <String> [-PassThru] [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Copy-ItemProperty` cmdlet copies a property and value from a specified location to another location. For instance, you can use this cmdlet to copy one or more registry entries from one registry key to another registry key. ## EXAMPLES ### Example 1: Copy a property from a registry key to another registry key This command copies the property named "MyProperty" from the "MyApplication" registry key to the "MyApplicationRev2" registry key. ```powershell Copy-ItemProperty -Path "MyApplication" -Destination "HKLM:\Software\MyApplicationRev2" -Name "MyProperty" ``` ## PARAMETERS ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Destination Specifies the path to the destination location. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Forces the command to run without asking for user confirmation. Implementation varies from provider to provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies the name of the property to be copied. ```yaml Type: System.String Parameter Sets: (All) Aliases: PSProperty Required: True Position: 2 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies, as a string array, the path to the property to be copied. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSCustomObject When you use the **PassThru** parameter, this cmdlet returns a **PSCustomObject** representing the copied item property. ## NOTES PowerShell includes the following aliases for `Copy-ItemProperty`: - Windows: - `cpp` This cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Clear-ItemProperty](Clear-ItemProperty.md) [Get-ItemProperty](Get-ItemProperty.md) [Move-ItemProperty](Move-ItemProperty.md) [New-ItemProperty](New-ItemProperty.md) [Rename-ItemProperty](Rename-ItemProperty.md) [Set-ItemProperty](Set-ItemProperty.md) [Get-PSProvider](Get-PSProvider.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Debug-Process.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 07/24/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/debug-process?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Debug-Process --- # Debug-Process ## SYNOPSIS Debugs one or more processes running on the local computer. ## SYNTAX ### Name (Default) ``` Debug-Process [-Name] <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Id ``` Debug-Process [-Id] <Int32[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### InputObject ``` Debug-Process -InputObject <Process[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Debug-Process` cmdlet attaches a debugger to one or more running processes on a local computer. You can specify the processes by their process name or process ID (PID), or you can pipe process objects to this cmdlet. This cmdlet attaches the debugger that's registered for the process. Before using this cmdlet, verify that a debugger is installed and configured. ## EXAMPLES ### Example 1: Attach a debugger to a process on the computer ```powershell Debug-Process -Name powershell ``` This command attaches a debugger to the PowerShell process on the computer. ### Example 2: Attach a debugger to all processes that begin with the specified string ```powershell Debug-Process -Name note* ``` This command attaches a debugger to all processes that have names that begin with `note`. ### Example 3: Attach a debugger to multiple processes ```powershell Debug-Process "Winlogon", "Explorer", "Outlook" ``` This command attempts to attach a debugger to the Winlogon, Explorer, and Outlook processes. Winlogon is a protected process. To debug Winlogon, you must run the command as an administrator. ### Example 4: Attach a debugger to multiple process IDs ```powershell Debug-Process -Id 1132, 2028 ``` This command attaches a debugger to the processes that have process IDs 1132 and 2028. ### Example 5: Use Get-Process to get a process then attach a debugger to it ```powershell Get-Process powershell | Debug-Process ``` This command attaches a debugger to the PowerShell processes on the computer. It uses the `Get-Process` cmdlet to get the PowerShell processes on the computer, and it uses a pipeline operator (`|`) to send the processes to the `Debug-Process` cmdlet. To specify a particular PowerShell process, use the **Id** parameter of `Get-Process`. ### Example 6: Attach a debugger to a current process on the local computer ```powershell Debug-Process -Id $PID ``` This command attaches a debugger to the current PowerShell processes on the computer. The command uses the `$PID` automatic variable, which contains the process ID of the current PowerShell process. Then, it uses a pipeline operator (`|`) to send the process ID to the `Debug-Process` cmdlet. For more information about the `$PID` automatic variable, see [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md). ### Example 7: Attach a debugger to a process that uses the InputObject parameter ```powershell $P = Get-Process powershell Debug-Process -InputObject $P ``` This command attaches a debugger to the PowerShell processes on the local computer. The first command uses the `Get-Process` cmdlet to get the PowerShell processes on the computer. It saves the resulting process object in the variable named `$P`. The second command uses the **InputObject** parameter of the `Debug-Process` cmdlet to submit the process object in the `$P` variable. ## PARAMETERS ### -Id Specifies the process IDs of the processes to be debugged. The **Id** parameter name is optional. To find the process ID of a process, type `Get-Process`. ```yaml Type: System.Int32[] Parameter Sets: Id Aliases: PID, ProcessId Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InputObject Specifies the process objects that represent processes to be debugged. Enter a variable that contains the process objects or a command that gets the process objects, such as the `Get-Process` cmdlet. You can also pipe process objects to this cmdlet. ```yaml Type: System.Diagnostics.Process[] Parameter Sets: InputObject Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies the names of the processes to be debugged. If there is more than one process with the same name, this cmdlet attaches a debugger to all processes with that name. The **Name** parameter is optional. ```yaml Type: System.String[] Parameter Sets: Name Aliases: ProcessName Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Int32 You can pipe a process ID to this cmdlet. ### System.Diagnostics.Process You can pipe a process object to this cmdlet. ### System.String You can pipe a process name to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES This cmdlet uses the AttachDebugger method of the Windows Management Instrumentation (WMI) **Win32_Process** class. For more information about this method, see [AttachDebugger method](https://go.microsoft.com/fwlink/?LinkId=143640) in the MSDN library. ## RELATED LINKS [Debug-Process](Debug-Process.md) [Get-Process](Get-Process.md) [Start-Process](Start-Process.md) [Stop-Process](Stop-Process.md) [Wait-Process](Wait-Process.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Get-ChildItem.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 02/26/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-childitem?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-ChildItem --- # Get-ChildItem ## SYNOPSIS Gets the items and child items in one or more specified locations. ## SYNTAX ### Items (Default) ``` Get-ChildItem [[-Path] <string[]>] [[-Filter] <string>] [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-Depth <uint>] [-Force] [-Name] [<CommonParameters>] ``` ### LiteralItems ``` Get-ChildItem [[-Filter] <string>] -LiteralPath <string[]> [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-Depth <uint>] [-Force] [-Name] [<CommonParameters>] ``` ## DESCRIPTION The `Get-ChildItem` cmdlet gets the items in one or more specified locations. If the item is a container, it gets the items inside the container, known as child items. You can use the **Recurse** parameter to get items in all child containers and use the **Depth** parameter to limit the number of levels to recurse. `Get-ChildItem` doesn't display empty directories. When a `Get-ChildItem` command includes the **Depth** or **Recurse** parameters, empty directories aren't included in the output. The `Get-ChildItem` cmdlet is designed to work with the items exposed by any provider. For example, items can be a file system file or directory, registry hive, or a certificate store. To list the providers available in your session, use the `Get-PSProvider` command. Some parameters are only available for a specific provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## EXAMPLES ### Example 1: Get child items from a file system directory This example gets the child items from a file system directory. The filenames and subdirectory names are displayed. For empty locations, the command doesn't return any output and returns to the PowerShell prompt. The `Get-ChildItem` cmdlet uses the **Path** parameter to specify the directory `C:\Test`. `Get-ChildItem` displays the files and directories in the PowerShell console. ```powershell Get-ChildItem -Path C:\Test ``` ```Output Directory: C:\Test Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2/15/2019 08:29 Logs -a---- 2/13/2019 08:55 26 anotherfile.txt -a---- 2/12/2019 15:40 118014 Command.txt -a---- 2/1/2019 08:43 183 CreateTestFile.ps1 -ar--- 2/12/2019 14:31 27 ReadOnlyFile.txt ``` By default `Get-ChildItem` lists the mode (**Attributes**), **LastWriteTime**, file size (**Length**), and the **Name** of the item. The letters in the **Mode** property can be interpreted as follows: - `l` (link) - `d` (directory) - `a` (archive) - `r` (read-only) - `h` (hidden) - `s` (system) For more information about the mode flags, see [about_FileSystem_Provider](../Microsoft.PowerShell.Core/About/about_Filesystem_Provider.md#attributes-flagsexpression). ### Example 2: Get child item names in a directory This example lists only the names of items in a directory. The `Get-ChildItem` cmdlet uses the **Path** parameter to specify the directory `C:\Test`. The **Name** parameter returns only the file or directory names from the specified path. The names returned are relative to the value of the **Path** parameter. ```powershell Get-ChildItem -Path C:\Test -Name ``` ```Output Logs anotherfile.txt Command.txt CreateTestFile.ps1 ReadOnlyFile.txt ``` ### Example 3: Get child items in the current directory and subdirectories This example displays `.txt` files that are located in the current directory and its subdirectories. ```powershell Get-ChildItem -Path .\*.txt -Recurse -Force ``` ```Output Directory: C:\Test\Logs\Adirectory Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2/12/2019 16:16 20 Afile4.txt -a-h-- 2/12/2019 15:52 22 hiddenfile.txt -a---- 2/13/2019 13:26 20 LogFile4.txt Directory: C:\Test\Logs\Backup Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2/12/2019 16:16 20 ATextFile.txt -a---- 2/12/2019 15:50 20 LogFile3.txt Directory: C:\Test\Logs Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2/12/2019 16:16 20 Afile.txt -a-h-- 2/12/2019 15:52 22 hiddenfile.txt -a---- 2/13/2019 13:26 20 LogFile1.txt Directory: C:\Test Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2/13/2019 08:55 26 anotherfile.txt -a---- 2/12/2019 15:40 118014 Command.txt -a-h-- 2/12/2019 15:52 22 hiddenfile.txt -ar--- 2/12/2019 14:31 27 ReadOnlyFile.txt ``` The `Get-ChildItem` cmdlet uses the **Path** parameter to specify `C:\Test\*.txt`. **Path** uses the asterisk (`*`) wildcard to specify all files with the filename extension `.txt`. The **Recurse** parameter searches the **Path** directory and its subdirectories, as shown in the **Directory:** headings. The **Force** parameter displays hidden files such as `hiddenfile.txt` that have a mode of **h**. ### Example 4: Get child items using the Include parameter In this example `Get-ChildItem` uses the **Include** parameter to find specific items from the directory specified by the **Path** parameter. ```powershell # When using the -Include parameter, if you don't include an asterisk in the path # the command returns no output. Get-ChildItem -Path C:\Test\ -Include *.txt ``` ```Output ``` ```powershell Get-ChildItem -Path C:\Test\* -Include *.txt ``` ```Output Directory: C:\Test Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2/13/2019 08:55 26 anotherfile.txt -a---- 2/12/2019 15:40 118014 Command.txt -ar--- 2/12/2019 14:31 27 ReadOnlyFile.txt ``` The `Get-ChildItem` cmdlet uses the **Path** parameter to specify the directory `C:\Test`. The **Path** parameter includes a trailing asterisk (`*`) wildcard to specify the directory's contents. The **Include** parameter uses an asterisk (`*`) wildcard to specify all files with the file name extension `.txt`. When the **Include** parameter is used, the **Path** parameter needs a trailing asterisk (`*`) wildcard to specify the directory's contents. For example, `-Path C:\Test\*`. - If the **Recurse** parameter is added to the command, the trailing asterisk (`*`) in the **Path** parameter is optional. The **Recurse** parameter gets items from the **Path** directory and its subdirectories. For example, `-Path C:\Test\ -Recurse -Include *.txt` - If a trailing asterisk (`*`) isn't included in the **Path** parameter, the command doesn't return any output and returns to the PowerShell prompt. For example, `-Path C:\Test\`. ### Example 5: Get child items using the Exclude parameter The example's output shows the contents of the directory `C:\Test\Logs`. The output is a reference for the other commands that use the **Exclude** and **Recurse** parameters. ```powershell Get-ChildItem -Path C:\Test\Logs ``` ```Output Directory: C:\Test\Logs Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2/15/2019 13:21 Adirectory d----- 2/15/2019 08:28 AnEmptyDirectory d----- 2/15/2019 13:21 Backup -a---- 2/12/2019 16:16 20 Afile.txt -a---- 2/13/2019 13:26 20 LogFile1.txt -a---- 2/12/2019 16:24 23 systemlog1.log ``` ```powershell Get-ChildItem -Path C:\Test\Logs\* -Exclude A* ``` ```Output Directory: C:\Test\Logs Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2/15/2019 13:21 Backup -a---- 2/13/2019 13:26 20 LogFile1.txt -a---- 2/12/2019 16:24 23 systemlog1.log ``` The `Get-ChildItem` cmdlet uses the **Path** parameter to specify the directory `C:\Test\Logs`. The **Exclude** parameter uses the asterisk (`*`) wildcard to specify any files or directories that begin with `A` or `a` are excluded from the output. When the **Exclude** parameter is used, a trailing asterisk (`*`) in the **Path** parameter is optional. For example, `-Path C:\Test\Logs` or `-Path C:\Test\Logs\*`. - If a trailing asterisk (`*`) isn't included in the **Path** parameter, the contents of the **Path** parameter are displayed. The exceptions are filenames or subdirectory names that match the **Exclude** parameter's value. - If a trailing asterisk (`*`) is included in the **Path** parameter, the command recurses into the **Path** parameter's subdirectories. The exceptions are filenames or subdirectory names that match the **Exclude** parameter's value. - If the **Recurse** parameter is added to the command, the recursion output is the same whether or not the **Path** parameter includes a trailing asterisk (`*`). ### Example 6: Get the registry keys from a registry hive This example gets all the registry keys from `HKEY_LOCAL_MACHINE\HARDWARE`. `Get-ChildItem` uses the **Path** parameter to specify the registry key `HKLM:\HARDWARE`. The hive's path and top level of registry keys are displayed in the PowerShell console. For more information, see [about_Registry_Provider](../Microsoft.PowerShell.Core/About/about_Registry_Provider.md). ```powershell Get-ChildItem -Path HKLM:\HARDWARE ``` ```Output Hive: HKEY_LOCAL_MACHINE\HARDWARE Name Property ---- -------- ACPI DESCRIPTION DEVICEMAP RESOURCEMAP UEFI ``` ```powershell Get-ChildItem -Path HKLM:\HARDWARE -Exclude D* ``` ```Output Hive: HKEY_LOCAL_MACHINE\HARDWARE Name Property ---- -------- ACPI RESOURCEMAP ``` The first command shows the contents of the `HKLM:\HARDWARE` registry key. The **Exclude** parameter tells `Get-ChildItem` not to return any subkeys that start with `D*`. Currently, the **Exclude** parameter only works on subkeys, not item properties. ### Example 7: Get all certificates with code-signing authority This example gets each certificate in the PowerShell `Cert:` drive that has code-signing authority. The `Get-ChildItem` cmdlet uses the **Path** parameter to specify the Certificate provider with the `Cert:` drive. The **Recurse** parameter searches the directory specified by **Path** and its subdirectories. The **CodeSigningCert** parameter gets only certificates that have code-signing authority. ```powershell Get-ChildItem -Path Cert:\* -Recurse -CodeSigningCert ``` For more information about the Certificate provider and the `Cert:` drive, see [about_Certificate_Provider](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md). ### Example 8: Get items using the Depth parameter This example displays the items in a directory and its subdirectories. The **Depth** parameter determines the number of subdirectory levels to include in the recursion. Empty directories are excluded from the output. ```powershell Get-ChildItem -Path C:\Parent -Depth 2 ``` ```Output Directory: C:\Parent Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2/14/2019 10:24 SubDir_Level1 -a---- 2/13/2019 08:55 26 file.txt Directory: C:\Parent\SubDir_Level1 Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2/14/2019 10:24 SubDir_Level2 -a---- 2/13/2019 08:55 26 file.txt Directory: C:\Parent\SubDir_Level1\SubDir_Level2 Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 2/14/2019 10:22 SubDir_Level3 -a---- 2/13/2019 08:55 26 file.txt ``` The `Get-ChildItem` cmdlet uses the **Path** parameter to specify `C:\Parent`. The **Depth** parameter specifies two levels of recursion. `Get-ChildItem` displays the contents of the directory specified by the **Path** parameter and the two levels of subdirectories. ### Example 9: Getting hard link information In PowerShell 6.2, an alternate view was added to get hard link information. ```powershell Get-ChildItem -Path C:\PathContainingHardLink | Format-Table -View childrenWithHardLink ``` ### Example 10: Output for Non-Windows Operating Systems In PowerShell 7.1 on Unix systems, the `Get-ChildItem` provides Unix-like output: ```powershell PS> Get-ChildItem /etc/r* ``` ```Output Directory: /etc UnixMode User Group LastWriteTime Size Name -------- ---- ----- ------------- ---- ---- drwxr-xr-x root wheel 9/30/2019 19:19 128 racoon -rw-r--r-- root wheel 9/26/2019 18:20 1560 rc.common -rw-r--r-- root wheel 7/31/2017 17:30 1560 rc.common~previous -rw-r--r-- root wheel 9/27/2019 20:34 5264 rc.netboot lrwxr-xr-x root wheel 11/8/2019 15:35 22 resolv.conf -> /private/var/run/resolv.conf -rw-r--r-- root wheel 10/23/2019 17:41 0 rmtab -rw-r--r-- root wheel 10/23/2019 17:41 1735 rpc -rw-r--r-- root wheel 7/25/2017 18:37 1735 rpc~previous -rw-r--r-- root wheel 10/23/2019 18:42 891 rtadvd.conf -rw-r--r-- root wheel 8/24/2017 21:54 891 rtadvd.conf~previous ``` The new properties that are now part of the output are: - **UnixMode** is the file permissions as represented on a Unix system - **User** is the file owner - **Group** is the group owner - **Size** is the size of the file or directory as represented on a Unix system > [!NOTE] > This feature was moved from experimental to mainstream in PowerShell 7.1. ### Example 11: Get the link target for a junction point The `dir` command in the Windows Command Shell shows the target location of a filesystem junction point. In PowerShell, this information is available from the **LinkTarget** property of the filesystem object returned by `Get-ChildItem` and is displayed in the default output. ```powershell PS D:\> New-Item -ItemType Junction -Name tmp -Target $Env:TEMP PS D:\> Get-ChildItem | Select-Object Name, LinkTarget Name LinkTarget ---- ---------- tmp C:\Users\user1\AppData\Local\Temp PS D:\> Get-ChildItem Directory: D:\ Mode LastWriteTime Length Name ---- ------------- ------ ---- l---- 12/16/2021 9:29 AM tmp -> C:\Users\user1\AppData\Local\Temp ``` ### Example 12: Get the link target for an AppX reparse point This example attempts to get the target information for an AppX reparse point. Microsoft Store applications create AppX reparse points in the user's AppData directory. ```powershell Get-ChildItem ~\AppData\Local\Microsoft\WindowsApps\MicrosoftEdge.exe | Select-Object Mode, LinkTarget, LinkType, Name ``` ```Output Mode LinkTarget LinkType Name ---- ---------- -------- ---- la--- MicrosoftEdge.exe ``` At this time, Windows doesn't provide a way to get the target information for an AppX reparse point. The **LinkTarget** and **LinkType** properties of the filesystem object are empty. ## PARAMETERS ### -Attributes > [!NOTE] > This parameter is only available in the > [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider. Gets files and folders with the specified attributes. This parameter supports all attributes and lets you specify complex combinations of attributes. For example, to get non-system files (not directories) that are encrypted or compressed, type: `Get-ChildItem -Attributes !Directory+!System+Encrypted, !Directory+!System+Compressed` To find files and folders with commonly used attributes, use the **Attributes** parameter. Or, the parameters **Directory**, **File**, **Hidden**, **ReadOnly**, and **System**. The **Attributes** parameter supports the following values: - `Archive` - `Compressed` - `Device` - `Directory` - `Encrypted` - `Hidden` - `IntegrityStream` - `Normal` - `NoScrubData` - `NotContentIndexed` - `Offline` - `ReadOnly` - `ReparsePoint` - `SparseFile` - `System` - `Temporary` For a description of these attributes, see the [FileAttributes](xref:System.IO.FileAttributes) enumeration. To combine attributes, use the following operators: - `!` (NOT) - `+` (AND) - `,` (OR) Don't use spaces between an operator and its attribute. Spaces are accepted after commas. For common attributes, use the following abbreviations: - `D` (Directory) - `H` (Hidden) - `R` (Read-only) - `S` (System) ```yaml Type: System.Management.Automation.FlagsExpression`1[System.IO.FileAttributes] Parameter Sets: (All) Aliases: Accepted values: Archive, Compressed, Device, Directory, Encrypted, Hidden, IntegrityStream, Normal, NoScrubData, NotContentIndexed, Offline, ReadOnly, ReparsePoint, SparseFile, System, Temporary Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CodeSigningCert > [!NOTE] > This parameter is only available in the > [Certificate](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md) provider. To get a list of certificates that have `Code Signing` in their **EnhancedKeyUsageList** property value, use the **CodeSigningCert** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Depth This parameter was added in PowerShell 5.0 and enables you to control the depth of recursion. By default, `Get-ChildItem` displays the contents of the parent directory. The **Depth** parameter determines the number of subdirectory levels that are included in the recursion and displays the contents. For example, `-Depth 2` includes the **Path** parameter's directory, first level of subdirectories, and second level of subdirectories. By default directory names and filenames are included in the output. > [!NOTE] > On a Windows computer from PowerShell or **cmd.exe**, you can display a graphical view of a > directory structure with the **tree.com** command. ```yaml Type: System.UInt32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Directory > [!NOTE] > This parameter is only available in the > [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider. To get a list of directories, use the **Directory** parameter or the **Attributes** parameter with the **Directory** property. You can use the **Recurse** parameter with **Directory**. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: ad Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DnsName > [!NOTE] > This parameter is only available in the > [Certificate](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md) provider. Specifies a domain name or name pattern to match with the **DNSNameList** property of certificates the cmdlet gets. The value of this parameter can either be `Unicode` or `ASCII`. Punycode values are converted to Unicode. Wildcard characters (`*`) are permitted. This parameter was reintroduced in PowerShell 7.1 ```yaml Type: Microsoft.PowerShell.Commands.DnsNameRepresentation Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -DocumentEncryptionCert > [!NOTE] > This parameter is only available in the > [Certificate](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md) provider. To get a list of certificates that have `Document Encryption` in their **EnhancedKeyUsageList** property value, use the **DocumentEncryptionCert** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Eku > [!NOTE] > This parameter is only available in the > [Certificate](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md) provider. Specifies text or a text pattern to match with the **EnhancedKeyUsageList** property of certificates the cmdlet gets. Wildcard characters (`*`) are permitted. The **EnhancedKeyUsageList** property contains the friendly name and the OID fields of the EKU. This parameter was reintroduced in PowerShell 7.1 ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Exclude Specifies an array of one or more string patterns to be matched as the cmdlet gets child items. Any matching item is excluded from the output. Enter a path element or pattern, such as `*.txt` or `A*`. Wildcard characters are accepted. A trailing asterisk (`*`) in the **Path** parameter is optional. For example, `-Path C:\Test\Logs` or `-Path C:\Test\Logs\*`. If a trailing asterisk (`*`) is included, the command recurses into the **Path** parameter's subdirectories. Without the asterisk (`*`), the contents of the **Path** parameter are displayed. More details are included in Example 5 and the Notes section. The **Include** and **Exclude** parameters can be used together. However, the exclusions are applied after the inclusions, which can affect the final output. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -ExpiringInDays > [!NOTE] > This parameter is only available in the > [Certificate](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md) provider. Specifies that the cmdlet should only return certificates that are expiring in or before the specified number of days. A value of zero (`0`) gets certificates that have expired. This parameter was reintroduced in PowerShell 7.1 ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -File > [!NOTE] > This parameter is only available in the > [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider. To get a list of files, use the **File** parameter. You can use the **Recurse** parameter with **File**. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: af Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports filters. Filters are more efficient than other parameters. The provider applies filter when the cmdlet gets the objects rather than having PowerShell filter the objects after they're retrieved. The filter string is passed to the .NET API to enumerate files. The API only supports `*` and `?` wildcards. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -FollowSymlink > [!NOTE] > This parameter is only available in the > [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider. By default, the `Get-ChildItem` cmdlet displays symbolic links to directories found during recursion, but doesn't recurse into them. Use the **FollowSymlink** parameter to search the directories that target those symbolic links. The **FollowSymlink** is a dynamic parameter and is supported only in the **FileSystem** provider. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Allows the cmdlet to get items that otherwise can't be accessed by the user, such as hidden or system files. The **Force** parameter doesn't override security restrictions. Implementation varies by provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Hidden > [!NOTE] > This parameter is only available in the > [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider. To get only hidden items, use the **Hidden** parameter or the **Attributes** parameter with the **Hidden** property. By default, `Get-ChildItem` doesn't display hidden items. Use the **Force** parameter to get hidden items. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: ah, h Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies an array of one or more string patterns to be matched as the cmdlet gets child items. Any matching item is included in the output. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. The **Include** and **Exclude** parameters can be used together. However, the exclusions are applied after the inclusions, which can affect the final output. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell to not interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.PowerShell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralItems Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Gets only the names of the items in the location. The output is a string object that can be sent down the pipeline to other commands. The names returned are relative to the value of the **Path** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies a path to one or more locations. If not specified, the default location is the current directory (`.`). Wildcards are accepted. Use care when using the **Path** parameter with the **Recurse** parameter. For more information, see the [NOTES](#notes) section of this article. ```yaml Type: System.String[] Parameter Sets: Items Aliases: Required: False Position: 0 Default value: Current directory Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -ReadOnly > [!NOTE] > This parameter is only available in the > [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider. To get only read-only items, use the **ReadOnly** parameter or the **Attributes** parameter **ReadOnly** property. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: ar Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Recurse Gets the items in the specified locations and in all child items of the locations. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: s, r Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -SSLServerAuthentication > [!NOTE] > This parameter is only available in the > [Certificate](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md) provider. To get a list of certificates that have `Server Authentication` in their **EnhancedKeyUsageList** property value, use the **SSLServerAuthentication** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -System > [!NOTE] > This parameter is only available in the > [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider. Gets only system files and directories. To get only system files and folders, use the **System** parameter or **Attributes** parameter **System** property. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: as Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### System.Management.Automation.AliasInfo The cmdlet outputs this type when accessing the `Alias:` drive. ### Microsoft.PowerShell.Commands.X509StoreLocation ### System.Security.Cryptography.X509Certificates.X509Store ### System.Security.Cryptography.X509Certificates.X509Certificate2 The cmdlet outputs these types when accessing the `Cert:` drive. ### System.Collections.DictionaryEntry The cmdlet outputs this type when accessing the `Env:` drive. ### System.IO.DirectoryInfo ### System.IO.FileInfo The cmdlet outputs these types when accessing the Filesystem drives. ### System.Management.Automation.FunctionInfo ### System.Management.Automation.FilterInfo The cmdlet outputs these types when accessing the `Function:` drives. ### Microsoft.Win32.RegistryKey The cmdlet outputs this type when accessing the Registry drives. ### System.Management.Automation.PSVariable The cmdlet outputs this type when accessing the `Variable:` drives. ### Microsoft.WSMan.Management.WSManConfigContainerElement ### Microsoft.WSMan.Management.WSManConfigLeafElement The cmdlet outputs these types when accessing the `WSMan:` drives. ### System.String When you use the **Name** parameter, this cmdlet returns the object names as strings. ## NOTES PowerShell includes the following aliases for `Get-ChildItem`: - All platforms: - `dir`, `gci` - Windows: - `ls` **Recursion behavior with the Path parameter:** When you use `Get-ChildItem -Recurse` with the **Path** parameter, the cmdlet searches for the last path component whether or not it's a wildcard pattern or a literal name. - If the last path component matches an existing immediate subdirectory of the target directory, the cmdlet performs recursive enumeration on the matching directory. - If the last path component doesn't match an existing immediate subdirectory of the target directory, the cmdlet recursively searches the target directory's hierarchy for items that match the last path component When you use `Get-ChildItem -Recurse` with the **Path** and **Name** parameters, the behavior changes. The command searches for the last path component among the immediate child items of the target directory. - If there is a match among the immediate child items, the cmdlet performs recursive enumeration on the matching items. Wildcard matching happens only once, at the top level of the target directory. The results are processed as if they had been individually passed to the **LiteralPath** parameter. - If the last path component doesn't match any items at the top level, an error occurs. You should avoid using the **Path** parameter with the **Recurse** parameter. For best results: - Use **LiteralPath** to specify the target directory to avoid triggering a recursive search for the last path component. - Use **Filter** or **Include** parameters to specify wildcard or literal patterns that should be searched for in every level of the target directory's hierarchy. ## RELATED LINKS [about_Certificate_Provider](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md) [about_Quoting_Rules](../Microsoft.PowerShell.Core/About/about_Quoting_Rules.md) [about_Registry_Provider](../Microsoft.PowerShell.Core/About/about_Registry_Provider.md) [ForEach-Object](../Microsoft.PowerShell.Core/ForEach-Object.md) [Get-Alias](../Microsoft.PowerShell.Utility/Get-Alias.md) [Get-Item](Get-Item.md) [Get-Location](Get-Location.md) [Get-Process](Get-Process.md) [Get-PSProvider](Get-PSProvider.md) [Split-Path](Split-Path.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Get-Clipboard.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 08/30/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-clipboard?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Clipboard --- # Get-Clipboard ## SYNOPSIS Gets the contents of the clipboard. ## SYNTAX ``` Get-Clipboard [-Raw] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Clipboard` cmdlet gets the contents of the clipboard as text. Multiple lines of text are returned as an array of strings similar to `Get-Content`. > [!NOTE] > On Linux, this cmdlet requires the `xclip` utility to be in the path. On macOS, this cmdlet uses > the `pbpaste` utility. ## EXAMPLES ### Example 1: Get the content of the clipboard and display it to the command-line In this example we have copied the text "hello" into the clipboard. ```powershell Get-Clipboard ``` ```Output hello ``` ## PARAMETERS ### -Raw Gets the entire contents of the clipboard. Multiline text is returned as a single multiline string rather than an array of strings. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns a string containing the contents of the clipboard. ## NOTES PowerShell includes the following aliases for `Get-Clipboard`: - All platforms: - `gcb` Support for this cmdlet on macOS was added in the PowerShell 7.0.0 release. ## RELATED LINKS [Set-Clipboard](Set-Clipboard.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Get-ComputerInfo.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 01/12/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-computerinfo?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-ComputerInfo --- # Get-ComputerInfo ## SYNOPSIS Gets a consolidated object of system and operating system properties. ## SYNTAX ``` Get-ComputerInfo [[-Property] <String[]>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Get-ComputerInfo` cmdlet gets a consolidated object of system and operating system properties. This cmdlet was introduced in Windows PowerShell 5.1. ## EXAMPLES ### Example 1: Get all computer properties This command gets all system and operating system properties from the computer. ```powershell Get-ComputerInfo ``` ### Example 2: Get all computer version properties This command gets all version properties from the computer. ```powershell Get-ComputerInfo -Property "*version" ``` ```Output WindowsCurrentVersion : 6.3 WindowsVersion : 2009 BiosBIOSVersion : {LENOVO - 1380, N1FET64W (1.38 ), Lenovo - 1380} BiosEmbeddedControllerMajorVersion : 1 BiosEmbeddedControllerMinorVersion : 17 BiosSMBIOSBIOSVersion : N1FET64W (1.38 ) BiosSMBIOSMajorVersion : 2 BiosSMBIOSMinorVersion : 8 BiosSystemBiosMajorVersion : 1 BiosSystemBiosMinorVersion : 38 BiosVersion : LENOVO - 1380 OsVersion : 10.0.19043 OsCSDVersion : OsServicePackMajorVersion : 0 OsServicePackMinorVersion : 0 ``` ## PARAMETERS ### -Property Specifies, as a string array, the computer properties in which this cmdlet displays. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String[] You can pipe a string containing the name of a property to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Management.ComputerInfo This cmdlet returns a **ComputerInfo** object. ## NOTES PowerShell includes the following aliases for `Get-ComputerInfo`: - Windows: - `gin` This cmdlet is only available on Windows platforms. ## RELATED LINKS

#File: reference/7.6/Microsoft.PowerShell.Management/Get-Content.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 03/18/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-content?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Content --- # Get-Content ## SYNOPSIS Gets the content of the item at the specified location. ## SYNTAX ### Path (Default) ``` Get-Content [-ReadCount <Int64>] [-TotalCount <Int64>] [-Tail <Int32>] [-Path] <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Force] [-Credential <PSCredential>] [-Delimiter <String>] [-Wait] [-Raw] [-Encoding <Encoding>] [-AsByteStream] [-Stream <String>] [<CommonParameters>] ``` ### LiteralPath ``` Get-Content [-ReadCount <Int64>] [-TotalCount <Int64>] [-Tail <Int32>] -LiteralPath <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Force] [-Credential <PSCredential>] [-Delimiter <String>] [-Wait] [-Raw] [-Encoding <Encoding>] [-AsByteStream] [-Stream <String>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Content` cmdlet gets the content of the item at the location specified by the path, such as the text in a file or the content of a function. For files, the content is read one line at a time and returns a collection of objects, each representing a line of content. Beginning in PowerShell 3.0, `Get-Content` can also get a specified number of lines from the beginning or end of an item. ## EXAMPLES ### Example 1: Get the content of a text file This example gets the content of a file in the current directory. The `LineNumbers.txt` file has 100 lines in the format, **This is Line X** and is used in several examples. ```powershell 1..100 | ForEach-Object { Add-Content -Path .\LineNumbers.txt -Value "This is line $_." } Get-Content -Path .\LineNumbers.txt ``` ```Output This is Line 1 This is Line 2 ... This is line 99. This is line 100. ``` The array values 1-100 are sent down the pipeline to the `ForEach-Object` cmdlet. `ForEach-Object` uses a script block with the `Add-Content` cmdlet to create the `LineNumbers.txt` file. The variable `$_` represents the array values as each object is sent down the pipeline. The `Get-Content` cmdlet uses the **Path** parameter to specify the `LineNumbers.txt` file and displays the content in the PowerShell console. ### Example 2: Limit the number of lines Get-Content returns This command gets the first five lines of a file. The **TotalCount** parameter gets the first five lines of content. This example uses the `LineNumbers.txt` referenced in Example 1. ```powershell Get-Content -Path .\LineNumbers.txt -TotalCount 5 ``` ```Output This is Line 1 This is Line 2 This is Line 3 This is Line 4 This is Line 5 ``` ### Example 3: Get a specific line of content from a text file This command gets a specific number of lines from a file and then displays only the last line of that content. The **TotalCount** parameter gets the first 25 lines of content. This example uses the `LineNumbers.txt` file referenced in Example 1. ```powershell (Get-Content -Path .\LineNumbers.txt -TotalCount 25)[-1] ``` ```Output This is Line 25 ``` The `Get-Content` command is wrapped in parentheses so that the command completes before going to the next step. `Get-Content`returns an array of lines, this allows you to add the index notation after the parenthesis to retrieve a specific line number. In this case, the `[-1]` index specifies the last index in the returned array of 25 retrieved lines. ### Example 4: Get the last line of a text file This command gets the last line of content from a file. This example uses the `LineNumbers.txt` file that was created in Example 1. ```powershell Get-Item -Path .\LineNumbers.txt | Get-Content -Tail 1 ``` ```Output This is Line 100 ``` This example uses the `Get-Item` cmdlet to demonstrate that you can pipe files to `Get-Content`. The **Tail** parameter gets the last line of the file. This method is faster than retrieving all the lines in a variable and using the `[-1]` index notation. ### Example 5: Get the content of an alternate data stream This example describes how to use the **Stream** parameter to get the content of an alternate data stream for files stored on a Windows NTFS volume. In this example, the `Set-Content` cmdlet is used to create sample content in a file named `Stream.txt`. ```powershell Set-Content -Path .\Stream.txt -Value 'This is the content of the Stream.txt file' # Specify a wildcard to the Stream parameter to display all streams of the recently created file. Get-Item -Path .\Stream.txt -Stream * ``` ```Output PSPath : Microsoft.PowerShell.Core\FileSystem::C:\Test\Stream.txt::$DATA PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\Test PSChildName : Stream.txt::$DATA PSDrive : C PSProvider : Microsoft.PowerShell.Core\FileSystem PSIsContainer : False FileName : C:\Test\Stream.txt Stream : :$DATA Length : 44 ``` ```powershell # Retrieve the content of the primary stream. # Note the single quotes to prevent variable substitution. Get-Content -Path .\Stream.txt -Stream ':$DATA' ``` ```Output This is the content of the Stream.txt file ``` ```powershell # Alternative way to get the same content. Get-Content -Path .\Stream.txt -Stream "" # The primary stream doesn't need to be specified to get the primary stream of the file. # This gets the same data as the prior two examples. Get-Content -Path .\Stream.txt ``` ```Output This is the content of the Stream.txt file ``` ```powershell # Use the Stream parameter of Add-Content to create a new Stream containing sample content. $addContentSplat = @{ Path = '.\Stream.txt' Stream = 'NewStream' Value = 'Added a stream named NewStream to Stream.txt' } Add-Content @addContentSplat # Use Get-Item to verify the stream was created. Get-Item -Path .\Stream.txt -Stream * ``` ```Output PSPath : Microsoft.PowerShell.Core\FileSystem::C:\Test\Stream.txt::$DATA PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\Test PSChildName : Stream.txt::$DATA PSDrive : C PSProvider : Microsoft.PowerShell.Core\FileSystem PSIsContainer : False FileName : C:\Test\Stream.txt Stream : :$DATA Length : 44 PSPath : Microsoft.PowerShell.Core\FileSystem::C:\Test\Stream.txt:NewStream PSParentPath : Microsoft.PowerShell.Core\FileSystem::C:\Test PSChildName : Stream.txt:NewStream PSDrive : C PSProvider : Microsoft.PowerShell.Core\FileSystem PSIsContainer : False FileName : C:\Test\Stream.txt Stream : NewStream Length : 46 ``` ```powershell # Retrieve the content of your newly created Stream. Get-Content -Path .\Stream.txt -Stream NewStream ``` ```Output Added a stream named NewStream to Stream.txt ``` The **Stream** parameter is a dynamic parameter of the [FileSystem provider](../microsoft.powershell.core/about/about_filesystem_provider.md#stream-string). By default `Get-Content` only retrieves data from the default, or `:$DATA` stream. **Streams** can be used to store hidden data such as attributes, security settings, or other data. They can also be stored on directories without being child items. ### Example 6: Get raw content The commands in this example get the contents of a file as one string, instead of an array of strings. By default, without the **Raw** dynamic parameter, content is returned as an array of newline-delimited strings. This example uses the `LineNumbers.txt` file referenced in Example 1. ```powershell $raw = Get-Content -Path .\LineNumbers.txt -Raw $lines = Get-Content -Path .\LineNumbers.txt Write-Host "Raw contains $($raw.Count) lines." Write-Host "Lines contains $($lines.Count) lines." ``` ```Output Raw contains 1 lines. Lines contains 100 lines. ``` ### Example 7: Use Filters with Get-Content You can specify a filter to the `Get-Content` cmdlet. When using filters to qualify the **Path** parameter, you need to include a trailing asterisk (`*`) to indicate the contents of the path. The following command gets the content of all `*.log` files in the `C:\Temp` directory. ```powershell Get-Content -Path C:\Temp\* -Filter *.log ``` ### Example 8: Get file contents as a byte array This example demonstrates how to get the contents of a file as a `[byte[]]` as a single object. ```powershell $byteArray = Get-Content -Path C:\temp\test.txt -AsByteStream -Raw Get-Member -InputObject $byteArray ``` ```Output TypeName: System.Byte[] Name MemberType Definition ---- ---------- ---------- Count AliasProperty Count = Length Add Method int IList.Add(System.Object value) ``` The first command uses the **AsByteStream** parameter to get the stream of bytes from the file. The **Raw** parameter ensures that the bytes are returned as a `[System.Byte[]]`. If the **Raw** parameter was absent, the return value is a stream of bytes, which is interpreted by PowerShell as `[System.Object[]]`. ## PARAMETERS ### -AsByteStream Specifies that the content should be read as a stream of bytes. The **AsByteStream** parameter was introduced in Windows PowerShell 6.0. A warning occurs when you use the **AsByteStream** parameter with the **Encoding** parameter. The **AsByteStream** parameter ignores any encoding and the output is returned as a stream of bytes. When reading from and writing to binary files, use the **AsByteStream** parameter and a value of 0 for the **ReadCount** parameter. A **ReadCount** value of 0 reads the entire file in a single read operation. The default **ReadCount** value, 1, reads one byte in each read operation and converts each byte into a separate object. Piping single-byte output to `Set-Content` causes errors unless you use the **AsByteStream** parameter with `Set-Content`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential > [!NOTE] > This parameter isn't supported by any providers installed with PowerShell. To impersonate another > user, or elevate your credentials when running this cmdlet, use > [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Delimiter Specifies the delimiter that `Get-Content` uses to divide the file into objects while it reads. The default is `\n`, the end-of-line character. When reading a text file, `Get-Content` returns a collection of string objects, each ending with an end-of-line character. When you enter a delimiter that doesn't exist in the file, `Get-Content` returns the entire file as a single, undelimited object. You can use this parameter to split a large file into smaller files by specifying a file separator, as the delimiter. The delimiter is preserved (not discarded) and becomes the last item in each file section. **Delimiter** is a dynamic parameter that the **FileSystem** provider adds to the `Get-Content` cmdlet. This parameter works only in file system drives. > [!NOTE] > Currently, when the value of the **Delimiter** parameter is an empty string, `Get-Content` does > not return anything. This is a known issue. To force `Get-Content` to return the entire file as > a single, undelimited string. Enter a value that doesn't exist in the file. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: End-of-line character Accept pipeline input: False Accept wildcard characters: False ``` ### -Encoding Specifies the type of encoding for the target file. The default value is `utf8NoBOM`. The acceptable values for this parameter are as follows: - `ascii`: Uses the encoding for the ASCII (7-bit) character set. - `ansi`: Uses the encoding for the for the current culture's ANSI code page. This option was added in PowerShell 7.4. - `bigendianunicode`: Encodes in UTF-16 format using the big-endian byte order. - `bigendianutf32`: Encodes in UTF-32 format using the big-endian byte order. - `oem`: Uses the default encoding for MS-DOS and console programs. - `unicode`: Encodes in UTF-16 format using the little-endian byte order. - `utf7`: Encodes in UTF-7 format. - `utf8`: Encodes in UTF-8 format. - `utf8BOM`: Encodes in UTF-8 format with Byte Order Mark (BOM) - `utf8NoBOM`: Encodes in UTF-8 format without Byte Order Mark (BOM) - `utf32`: Encodes in UTF-32 format. Encoding is a dynamic parameter that the **FileSystem** provider adds to the `Get-Content` cmdlet. This parameter is available only in file system drives. Beginning with PowerShell 6.2, the **Encoding** parameter also allows numeric IDs of registered code pages (like `-Encoding 1251`) or string names of registered code pages (like `-Encoding "windows-1251"`). For more information, see the .NET documentation for [Encoding.CodePage](/dotnet/api/system.text.encoding.codepage?view=netcore-2.2). Starting with PowerShell 7.4, you can use the `Ansi` value for the **Encoding** parameter to pass the numeric ID for the current culture's ANSI code page without having to specify it manually. > [!NOTE] > **UTF-7*** is no longer recommended to use. As of PowerShell 7.1, a warning is written if you > specify `utf7` for the **Encoding** parameter. ```yaml Type: System.Text.Encoding Parameter Sets: (All) Aliases: Accepted values: ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 Required: False Position: Named Default value: UTF8NoBOM Accept pipeline input: False Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they're retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force **Force** can override a read-only attribute or create directories to complete a file path. The **Force** parameter doesn't attempt to change file permissions or override security restrictions. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the path to an item where `Get-Content` gets the content. Wildcard characters are permitted. The paths must be paths to items, not to containers. For example, you must specify a path to one or more files, not a path to a directory. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Raw Ignores newline characters and returns the entire contents of a file in one string with the newlines preserved. By default, newline characters in a file are used as delimiters to separate the input into an array of strings. This parameter was introduced in PowerShell 3.0. **Raw** is a dynamic parameter that the **FileSystem** provider adds to the `Get-Content` cmdlet This parameter works only in file system drives. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ReadCount Specifies how many lines of content are sent through the pipeline at a time. The default value is 1. A value of 0 (zero) or negative numbers sends all the content at one time. This parameter doesn't change the content displayed, but it does affect the time it takes to display the content. As the value of **ReadCount** increases, the time it takes to return the first line increases, but the total time for the operation decreases. This can make a perceptible difference in large items. ```yaml Type: System.Int64 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 1 Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Stream > [!NOTE] > This Parameter is only available on Windows. Gets the contents of the specified alternate NTFS file stream from the file. Enter the stream name. Wildcards aren't supported. **Stream** is a dynamic parameter that the **FileSystem** provider adds to the `Get-Content` cmdlet. This parameter works only in file system drives on Windows systems. This parameter was introduced in Windows PowerShell 3.0. In PowerShell 7.2, `Get-Content` can retrieve the content of alternative data streams from directories as well as files. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Tail Specifies the number of lines from the end of a file or other item. You can use the **Tail** parameter name or its alias, **Last**. A value of `0` returns no lines. Negative values cause an error. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Last Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -TotalCount Specifies the number of lines from the beginning of a file or other item. A value of `0` returns no lines. Negative values cause an error. You can use the **TotalCount** parameter name or its aliases, **First** or **Head**. ```yaml Type: System.Int64 Parameter Sets: (All) Aliases: First, Head Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Wait Causes the cmdlet to wait indefinitely, keeping the file open, until interrupted. While waiting, `Get-Content` checks the file once per second and outputs new lines if present. When used with the **TotalCount** parameter, `Get-Content` waits until the specified number of lines are available in the specified file. For example, if you specify a **TotalCount** of 10 and the file already has 10 or more lines, `Get-Content` returns the 10 lines and exits. If the file has fewer than 10 lines, `Get-Content` outputs each line as it arrives, but waits until the tenth line arrives before exiting. You can interrupt **Wait** by pressing <kbd>Ctrl</kbd>+<kbd>C</kbd>. Deleting the file causes a non-terminating error that also interrupts the waiting. **Wait** is a dynamic parameter that the FileSystem provider adds to the `Get-Content` cmdlet. This parameter works only in file system drives. **Wait** can't be combined with **Raw**. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Int64 You can pipe the read count or total count to this cmdlet. ### System.String[] You can pipe paths to this cmdlet. ### System.Management.Automation.PSCredential You can pipe credentials to this cmdlet. ## OUTPUTS ### System.Byte When you use the **AsByteStream** parameter, this cmdlet returns the content as bytes. ### System.String By default, this cmdlet returns the content as an array of strings, one per line. When you use the **Raw** parameter, it returns a single string containing every line in the file. ## NOTES PowerShell includes the following aliases for `Get-Content`: - All platforms: - `gc` - `type` - Windows: - `cat` The `Get-Content` cmdlet is designed to work with the data exposed by any provider. To get the providers in your session, use the `Get-PSProvider` cmdlet. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md) [Add-Content](Add-Content.md) [Clear-Content](Clear-Content.md) [ForEach-Object](../Microsoft.PowerShell.Core/ForEach-Object.md) [Get-PSProvider](Get-PSProvider.md) [Set-Content](Set-Content.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Get-HotFix.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 02/23/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-hotfix?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-HotFix --- # Get-HotFix ## SYNOPSIS Gets the hotfixes that are installed on local or remote computers. ## SYNTAX ### Default (Default) ``` Get-HotFix [[-Id] <String[]>] [-ComputerName <String[]>] [-Credential <PSCredential>] [<CommonParameters>] ``` ### DESCRIPTION ``` Get-HotFix [-Description <String[]>] [-ComputerName <String[]>] [-Credential <PSCredential>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Get-HotFix` cmdlet uses the **Win32_QuickFixEngineering** WMI class to list hotfixes that are installed on the local computer or specified remote computers. ## EXAMPLES ### Example 1: Get all hotfixes on the local computer The `Get-HotFix` cmdlet gets all hotfixes installed on the local computer. ```powershell Get-HotFix ``` ```output Source Description HotFixID InstalledBy InstalledOn ------ ----------- -------- ----------- ----------- Server01 Update KB4495590 NT AUTHORITY\SYSTEM 5/16/2019 00:00:00 Server01 Security Update KB4470788 NT AUTHORITY\SYSTEM 1/22/2019 00:00:00 Server01 Update KB4480056 NT AUTHORITY\SYSTEM 1/24/2019 00:00:00 ``` ### Example 2: Get hotfixes from multiple computers filtered by a string The `Get-HotFix` command uses parameters to get hotfixes installed on remote computers. The results are filtered by a specified description string. ```powershell Get-HotFix -Description Security* -ComputerName Server01, Server02 -Credential Domain01\admin01 ``` `Get-HotFix` filters the output with the **Description** parameter and the string **Security** that includes the asterisk (`*`) wildcard. The **ComputerName** parameter includes a comma-separated string of remote computer names. The **Credential** parameter specifies a user account that has permission to access the remote computers and run commands. ### Example 3: Verify if an update is installed and write computer names to a file The commands in this example verify whether a particular update installed. If the update isn't installed, the computer name is written to a text file. ```powershell $A = Get-Content -Path ./Servers.txt $A | ForEach-Object { if (!(Get-HotFix -Id KB957095 -ComputerName $_)) { Add-Content $_ -Path ./Missing-KB957095.txt }} ``` The `$A` variable contains computer names that were obtained by `Get-Content` from a text file. The objects in `$A` are sent down the pipeline to `ForEach-Object`. An `if` statement uses the `Get-HotFix` cmdlet with the **Id** parameter and a specific Id number for each computer name. If a computer doesn't have the specified hotfix Id installed, the `Add-Content` cmdlet writes the computer name to a file. ### Example 4: Get the most recent hotfix on the local computer This example gets the most recent hotfix installed on a computer. ```powershell (Get-HotFix | Sort-Object -Property InstalledOn)[-1] ``` `Get-HotFix` sends the objects down the pipeline to the `Sort-Object` cmdlet. `Sort-Object` sorts objects by ascending order and uses the **Property** parameter to evaluate each **InstalledOn** date. The array notation `[-1]` selects the most recent installed hotfix. ## PARAMETERS ### -ComputerName Specifies a remote computer. Type the NetBIOS name, an Internet Protocol (IP) address, or a fully qualified domain name (FQDN) of a remote computer. When the **ComputerName** parameter isn't specified, `Get-HotFix` runs on the local computer. The **ComputerName** parameter doesn't rely on Windows PowerShell remoting. If your computer isn't configured to run remote commands, use the **ComputerName** parameter. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: CN, __Server, IPAddress Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to access the computer and run commands. The default is the current user Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. If you type a user name, you're prompted to enter the password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: False Accept wildcard characters: False ``` ### -Description `Get-HotFix` uses the **Description** parameter to specify hotfix types. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: Description Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Id Filters the `Get-HotFix` results for specific hotfix Ids. Wildcards aren't accepted. ```yaml Type: System.String[] Parameter Sets: Default Aliases: HFID Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### String You can pipe a string containing a computer name to this cmdlet. ## OUTPUTS ### System.Management.ManagementObject#root\cimv2\Win32_QuickFixEngineering This cmdlet returns objects representing the hotfixes on the computer. ## NOTES This cmdlet is only available on Windows platforms. The **Win32_QuickFixEngineering** [WMI class](/windows/desktop/WmiSdk/retrieving-a-class) represents a small system-wide update, commonly referred to as a quick-fix engineering (QFE) update, applied to the current operating system. This class returns only the updates supplied by Component Based Servicing (CBS). These updates aren't listed in the registry. Updates supplied by Microsoft Windows Installer (MSI) or the [Windows Update](https://www.catalog.update.microsoft.com/) site aren't returned by **Win32_QuickFixEngineering**. For more information, see [Win32_QuickFixEngineering class](/windows/desktop/CIMWin32Prov/win32-quickfixengineering). The `Get-HotFix` output might vary on different operating systems. ## RELATED LINKS [about_Arrays](/powershell/module/microsoft.powershell.core/about/about_arrays) [Add-Content](Add-Content.md) [Get-Credential](xref:Microsoft.PowerShell.Security.Get-Credential) [Win32_QuickFixEngineering class](/windows/desktop/CIMWin32Prov/win32-quickfixengineering)

#File: reference/7.6/Microsoft.PowerShell.Management/Get-Item.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 02/14/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-item?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Item --- # Get-Item ## SYNOPSIS Gets the item at the specified location. ## SYNTAX ### Path (Default) - FileSystem provider ``` Get-Item [-Path] <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-Stream <string[]>] [<CommonParameters>] ``` ### LiteralPath - FileSystem provider ``` Get-Item -LiteralPath <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-Stream <string[]>] [<CommonParameters>] ``` ### Path (Default) - Certificate provider ``` Get-Item [-Path] <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-CodeSigningCert] [-DocumentEncryptionCert] [-SSLServerAuthentication] [-DnsName <string>] [-Eku <string[]>] [-ExpiringInDays <int>] [<CommonParameters>] ``` ### LiteralPath - Certificate provider ``` Get-Item -LiteralPath <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-CodeSigningCert] [-DocumentEncryptionCert] [-SSLServerAuthentication] [-DnsName <string>] [-Eku <string[]>] [-ExpiringInDays <int>] [<CommonParameters>] ``` ### Path (Default) - All providers ``` Get-Item [-Path] <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [<CommonParameters>] ``` ### LiteralPath - All providers ``` Get-Item -LiteralPath <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Item` cmdlet gets the item at the specified location. It doesn't get the contents of the item at the location unless you use a wildcard character (`*`) to request all the contents of the item. This cmdlet is used by PowerShell providers to navigate through different types of data stores. ## EXAMPLES ### Example 1: Get the current directory This example gets the current directory. The dot ('.') represents the item at the current location (not its contents). ```powershell Get-Item . ``` ```output Directory: C:\ Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 7/26/2006 10:01 AM ps-test ``` ### Example 2: Get all the items in the current directory This example gets all the items in the current directory. The wildcard character (`*`) represents all the contents of the current item. ```powershell Get-Item * ``` ```output Directory: C:\ps-test Mode LastWriteTime Length Name ---- ------------- ------ ---- d---- 7/26/2006 9:29 AM Logs d---- 7/26/2006 9:26 AM Recs -a--- 7/26/2006 9:28 AM 80 date.csv -a--- 7/26/2006 10:01 AM 30 filenoext -a--- 7/26/2006 9:30 AM 11472 process.doc -a--- 7/14/2006 10:47 AM 30 test.txt ``` ### Example 3: Get the current directory of a drive This example gets the current directory of the `C:` drive. The object that is retrieved represents only the directory, not its contents. ```powershell Get-Item C: ``` ### Example 4: Get items in the specified drive This example gets the items in the `C:` drive. The wildcard character (`*`) represents all the items in the container, not just the container. ```powershell Get-Item C:\* ``` In PowerShell, use a single asterisk (`*`) to get contents, instead of the traditional `*.*`. The format is interpreted literally, so `*.*` wouldn't retrieve directories or filenames without a dot. ### Example 5: Get a property in the specified directory This example gets the **LastAccessTime** property of the `C:\Windows` directory. **LastAccessTime** is just one property of file system directories. To see all the properties of a directory, type `(Get-Item <directory-name>) | Get-Member`. ```powershell (Get-Item C:\Windows).LastAccessTime ``` ### Example 6: Show the contents of a registry key This example shows the contents of the **Microsoft.PowerShell** registry key. You can use this cmdlet with the PowerShell Registry provider to get registry keys and subkeys, but you must use the `Get-ItemProperty` cmdlet to get the registry values and data. ```powershell Get-Item HKLM:\Software\Microsoft\PowerShell\1\Shellids\Microsoft.PowerShell\ ``` ### Example 7: Get items in a directory that have an exclusion This example gets items in the Windows directory with names that include a dot (`.`), but don't begin with `w*`.This example works only when the path includes a wildcard character (`*`) to specify the contents of the item. ```powershell Get-Item C:\Windows\*.* -Exclude "w*" ``` ### Example 8: Getting hardlink information In PowerShell 6.2, an alternate view was added to get hardlink information. To get the hardlink information, pipe the output to `Format-Table -View childrenWithHardlink` ```powershell Get-Item C:\Windows\System32\ntoskrnl.exe | Format-Table -view childrenWithHardLink ``` ```Output Directory: C:\Windows\System32 Mode LastWriteTime Length Name ---- ------------- ------ ---- la--- 5/12/2021 7:40 AM 10848576 ntoskrnl.exe ``` The `Mode` property identifies the hardlink by the `l` in `la---` ### Example 9: Output for Non-Windows Operating Systems In PowerShell 7.1 on Unix systems, the `Get-Item` cmdlet provides Unix-like output: ```powershell PS> Get-Item /Users ``` ```Output Directory: / UnixMode User Group LastWriteTime Size Name -------- ---- ----- ------------- ---- ---- drwxr-xr-x root admin 12/20/2019 11:46 192 Users ``` The new properties that are now part of the output are: - **UnixMode** is the file permissions as represented on a Unix system - **User** is the file owner - **Group** is the group owner - **Size** is the size of the file or directory as represented on a Unix system > [!NOTE] > This feature was moved from experimental to mainstream in PowerShell 7.1. ## PARAMETERS ### -CodeSigningCert This is a dynamic parameter made available by the **Certificate** provider. This parameter and the **Certificate** provider are only available on Windows. To get certificates that have `Code Signing` in their **EnhancedKeyUsageList** property value, use the **CodeSigningCert** parameter. For more information, see [about_Certificate_Provider](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential > [!NOTE] > This parameter isn't supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -DnsName This is a dynamic parameter made available by the **Certificate** provider. This parameter and the **Certificate** provider are only available on Windows. Specifies a domain name or name pattern to match with the **DNSNameList** property of certificates the cmdlet gets. The value of this parameter can either be `Unicode` or `ASCII`. Punycode values are converted to Unicode. Wildcard characters (`*`) are permitted. This parameter was reintroduced in PowerShell 7.1 For more information, see [about_Certificate_Provider](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md). ```yaml Type: Microsoft.PowerShell.Commands.DnsNameRepresentation Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -DocumentEncryptionCert This is a dynamic parameter made available by the **Certificate** provider. This parameter and the **Certificate** provider are only available on Windows. To get certificates that have `Document Encryption` in their **EnhancedKeyUsageList** property value, use the **DocumentEncryptionCert** parameter. For more information, see [about_Certificate_Provider](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Eku This is a dynamic parameter made available by the **Certificate** provider. This parameter and the **Certificate** provider are only available on Windows. Specifies text or a text pattern to match with the **EnhancedKeyUsageList** property of certificates the cmdlet gets. Wildcard characters (`*`) are permitted. The **EnhancedKeyUsageList** property contains the friendly name and the OID fields of the EKU. This parameter was reintroduced in PowerShell 7.1 For more information, see [about_Certificate_Provider](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -ExpiringInDays This is a dynamic parameter made available by the **Certificate** provider. This parameter and the **Certificate** provider are only available on Windows. Specifies that the cmdlet should only return certificates that are expiring in or before the specified number of days. A value of zero (`0`) gets certificates that have expired. This parameter was reintroduced in PowerShell 7.1 For more information, see [about_Certificate_Provider](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md). ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports filters. Filters are more efficient than other parameters. The provider applies filter when the cmdlet gets the objects rather than having PowerShell filter the objects after they're retrieved. The filter string is passed to the .NET API to enumerate files. The API only supports `*` and `?` wildcards. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Indicates that this cmdlet gets items that can't otherwise be accessed, such as hidden items. Implementation varies from provider to provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). Even using the **Force** parameter, the cmdlet can't override security restrictions. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the path to an item. This cmdlet gets the item at the specified location. Wildcard characters are permitted. This parameter is required, but the parameter name **Path** is optional. Use a dot (`.`) to specify the current location. Use the wildcard character (`*`) to specify all the items in the current location. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -SSLServerAuthentication This is a dynamic parameter made available by the **Certificate** provider. This parameter and the **Certificate** provider are only available on Windows. To get certificates that have `Server Authentication` in their **EnhancedKeyUsageList** property value, use the **SSLServerAuthentication** parameter. For more information, see [about_Certificate_Provider](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Stream This is a dynamic parameter made available by the **FileSystem** provider. This parameter is only available on Windows. Gets the specified alternative data stream from the file. Enter the stream name. Wildcards are supported. To get all streams, use an asterisk (`*`). This parameter is valid on directories, but note that directories do not have data streams by default. This parameter was introduced in PowerShell 3.0. As of PowerShell 7.2, `Get-Item` can get alternative data streams from directories as well as files. For more information, see [about_FileSystem_Provider](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md). ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: No alternate file streams Accept pipeline input: False Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### System.Management.Automation.AliasInfo The cmdlet outputs this type when accessing the `Alias:` drive. ### Microsoft.PowerShell.Commands.X509StoreLocation ### System.Security.Cryptography.X509Certificates.X509Store ### System.Security.Cryptography.X509Certificates.X509Certificate2 The cmdlet outputs these types when accessing the `Cert:` drive. ### System.Collections.DictionaryEntry The cmdlet outputs this type when accessing the `Env:` drive. ### System.IO.DirectoryInfo ### System.IO.FileInfo The cmdlet outputs these types when accessing the FileSystem drives. ### System.Management.Automation.FunctionInfo ### System.Management.Automation.FilterInfo The cmdlet outputs these types when accessing the `Function:` drives. ### Microsoft.Win32.RegistryKey The cmdlet outputs this type when accessing the Registry drives. ### System.Management.Automation.PSVariable The cmdlet outputs this type when accessing the `Variable:` drives. ### Microsoft.WSMan.Management.WSManConfigContainerElement ### Microsoft.WSMan.Management.WSManConfigLeafElement The cmdlet outputs these types when accessing the `WSMan:` drives. ## NOTES PowerShell includes the following aliases for `Get-Item`: - All platforms: - `gi` This cmdlet does not have a **Recurse** parameter, because it gets only an item, not its contents. To get the contents of an item recursively, use `Get-ChildItem`. To navigate through the registry, use this cmdlet to get registry keys and the `Get-ItemProperty` to get registry values and data. The registry values are considered to be properties of the registry key. This cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Clear-Item](Clear-Item.md) [Copy-Item](Copy-Item.md) [Invoke-Item](Invoke-Item.md) [Move-Item](Move-Item.md) [New-Item](New-Item.md) [Remove-Item](Remove-Item.md) [Rename-Item](Rename-Item.md) [Set-Item](Set-Item.md) [Get-ChildItem](Get-ChildItem.md) [Get-ItemProperty](Get-ItemProperty.md) [Get-PSProvider](Get-PSProvider.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Get-ItemProperty.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-itemproperty?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-ItemProperty --- # Get-ItemProperty ## SYNOPSIS Gets the properties of a specified item. ## SYNTAX ### Path (Default) ``` Get-ItemProperty [-Path] <String[]> [[-Name] <String[]>] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [<CommonParameters>] ``` ### LiteralPath ``` Get-ItemProperty -LiteralPath <String[]> [[-Name] <String[]>] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-ItemProperty` cmdlet gets the properties of the specified items. For example, you can use this cmdlet to get the value of the **LastAccessTime** property of a file object. You can also use this cmdlet to view registry entries and their values. ## EXAMPLES ### Example 1: Get information about a specific directory This command gets information about the `C:\Windows` directory. ```powershell Get-ItemProperty C:\Windows ``` ### Example 2: Get the properties of a specific file This command gets the properties of the `C:\Test\Weather.xls` file. The result is piped to the `Format-List` cmdlet to display the output as a list. ```powershell Get-ItemProperty C:\Test\Weather.xls | Format-List ``` ### Example 3: Get the value name and data of a registry entry in a registry subkey This command gets the value name and data of the `ProgramFilesDir` registry entry in the `CurrentVersion` registry subkey. The **Path** specifies the subkey and the **Name** parameter specifies the value name of the entry. ```powershell Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name "ProgramFilesDir" ``` > [!NOTE] > This command requires that there is a PowerShell drive named `HKLM:` that is mapped to the > `HKEY_LOCAL_MACHINE` hive of the registry. > > A drive with that name and mapping is available in PowerShell by default. Alternatively, the path > to this registry subkey can be specified by using the following alternative path that begins with > the provider name followed by two colons: > > `Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion`. ### Example 4: Get the value names and data of registry entries in a registry key This command gets the value names and data of the registry entries in the `PowerShellEngine` registry key. The results are shown in the following sample output. ```powershell Get-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\PowerShell\1\PowerShellEngine ``` ```Output ApplicationBase : C:\Windows\system32\WindowsPowerShell\v1.0\ ConsoleHostAssemblyName : Microsoft.PowerShell.ConsoleHost, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, ProcessorArchitecture=msil PowerShellVersion : 2.0 RuntimeVersion : v2.0.50727 CTPVersion : 5 PSCompatibleVersion : 1.0,2.0 ``` ## PARAMETERS ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. To impersonate another > user, or elevate your credentials when running this cmdlet, use > [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies the name of the property or properties to retrieve. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: PSProperty Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Path Specifies the path to the item or items. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### System.Boolean ### System.String ### System.DateTime ### System.IO.FileInfo ### System.IO.DirectoryInfo This cmdlet returns an object for each item property that it gets. The object type depends on the object that is retrieved. For example, in a file system drive, it might return a file or folder. ## NOTES PowerShell includes the following aliases for `Get-ItemProperty`: - All platforms: - `gp` The `Get-ItemProperty` cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Clear-ItemProperty](Clear-ItemProperty.md) [Copy-ItemProperty](Copy-ItemProperty.md) [Move-ItemProperty](Move-ItemProperty.md) [New-ItemProperty](New-ItemProperty.md) [Remove-ItemProperty](Remove-ItemProperty.md) [Rename-ItemProperty](Rename-ItemProperty.md) [Set-ItemProperty](Set-ItemProperty.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Get-ItemPropertyValue.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 03/10/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-itempropertyvalue?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-ItemPropertyValue --- # Get-ItemPropertyValue ## SYNOPSIS Gets the value for one or more properties of a specified item. ## SYNTAX ### Path (Default) ``` Get-ItemPropertyValue [[-Path] <String[]>] [-Name] <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [<CommonParameters>] ``` ### LiteralPath ``` Get-ItemPropertyValue -LiteralPath <String[]> [-Name] <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-ItemPropertyValue` gets the current value for a property that you specify when you use the **Name** parameter, located in a path that you specify with either the **Path** or **LiteralPath** parameters. ## EXAMPLES ### Example 1: Get the value of the ProductID property This command gets the value of the **ProductID** property of the "\SOFTWARE\Microsoft\Windows NT\CurrentVersion" object in the Windows Registry provider. ```powershell Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' -Name ProductID ``` ```output 94253-50000-11141-AA785 ``` ### Example 2: Get the last write time of a file or folder This command gets the value of the **LastWriteTime** property, or the last time a file or folder was changed, from the `C:\Program Files\PowerShell` folder, working in the FileSystem provider. ```powershell Get-ItemPropertyValue -Path 'C:\Program Files\PowerShell' -Name LastWriteTime ``` ```output Wednesday, September 3, 2014 2:53:22 PM ``` ### Example 3: Get multiple property values of a file or folder This command gets the values of the **LastWriteTime**, **CreationTime**, and **Root** properties of a folder. The property values are returned in the order in which you specified the property names. ```powershell Get-ItemPropertyValue -Path 'C:\Program Files\PowerShell' -Name LastWriteTime,CreationTime,Root ``` ```output Tuesday, March 23, 2021 6:53:13 AM Monday, August 14, 2017 1:42:40 PM Parent : Root : C:\ FullName : C:\ Extension : Name : C:\ Exists : True CreationTime : 10/30/2015 1:28:30 AM CreationTimeUtc : 10/30/2015 6:28:30 AM LastAccessTime : 5/26/2021 9:22:24 AM LastAccessTimeUtc : 5/26/2021 2:22:24 PM LastWriteTime : 5/25/2021 7:25:08 AM LastWriteTimeUtc : 5/25/2021 12:25:08 PM Attributes : Hidden, System, Directory Mode : d--hs ModeWithoutHardLink : d--hs BaseName : C:\ Target : LinkType : ``` ## PARAMETERS ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies the name of the property or properties to retrieve. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: PSProperty Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to the item or items. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSObject This cmdlet returns an object for each item property value that it gets. The object type depends on the property value that is retrieved. ## NOTES PowerShell includes the following aliases for `Get-ItemPropertyValue`: - All platforms: - `gpv` This cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, run the `Get-PSProvider` cmdlet. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Get-ItemProperty](Get-ItemProperty.md) [Clear-ItemProperty](Clear-ItemProperty.md) [Copy-ItemProperty](Copy-ItemProperty.md) [Get-PSProvider](Get-PSProvider.md) [Move-ItemProperty](Move-ItemProperty.md) [New-ItemProperty](New-ItemProperty.md) [Remove-ItemProperty](Remove-ItemProperty.md) [Rename-ItemProperty](Rename-ItemProperty.md) [Set-ItemProperty](Set-ItemProperty.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Get-Location.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-location?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Location --- # Get-Location ## SYNOPSIS Gets information about the current working location or a location stack. ## SYNTAX ### Location (Default) ``` Get-Location [-PSProvider <String[]>] [-PSDrive <String[]>] [<CommonParameters>] ``` ### Stack ``` Get-Location [-Stack] [-StackName <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Location` cmdlet gets an object that represents the current directory, much like the print working directory (pwd) command. When you move between PowerShell drives, PowerShell retains your location in each drive. You can use this cmdlet to find your location in each drive. You can use this cmdlet to get the current directory at run time and use it in functions and scripts, such as in a function that displays the current directory in the PowerShell prompt. You can also use this cmdlet to display the locations in a location stack. For more information, see the Notes and the descriptions of the **Stack** and **StackName** parameters. ## EXAMPLES ### Example 1: Display your current drive location This command displays your location in the current PowerShell drive. ```powershell PS C:\Windows> Get-Location ``` ```Output Path ---- C:\Windows ``` For instance, if you are in the `Windows` directory of the `C:` drive, it displays the path to that directory. ### Example 2: Display your current location for different drives This example demonstrates the use of `Get-Location` to display your current location in different PowerShell drives. `Set-Location` is used to change the location to several different paths on different PSDrives. ```powershell PS C:\> Set-Location C:\Windows PS C:\Windows> Set-Location HKLM:\Software\Microsoft PS HKLM:\Software\Microsoft> Set-Location "HKCU:\Control Panel\Input Method" PS HKCU:\Control Panel\Input Method> Get-Location -PSDrive C Path ---- C:\Windows PS HKCU:\Control Panel\Input Method> Get-Location -PSDrive HKLM Path ---- HKLM:\Software\Microsoft PS HKCU:\Control Panel\Input Method> Set-Location C: PS C:\Windows> Get-Location -PSProvider Registry Path ---- HKCU:\Control Panel\Input Method ``` ### Example 3: Get locations using stacks This example shows how to use the **Stack** and **StackName** parameters of `Get-Location` to list the locations in the current location stack and alternate location stacks. The `Push-Location` cmdlet is used to change into three different locations. The third push uses a different stack name. The **Stack** parameter of `Get-Location` displays the contents of the default stack. The **StackName** parameter of `Get-Location` displays the contents of the stack named `Stack2`. ```powershell PS C:\> Push-Location C:\Windows PS C:\Windows>Push-Location System32 PS C:\Windows\System32>Push-Location WindowsPowerShell -StackName Stack2 C:\Windows\System32\WindowsPowerShell>Get-Location -Stack Path ---- C:\Windows C:\ C:\Windows\System32\WindowsPowerShell>Get-Location -StackName Stack2 Path ---- C:\Windows\System32 ``` ### Example 4: Customize the PowerShell prompt This example shows how to customize the PowerShell prompt. ```powershell PS C:\> function prompt { 'PowerShell: ' + (Get-Location) + '> '} PowerShell: C:\> ``` The function that defines the prompt includes a `Get-Location` command, which is run whenever the prompt appears in the console. The format of the default PowerShell prompt is defined by a special function named `prompt`. You can change the prompt in your console by creating a new function named `prompt`. To see the current prompt function, type the following command: `Get-Content Function:\prompt` ## PARAMETERS ### -PSDrive Gets the current location in the specified PowerShell drive. For instance, if you are in the `Cert:` drive, you can use this parameter to find your current location in the `C:` drive. ```yaml Type: System.String[] Parameter Sets: Location Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PSProvider Gets the current location in the drive supported by the specified PowerShell provider. If the specified provider supports more than one drive, this cmdlet returns the location on the most recently accessed drive. For example, if you are in the `C:` drive, you can use this parameter to find your current location in the drives of the PowerShell **Registry** provider. ```yaml Type: System.String[] Parameter Sets: Location Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Stack Indicates that this cmdlet displays the locations added to the current location stack. You can add locations to stacks by using the `Push-Location` cmdlet. To display the locations in a different location stack, use the **StackName** parameter. For information about location stacks, see the [Notes](#notes). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Stack Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -StackName Specifies, as a string array, the named location stacks. Enter one or more location stack names. To display the locations in the current location stack, use the **Stack** parameter. To make a location stack the current location stack, use the `Set-Location` cmdlet. This cmdlet cannot display the locations in the unnamed default stack unless it is the current stack. ```yaml Type: System.String[] Parameter Sets: Stack Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.PathInfo By default, this cmdlet returns a **PathInfo** object. ### System.Management.Automation.PathInfoStack When you use the **Stack** or **StackName** parameters, this cmdlet returns a **PathInfoStack** object. ## NOTES PowerShell includes the following aliases for `Get-Location`: - All Platforms: - `gl` - `pwd` PowerShell supports multiple runspaces per process. Each runspace has its own _current directory_. This is not the same as `[System.Environment]::CurrentDirectory`. This behavior can be an issue when calling .NET APIs or running native applications without providing explicit directory paths. The `Get-Location` cmdlet returns the current directory of the current PowerShell runspace. This cmdlet is designed to work with the data exposed by any provider. To list the providers in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). The ways that the **PSProvider**, **PSDrive**, **Stack**, and **StackName** parameters interact depends on the provider. Some combinations will result in errors, such as specifying both a drive and a provider that does not expose that drive. If no parameters are specified, this cmdlet returns the **PathInfo** object for the provider that contains the current working location. A stack is a last-in, first-out list in which only the most recently added item is accessible. You add items to a stack in the order that you use them, and then retrieve them for use in the reverse order. PowerShell lets you store provider locations in location stacks. PowerShell creates an unnamed default location stack and you can create multiple named location stacks. If you do not specify a stack name, PowerShell uses the current location stack. By default, the unnamed default location is the current location stack, but you can use the `Set-Location` cmdlet to change the current location stack. To manage location stacks, use the PowerShell `*-Location` cmdlets, as follows. - To add a location to a location stack, use the `Push-Location` cmdlet. - To get a location from a location stack, use the `Pop-Location` cmdlet. - To display the locations in the current location stack, use the **Stack** parameter of the `Get-Location` cmdlet. To display the locations in a named location stack, use the **StackName** parameter of the `Get-Location` cmdlet. - To create a new location stack, use the **StackName** parameter of the `Push-Location` cmdlet. If you specify a stack that does not exist, `Push-Location` creates the stack. - To make a location stack the current location stack, use the **StackName** parameter of the `Set-Location` cmdlet. The unnamed default location stack is fully accessible only when it is the current location stack. If you make a named location stack the current location stack, you can no longer use the `Push-Location` or `Pop-Location` cmdlets to add or get items from the default stack or use this cmdlet to display the locations in the unnamed stack. To make the unnamed stack the current stack, use the **StackName** parameter of the `Set-Location` cmdlet with a value of `$null` or an empty string (`""`). ## RELATED LINKS [Pop-Location](Pop-Location.md) [Push-Location](Push-Location.md) [Set-Location](Set-Location.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Get-Process.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 04/15/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-process?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Process --- # Get-Process ## SYNOPSIS Gets the processes that are running on the local computer. ## SYNTAX ### Name (Default) ``` Get-Process [[-Name] <String[]>] [-Module] [-FileVersionInfo] [<CommonParameters>] ``` ### NameWithUserName ``` Get-Process [[-Name] <String[]>] -IncludeUserName [<CommonParameters>] ``` ### Id ``` Get-Process -Id <Int32[]> [-Module] [-FileVersionInfo] [<CommonParameters>] ``` ### IdWithUserName ``` Get-Process -Id <Int32[]> -IncludeUserName [<CommonParameters>] ``` ### InputObject ``` Get-Process -InputObject <Process[]> [-Module] [-FileVersionInfo] [<CommonParameters>] ``` ### InputObjectWithUserName ``` Get-Process -InputObject <Process[]> -IncludeUserName [<CommonParameters>] ``` ## DESCRIPTION The `Get-Process` cmdlet gets the processes on a local computer. Without parameters, this cmdlet gets all processes on the local computer. You can also specify a specific process by process name or process ID (PID), or by piping a **System.Diagnostics.Process** object to this cmdlet. By default, this cmdlet returns a **Process** object that has detailed information about the process and supports methods that let you control it. With parameters, you can change the type of information returned by this cmdlet. - **Module**: Retrieve information for each module loaded into the process. - **FileVersionInfo**: Retrieve file version information for the main module of the process. > [!NOTE] > A module is an executable file or a dynamic link library (DLL) loaded into a process. A process > has one or more modules. The main module is the module used to initially start the process. For > more information, see [ProcessModule Class](/dotnet/api/system.diagnostics.processmodule). ## EXAMPLES ### Example 1: Get a list of all running processes on the local computer ```powershell Get-Process ``` This command gets a list of all running processes on the local computer. For a definition of each display column, see the [NOTES](#notes) section. To see all properties of a **Process** object, use `Get-Process | Get-Member`. By default, PowerShell displays certain property values using units such as kilobytes (K) and megabytes (M). The actual values when accessed with the member-access operator (`.`) are in bytes. ### Example 2: Display detailed information about one or more processes ```powershell Get-Process winword, explorer | Format-List * ``` This pipeline displays detailed information about the `winword` and `explorer` processes on the computer. It uses the **Name** parameter to specify the processes, but it omits the optional parameter name. The pipeline operator (`|`) pipes **Process** objects to the `Format-List` cmdlet, which displays all available properties (`*`) and their values for each object. You can also identify the processes by their process IDs. For instance, `Get-Process -Id 664, 2060`. ### Example 3: Get all processes with a working set greater than a specified size ```powershell Get-Process | Where-Object { $_.WorkingSet -gt 20971520 } Get-Process | Where-Object WorkingSet -GT 20MB ``` The `Get-Process` cmdlet returns the running processes. The output is piped to the `Where-Object` cmdlet, which selects the objects with a **WorkingSet** value greater than 20,971,520 bytes. In the first example, `Where-Object` uses a scriptblock to compare the **WorkingSet** property of each **Process** object. In the second example, the `Where-Object` cmdlet uses the simplified syntax to compare the **WorkingSet** property. In this case, `-GT` is a parameter, not a comparison operator. The second example also uses a [numeric literal suffix](../Microsoft.PowerShell.Core/About/about_Numeric_Literals.md) as a concise alternative to `20971520`. In PowerShell, `MB` represents a mebibyte (MiB) multiplier. `20MB` is equal to 20,971,520 bytes. ### Example 4: Display processes on the computer in groups based on priority ```powershell $processes = Get-Process $processes | Sort-Object { $_.PriorityClass } | Format-Table -View Priority ``` These commands display processes on the computer in groups based on their [priority class](/dotnet/api/system.diagnostics.processpriorityclass). The first command gets all processes on the computer and stores them in the `$processes` variable. The second command pipes the **Process** objects stored in the `$processes` variable to the `Sort-Object` cmdlet, then to the `Format-Table` cmdlet, which formats the processes using the **Priority** view. ### Example 5: Add a property to the default `Get-Process` output display ```powershell Get-Process -Name pwsh | Format-Table -Property @( @{ Name = 'NPM(K)'; Expression = { [int] ($_.NPM / 1KB) } } @{ Name = 'PM(M)'; Expression = { [int] ($_.PM / 1MB) } } @{ Name = 'WS(M)'; Expression = { [int] ($_.WS / 1MB) } } @{ Name = 'CPU(s)'; Expression = { if ($_.CPU) { $_.CPU.ToString('N') } } } 'Id' @{ Name = 'SI'; Expression = 'SessionId' } 'ProcessName' 'StartTime' ) -AutoSize ``` ```Output NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName StartTime ------ ----- ----- ------ -- -- ----------- --------- 84 46 79 18.297 3188 1 pwsh 4/14/2025 10:40:10 AM 66 30 90 4.328 4640 1 pwsh 4/13/2025 3:33:50 PM 66 30 90 4.516 9204 1 pwsh 4/14/2025 9:54:27 AM ``` This example retrieves processes from the local computer and pipes each **Process** object to the `Format-Table` cmdlet. `Format-Table` recreates the default output display of a **Process** object using a mixture of property names and [calculated properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). The display includes an additional **StartTime** property not present in the default display. ### Example 6: Get version information for a process ```powershell Get-Process -Name pwsh -FileVersionInfo ``` ```Output ProductVersion FileVersion FileName -------------- ----------- -------- 7.5.0 SHA: 99da… 7.5.0.500 C:\Program Files\PowerShell\7\pwsh.exe ``` This command uses the **FileVersionInfo** parameter to get file version information for the main module of the `pwsh` process. The main module is the file used to start the process, which in this case is `pwsh.exe`. To use this command with processes that you don't own on Windows Vista and later versions of Windows, you must run PowerShell with elevated user rights (**Run as administrator**). ### Example 7: Get modules loaded with the specified process ```powershell Get-Process -Name SQL* -Module ``` This command uses the **Module** parameter to get the modules loaded by all processes with a name beginning with `SQL`. To use this command with processes that you don't own on Windows Vista and later versions of Windows, you must run PowerShell with elevated user rights (**Run as administrator**). ### Example 8: Find the owner of a process ```powershell Get-Process -Name pwsh -IncludeUserName ``` ```Output WS(M) CPU(s) Id UserName ProcessName ----- ------ -- -------- ----------- 46.53 21.70 3188 DOMAIN01\user01 pwsh ``` ```powershell Get-CimInstance -ClassName Win32_Process -Filter "name='pwsh.exe'" | Invoke-CimMethod -MethodName GetOwner ``` ```Output Domain ReturnValue User PSComputerName ------ ----------- ---- -------------- DOMAIN01 0 user01 ``` The first command shows how to get the owner of a process. The output reveals that the owner is `DOMAIN01\user01`. The second pipeline shows a different way to get the owner of a process using `Get-CimInstance` and `Invoke-CimMethod`. The **Win32_Process** class with a filter retrieves `pwsh` processes and the invoked `GetOwner()` method returns information on the process's **Domain** and **User**. This method is only available on Windows and doesn't require elevated user rights. ### Example 9: Use an automatic variable to identify the process hosting the current session ```powershell Get-Process -Name pwsh ``` ```Output NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 83 96.21 105.95 4.33 1192 10 pwsh 79 83.81 117.61 2.16 10580 10 pwsh ``` ```powershell Get-Process -Id $PID ``` ```Output NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 83 96.21 77.53 4.39 1192 10 pwsh ``` These commands show how to use the `$PID` automatic variable to identify the process that's hosting the current PowerShell session. You can use this method to distinguish the host process from other `pwsh` processes that you might want to control. The first command gets all `pwsh` processes running. The second command gets the `pwsh` process that's hosting the current session. ### Example 10: Get all processes that have a main window title and display them in a table ```powershell Get-Process | Where-Object -Property MainWindowTitle | Format-Table -Property Id, Name, MainWindowTitle -AutoSize ``` This pipeline gets all processes that have a main window title, and displays them in a table with the process ID and name. **MainWindowTitle** is one of many useful properties of the **Diagnostics.Process** object type that `Get-Process` returns. To view all properties, use `Get-Process | Get-Member`. ## PARAMETERS ### -FileVersionInfo Indicates that this cmdlet gets the file version information for the program that runs in the process. On Windows Vista and later versions of Windows, you must run PowerShell with elevated user rights (**Run as administrator**) to use this parameter on processes that you don't own. Using this parameter is the same as accessing the **MainModule.FileVersionInfo** property of each **Process** object. When you use this parameter, `Get-Process` returns a **FileVersionInfo** object, not a **Process** object. You can't pipe output produced using this parameter to a cmdlet that expects a **Process** object, such as `Stop-Process`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Name, Id, InputObject Aliases: FV, FVI Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies one or more processes by process ID (PID). You can specify multiple IDs separated by commas. To get the PID of a process, use `Get-Process`. To get the PID of the current PowerShell session, use `$PID`. ```yaml Type: System.Int32[] Parameter Sets: Id, IdWithUserName Aliases: PID Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -IncludeUserName Indicates that this command adds a **UserName** property to each returned **Process** object. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: NameWithUserName, IdWithUserName, InputObjectWithUserName Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies one or more **Process** objects. Use a variable that contains the objects, or a command or expression that gets the objects. ```yaml Type: System.Diagnostics.Process[] Parameter Sets: InputObject, InputObjectWithUserName Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Module Indicates that this cmdlet gets the modules that the process has loaded. On Windows Vista and later versions of Windows, you must run PowerShell with elevated user rights (**Run as administrator**) to use this parameter on processes that you don't own. Using this parameter is the same as accessing the **Modules** property of each **Process** object. When you use this parameter, `Get-Process` returns a **ProcessModule** object, not a **Process** object. You can't pipe output produced using this parameter to a cmdlet that expects a **Process** object, such as `Stop-Process`. When you use both the **Module** and **FileVersionInfo** parameters together, this cmdlet returns a **FileVersionInfo** object with information about the file version of all modules. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Name, Id, InputObject Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies one or more processes by process name. You can specify multiple process names separated by commas and use wildcard characters. Using the `-Name` parameter is optional. ```yaml Type: System.String[] Parameter Sets: Name, NameWithUserName Aliases: ProcessName Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.Diagnostics.Process You can pipe **Process** objects to this cmdlet. ## OUTPUTS ### System.Diagnostics.Process By default, this cmdlet returns a **System.Diagnostics.Process** object. ### System.Diagnostics.FileVersionInfo If you use the **FileVersionInfo** parameter, this cmdlet returns a **System.Diagnostics.FileVersionInfo** object. ### System.Diagnostics.ProcessModule If you use the **Module** parameter, without the **FileVersionInfo** parameter, this cmdlet returns a **System.Diagnostics.ProcessModule** object. ## NOTES PowerShell includes the following aliases for `Get-Process`: - All platforms: - `gps` - Windows: - `ps` On computers running 64-bit Windows, the 64-bit version of PowerShell gets the main module and 64-bit process modules. The 32-bit version of PowerShell gets only 32-bit process modules. > [!WARNING] > When you use `Get-Process` to get a 64-bit process in the 32-bit version of PowerShell, properties > such as `Path` and `MainModule` of the returned **Process** object are `$null`. You must use > either the 64-bit version of PowerShell or the > [Win32_Process](/windows/desktop/CIMWin32Prov/win32-process) class. To get process information from a remote computer, use the `Invoke-Command` cmdlet. For more information, see [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). On Windows, you can use the Windows Management Instrumentation (WMI) [Win32_Process](/windows/desktop/CIMWin32Prov/win32-process) class in PowerShell as an alternative to `Get-Process`. For more information, see: - [Example 8: Find the owner of a process](#example-8-find-the-owner-of-a-process) - [Get-CimInstance](../CimCmdlets/Get-CimInstance.md) The default display of a **Process** object is a table view that includes the following columns. - **NPM(K)**: The amount of non-paged memory that the process is using, in kilobytes. - **PM(M)**: The amount of pageable memory that the process is using, in megabytes. - **WS(M)**: The size of the working set of the process, in megabytes. The working set consists of the pages of memory that were recently referenced by the process. - **CPU(s)**: The amount of processor time that the process has used on all processors, in seconds. - **Id**: The process ID (PID) of the process. - **SI**: The session ID of the process. - **ProcessName**: The name of the process. You can use the built-in alternate views for **Process** objects available with `Format-Table`, such as **StartTime** and **Priority**. You can also design your own views. For a description of all available **Process** object members, see [Process Properties](xref:System.Diagnostics.Process#properties) and [Process Methods](xref:System.Diagnostics.Process#methods). ## RELATED LINKS [Debug-Process](Debug-Process.md) [Get-Process](Get-Process.md) [Start-Process](Start-Process.md) [Stop-Process](Stop-Process.md) [Wait-Process](Wait-Process.md) [Where-Object](../Microsoft.PowerShell.Core/Where-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Get-PSDrive.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 01/18/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-psdrive?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-PSDrive --- # Get-PSDrive ## SYNOPSIS Gets drives in the current session. ## SYNTAX ### Name (Default) ``` Get-PSDrive [[-Name] <String[]>] [-Scope <String>] [-PSProvider <String[]>] [<CommonParameters>] ``` ### LiteralName ``` Get-PSDrive [-LiteralName] <String[]> [-Scope <String>] [-PSProvider <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-PSDrive` cmdlet gets the drives in the current session. You can get a particular drive or all drives in the session. This cmdlet gets the following types of drives: - Windows logical drives on the computer, including drives mapped to network shares. - Drives exposed by PowerShell providers (such as the Certificate:, Function:, and Alias: drives) and the HKLM: and HKCU: drives that are exposed by the Windows PowerShell Registry provider. - Session-specified temporary drives and persistent mapped network drives that you create by using the New-PSDrive cmdlet. Beginning in Windows PowerShell 3.0, the **Persist** parameter of the `New-PSDrive` cmdlet can create mapped network drives that are saved on the local computer and are available in other sessions. For more information, see New-PSDrive. Also, beginning in Windows PowerShell 3.0, when an external drive is connected to the computer, Windows PowerShell automatically adds a PSDrive to the file system that represents the new drive. You do not need to restart Windows PowerShell. Similarly, when an external drive is disconnected from the computer, Windows PowerShell automatically deletes the PSDrive that represents the removed drive. ## EXAMPLES ### Example 1: Get drives in the current session ``` PS C:\> Get-PSDrive Name Used (GB) Free (GB) Provider Root ---- --------- --------- -------- ---- Alias Alias C 202.06 23718.91 FileSystem C:\ Cert Certificate \ D 1211.06 123642.32 FileSystem D:\ Env Environment Function Function HKCU Registry HKEY_CURRENT_USER HKLM Registry HKEY_LOCAL_MACHINE Variable Variable ``` This command gets the drives in the current session. The output shows the hard drive (C:), CD-ROM drive (D:), and the drives exposed by the Windows PowerShell providers (Alias:, Cert:, Env:, Function:, HKCU:, HKLM:, and Variable:). ### Example 2: Get a drive on the computer ``` PS C:\foo> Get-PSDrive D Name Used (GB) Free (GB) Provider Root ---- --------- --------- -------- ---- D 1211.06 123642.32 FileSystem D:\ ``` This command gets the D: drive on the computer. Note that the drive letter in the command is not followed by a colon. ### Example 3: Get all the drives that are supported by the Windows PowerShell FileSystem provider ``` PS C:\> Get-PSDrive -PSProvider FileSystem Name Used (GB) Free (GB) Provider Root ---- --------- --------- -------- ---- A A:\ C 202.06 23718.91 FileSystem C:\ D 1211.06 123642.32 FileSystem D:\ G 202.06 710.91 FileSystem \\Music\GratefulDead ``` This command gets all of the drives that are supported by the Windows PowerShell FileSystem provider. This includes fixed drives, logical partitions, mapped network drives, and temporary drives that you create by using the New-PSDrive cmdlet. ### Example 4: Check to see if a drive is in use as a Windows PowerShell drive name ```powershell if (Get-PSDrive X -ErrorAction SilentlyContinue) { Write-Host 'The X: drive is already in use.' } else { New-PSDrive -Name X -PSProvider Registry -Root HKLM:\SOFTWARE } ``` This command checks to see whether the X drive is already in use as a Windows PowerShell drive name. If it is not, the command uses the `New-PSDrive` cmdlet to create a temporary drive that is mapped to the HKLM:\SOFTWARE registry key. ### Example 5: Compare the types of files system drives ``` PS C:\> Get-PSDrive -PSProvider FileSystem Name Used (GB) Free (GB) Provider Root ---- --------- --------- -------- ---- A A:\ C 202.06 23718.91 FileSystem C:\ D 1211.06 123642.32 FileSystem D:\ G 202.06 710.91 FileSystem \\Music\GratefulDead X Registry HKLM:\Network PS C:\> net use New connections will be remembered. Status Local Remote Network ------------------------------------------------------------------------------- OK G: \\Server01\Public Microsoft Windows Network PS C:\> [System.IO.DriveInfo]::GetDrives() | Format-Table Name DriveType DriveFormat IsReady AvailableFreeSpace TotalFreeSpace TotalSize RootDirectory VolumeLabel ---- --------- ----------- ------- ------------------ -------------- --------- ------------- ----------- A:\ Network False A:\ C:\ Fixed NTFS True 771920580608 771920580608 988877418496 C:\ Windows D:\ Fixed NTFS True 689684144128 689684144128 1990045179904 D:\ Big Drive E:\ CDRom False E:\ G:\ Network NTFS True 69120000 69120000 104853504 G:\ GratefulDead PS N:\> Get-CimInstance -Class Win32_LogicalDisk DeviceID DriveType ProviderName VolumeName Size FreeSpace -------- --------- ------------ ---------- ---- --------- A: 4 C: 3 Windows 988877418496 771926069248 D: 3 Big! 1990045179904 689684144128 E: 5 G: 4 \\Music\GratefulDead 988877418496 771926069248 PS C:\> Get-CimInstance -Class Win32_NetworkConnection LocalName RemoteName ConnectionState Status --------- ---------- --------------- ------ G: \\Music\GratefulDead Connected OK ``` This example compares the types of file system drives that are displayed by `Get-PSDrive` to those displayed by using other methods. This example demonstrates different ways to display drives in Windows PowerShell, and it shows that session-specific drives created by using the New-PSDrive cmdlet are accessible only in Windows PowerShell. The first command uses `Get-PSDrive` to get all of the file system drives in the session. This includes the fixed drives (C: and D:), a mapped network drive (G:) that was created by using the **Persist** parameter of `New-PSDrive`, and a PowerShell drive (T:) that was created by using `New-PSDrive` without the **Persist** parameter. The **net use** command displays Windows mapped network drives, in this case it displays only the G drive. It does not display the X: drive that was created by `New-PSDrive`. It shows that the G: drive is also mapped to \\\\Music\\GratefulDead. The third command uses the **GetDrives** method of the Microsoft .NET Framework **System.IO.DriveInfo** class. This command gets the Windows file system drives, including drive G:, but it does not get the drives created by `New-PSDrive`. The fourth command uses the `Get-CimInstance` cmdlet to get the instances of the **Win32_LogicalDisk** class. It returns the A:, C:, D:, E:, and G: drives, but not the drives created by `New-PSDrive`. The last command uses the `Get-CimInstance` cmdlet to display the instances of the **Win32_NetworkConnection** class. Like **net use**, it returns only the persistent G: drive created by `New-PSDrive`. ## PARAMETERS ### -LiteralName Specifies the name of the drive. The value of **LiteralName** is used exactly as it is typed. No characters are interpreted as wildcards. If the name includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: LiteralName Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies, as a string array, the name or name of drives that this cmdlet gets in the operation. Type the drive name or letter without a colon (`:`). ```yaml Type: System.String[] Parameter Sets: Name Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PSProvider Specifies, as a string array, the Windows PowerShell provider. This cmdlet gets only the drives supported by this provider. Type the name of a provider, such as FileSystem, Registry, or Certificate. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Scope Specifies the scope in which this cmdlet gets the drives. The acceptable values for this parameter are: - Global - Local - Script - a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). "Local" is the default. For more information, see [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSDriveInfo This cmdlet returns objects representing the drives in the session. ## NOTES PowerShell includes the following aliases for `Get-PSDrive`: - All platforms: - `gdr` - This cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, use the `Get-PSProvider` cmdlet. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). - Mapped network drives that are created by using the **Persist** parameter of the New-PSDrive cmdlet are specific to a user account. Mapped network drives that you create in sessions that are started with the Run as administrator option or with the credentials of another user are not visible in sessions that are started without explicit credentials or with the credentials of the current user. ## RELATED LINKS [New-PSDrive](New-PSDrive.md) [Remove-PSDrive](Remove-PSDrive.md) [Get-PSProvider](Get-PSProvider.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Get-PSProvider.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-psprovider?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-PSProvider --- # Get-PSProvider ## SYNOPSIS Gets information about the specified PowerShell provider. ## SYNTAX ``` Get-PSProvider [[-PSProvider] <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-PSProvider` cmdlet gets the PowerShell providers in the current session. You can get a particular drive or all drives in the session. PowerShell providers let you access a variety of data stores as though they were file system drives. For information about PowerShell providers, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## EXAMPLES ### Example 1: Display a list of all available providers ```powershell Get-PSProvider ``` This command displays a list of all available PowerShell providers. ### Example 2: Display a list of all PowerShell providers that begin with specified letters ```powershell Get-PSProvider F*, R* | Format-List ``` This command displays a list of all PowerShell providers with names that begin with the letter `F` or `R`. ### Example 3: Find snap-ins or module that added providers to your session ```powershell Get-PSProvider | Format-Table Name, Module, PSSnapIn -AutoSize ``` ```Output Name Module PSSnapIn ---- ------ -------- Registry Microsoft.PowerShell.Core Alias Microsoft.PowerShell.Core Environment Microsoft.PowerShell.Core FileSystem Microsoft.PowerShell.Core Function Microsoft.PowerShell.Core Variable Microsoft.PowerShell.Core Certificate Microsoft.PowerShell.Security WSMan Microsoft.WSMan.Management ``` ```powershell Get-PSProvider | where {$_.ModuleName -eq "Microsoft.PowerShell.Security"} ``` ```Output Name Capabilities Drives ---- ------------ ------ Certificate ShouldProcess {cert} ``` These commands find the PowerShell snap-ins or modules that added providers to your session. All PowerShell elements, including providers, originate in a snap-in or in a module. These commands use the PSSnapin and Module properties of the **ProviderInfo** object that `Get-PSProvider` returns. The values of these properties contain the name of the snap-in or module that adds the provider. The first command gets all of the providers in the session and formats them in a table with the values of their Name, Module, and PSSnapin properties. The second command uses the `Where-Object` cmdlet to get the providers that come from the **Microsoft.PowerShell.Security** snap-in. ### Example 4: Resolve the path of the Home property of the FileSystem provider ```powershell C:\> Resolve-Path ~ ``` ```Output Path ---- C:\Users\User01 ``` ```powershell PS C:\> (Get-PSProvider FileSystem).Home ``` ```Output C:\Users\User01 ``` This example shows that the tilde symbol (`~`) represents the value of the **Home** property of the FileSystem provider. The **Home** property value is optional, but for the **FileSystem** provider, it is defined as `$Env:HOMEDRIVE\$Env:HOMEPATH` or `$HOME`. ## PARAMETERS ### -PSProvider Specifies the name or names of the PowerShell providers about which this cmdlet gets information. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe one or more provider name strings to this cmdlet. ## OUTPUTS ### System.Management.Automation.ProviderInfo This cmdlet returns objects that represent the PowerShell providers in the session. ## NOTES ## RELATED LINKS

#File: reference/7.6/Microsoft.PowerShell.Management/Get-Service.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 03/20/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-service?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Service --- # Get-Service ## SYNOPSIS Gets the services on the computer. ## SYNTAX ### Default (Default) ``` Get-Service [[-Name] <String[]>] [-DependentServices] [-RequiredServices] [-Include <String[]>] [-Exclude <String[]>] [<CommonParameters>] ``` ### DisplayName ``` Get-Service [-DependentServices] [-RequiredServices] -DisplayName <String[]> [-Include <String[]>] [-Exclude <String[]>] [<CommonParameters>] ``` ### InputObject ``` Get-Service [-DependentServices] [-RequiredServices] [-Include <String[]>] [-Exclude <String[]>] [-InputObject <ServiceController[]>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Get-Service` cmdlet gets objects that represent the services on a computer, including running and stopped services. By default, when `Get-Service` is run without parameters, all the local computer's services are returned. You can direct this cmdlet to get only particular services by specifying the service name or the display name of the services, or you can pipe service objects to this cmdlet. ## EXAMPLES ### Example 1: Get all services on the computer This example gets all of the services on the computer. It behaves as though you typed `Get-Service *`. The default display shows the status, service name, and display name of each service. ```powershell Get-Service ``` ### Example 2: Get services that begin with a search string This example retrieves services with service names that begin with `WMI` (Windows Management Instrumentation). ```powershell Get-Service "wmi*" ``` ### Example 3: Display services that include a search string This example displays services with a display name that includes the word `network`. Searching the display name finds network-related services even when the service name doesn't include `Net`, such as xmlprov, the Network Provisioning Service. ```powershell Get-Service -DisplayName "*network*" ``` ### Example 4: Get services that begin with a search string and an exclusion This example only gets the services with service names that begin with `win`, except for the WinRM service. ```powershell Get-Service -Name "win*" -Exclude "WinRM" ``` ### Example 5: Display services that are currently active This example displays only the services with a status of `Running`. ```powershell Get-Service | Where-Object {$_.Status -eq "Running"} ``` `Get-Service` gets all the services on the computer and sends the objects down the pipeline. The `Where-Object` cmdlet, selects only the services with a **Status** property that equals `Running`. Status is only one property of service objects. To see all of the properties, type `Get-Service | Get-Member`. ### Example 6: List the services on the computer that have dependent services This example gets services that have dependent services. ```powershell Get-Service | Where-Object {$_.DependentServices} | Format-List -Property Name, DependentServices, @{ Label="NoOfDependentServices"; Expression={$_.DependentServices.Count} } ``` ```Output Name : AudioEndpointBuilder DependentServices : {AudioSrv} NoOfDependentServices : 1 Name : Dhcp DependentServices : {WinHttpAutoProxySvc} NoOfDependentServices : 1 ... ``` The `Get-Service` cmdlet gets all the services on the computer and sends the objects down the pipeline. The `Where-Object` cmdlet selects the services whose **DependentServices** property isn't null. The results are sent down the pipeline to the `Format-List` cmdlet. The **Property** parameter displays the name of the service, the name of the dependent services, and a calculated property that displays the number of dependent services for each service. ### Example 7: Sort services by property value This example shows that when you sort services in ascending order by the value of their **Status** property, stopped services appear before running services. This happens because the value of **Status** is an enumeration, in which `Stopped` has a value of `1`, and `Running` has a value of `4`. For more information, see [ServiceControllerStatus](/dotnet/api/system.serviceprocess.servicecontrollerstatus). To list running services first, use the **Descending** parameter of the `Sort-Object` cmdlet. ```powershell Get-Service "s*" | Sort-Object Status ``` ```Output Status Name DisplayName ------ ---- ----------- Stopped stisvc Windows Image Acquisition (WIA) Stopped SwPrv MS Software Shadow Copy Provider Stopped SysmonLog Performance Logs and Alerts Running Spooler Print Spooler Running srservice System Restore Service Running SSDPSRV SSDP Discovery Service Running ShellHWDetection Shell Hardware Detection Running Schedule Task Scheduler Running SCardSvr Smart Card Running SamSs Security Accounts Manager Running SharedAccess Windows Firewall/Internet Connectio... Running SENS System Event Notification Running seclogon Secondary Logon ``` ### Example 8: Get the dependent services of a service This example gets the services that the WinRM service requires. The value of the service's **ServicesDependedOn** property is returned. ```powershell Get-Service "WinRM" -RequiredServices ``` ### Example 9: Get a service through the pipeline operator This example gets the WinRM service on the local computer. The service name string, enclosed in quotation marks, is sent down the pipeline to `Get-Service`. ```powershell "WinRM" | Get-Service ``` ## PARAMETERS ### -DependentServices Indicates that this cmdlet gets only the services that depend upon the specified service. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: DS Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -DisplayName Specifies, as a string array, the display names of services to be retrieved. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: DisplayName Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Exclude Specifies, as a string array, a service or services that this cmdlet excludes from the operation. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as `s*`. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Include Specifies, as a string array, a service or services that this cmdlet includes in the operation. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as `s*`. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -InputObject Specifies **ServiceController** objects representing the services to be retrieved. Enter a variable that contains the objects, or type a command or expression that gets the objects. You can pipe a service object to this cmdlet. ```yaml Type: System.ServiceProcess.ServiceController[] Parameter Sets: InputObject Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies the service names of services to be retrieved. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: Default Aliases: ServiceName Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -RequiredServices Indicates that this cmdlet gets only the services that this service requires. This parameter gets the value of the **ServicesDependedOn** property of the service. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: SDO, ServicesDependedOn Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.ServiceProcess.ServiceController You can pipe a service object to this cmdlet. ### System.String You can pipe a service name to this cmdlet. ## OUTPUTS ### System.ServiceProcess.ServiceController This cmdlet returns objects that represent the services on the computer. ## NOTES PowerShell includes the following aliases for `Get-Service`: - Windows: - `gsv` This cmdlet is only available on Windows platforms. Beginning in PowerShell 6.0, the following properties are added to the **ServiceController** objects: **UserName**, **Description**, **DelayedAutoStart**, **BinaryPathName**, and **StartupType** . This cmdlet can display services only when the current user has permission to see them. If this cmdlet does not display services, you might not have permission to see them. To find the service name and display name of each service on your system, type `Get-Service`. The service names appear in the **Name** column, and the display names appear in the **DisplayName** column. > [!NOTE] > Typically, `Get-Service` returns information about services and not driver. However, if you > specify the name of a driver, `Get-Service` returns information about the driver. > > - Enumeration doesn't include device driver services > - When a wildcard is specified, the cmdlet only returns Windows services > - If you specify the **Name** or **DisplayName** that is an exact match to a device service name, > then the device instance is returned When you sort in ascending order by status value, `Stopped` services appear before `Running` services. The **Status** property of a service is an enumerated value in which the names of the statuses represent integer values. The sort is based on the integer value, not the name. `Running` appears before `Stopped` because `Stopped` has a value of `1`, and `Running` has a value of `4`. For more information, see [ServiceControllerStatus](/dotnet/api/system.serviceprocess.servicecontrollerstatus). ## RELATED LINKS [New-Service](New-Service.md) [Restart-Service](Restart-Service.md) [Resume-Service](Resume-Service.md) [Set-Service](Set-Service.md) [Start-Service](Start-Service.md) [Stop-Service](Stop-Service.md) [Suspend-Service](Suspend-Service.md) [Remove-Service](Remove-Service.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Get-TimeZone.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 10/02/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/get-timezone?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-TimeZone --- # Get-TimeZone ## SYNOPSIS Gets the current time zone or a list of available time zones. ## SYNTAX ### Name (Default) ``` Get-TimeZone [[-Name] <String[]>] [<CommonParameters>] ``` ### Id ``` Get-TimeZone -Id <String[]> [<CommonParameters>] ``` ### ListAvailable ``` Get-TimeZone [-ListAvailable] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Get-TimeZone` cmdlet gets the current time zone or a list of available time zones. ## EXAMPLES ### Example 1: Get the current time zone ```powershell Get-TimeZone ``` This command gets the current time zone. ### Example 2: Get time zones that match a specified string ```powershell Get-TimeZone -Name "*pac*" ``` ```Output Pacific Standard Time (Mexico) (UTC-08:00) Pacific Time (US &amp; Canada) Pacific Standard Time SA Pacific Standard Time Pacific SA Standard Time West Pacific Standard Time Central Pacific Standard Time ``` This command gets all time zones that match the specified wildcard. ### Example 3: Get all available time zones ```powershell Get-TimeZone -ListAvailable ``` This command gets all available time zones. ## PARAMETERS ### -Id Specifies, as a string array, the ID or IDs of the time zones that this cmdlet gets. ```yaml Type: System.String[] Parameter Sets: Id Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ListAvailable Indicates that this cmdlet gets all available time zones. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ListAvailable Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies, as a string array, the name or names of the time zones that this cmdlet gets. ```yaml Type: System.String[] Parameter Sets: Name Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String[] ## OUTPUTS ### System.TimeZoneInfo[] ## NOTES PowerShell includes the following aliases for `Get-TimeZone`: - All platforms: - `gtz` ## RELATED LINKS [Set-TimeZone](Set-TimeZone.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Invoke-Item.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/invoke-item?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Invoke-Item --- # Invoke-Item ## SYNOPSIS Performs the default action on the specified item. ## SYNTAX ### Path (Default) ``` Invoke-Item [-Path] <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath ``` Invoke-Item -LiteralPath <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Invoke-Item` cmdlet performs the default action on the specified item. For example, it runs an executable file or opens a document file in the application associated with the document file type. The default action depends on the type of item and is determined by the PowerShell provider that provides access to the data. ## EXAMPLES ### Example 1: Open a file This command opens the file `aliasApr04.doc` in Microsoft Office Word. In this case, opening in Word is the default action for `.doc` files. ```powershell Invoke-Item "C:\Test\aliasApr04.doc" ``` ### Example 2: Open all files of a specific type This command opens all of the Microsoft Office Excel spreadsheets in the `C:\Users\User1\Documents` folder. Each spreadsheet is opened in a new instance of Excel. In this case, opening in Excel is the default action for `.xls` files. ```powershell Invoke-Item "C:\Users\User1\Documents\*.xls" ``` ## PARAMETERS ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the path to the selected item. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output of its own, but the items it invokes may return their own output. ## NOTES PowerShell includes the following aliases for `Invoke-Item`: - `ii` This cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Clear-Item](Clear-Item.md) [Copy-Item](Copy-Item.md) [Get-Item](Get-Item.md) [Move-Item](Move-Item.md) [New-Item](New-Item.md) [Remove-Item](Remove-Item.md) [Rename-Item](Rename-Item.md) [Set-Item](Set-Item.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Join-Path.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 03/25/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/join-path?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Join-Path --- # Join-Path ## SYNOPSIS Combines a path and a child path into a single path. ## SYNTAX ``` Join-Path [-Path] <String[]> [-ChildPath] <String> [[-AdditionalChildPath] <String[]>] [-Resolve] [-Credential <PSCredential>] [<CommonParameters>] ``` ## DESCRIPTION The `Join-Path` cmdlet combines a path and child-path into a single path. The provider supplies the path delimiters. ## EXAMPLES ### Example 1: Combine a path with a child path ```powershell Join-Path -Path "path" -ChildPath "childpath" ``` ```output path\childpath ``` This command uses `Join-Path` to combine a path with a childpath. Since the command is executed from the **FileSystem** provider, it provides the `\` delimiter to join the paths. ### Example 2: Combine paths that already contain directory separators ```powershell Join-Path -Path "path\" -ChildPath "\childpath" ``` ```output path\childpath ``` Existing directory separators `\` are handled so there is only one separator between **Path** and **ChildPath**. ### Example 3: Display files and folders by joining a path with a child path ```powershell Join-Path "C:\win*" "System*" -Resolve ``` This command displays the files and folders that are referenced by joining the `C:\Win\*` path and the `System\*` child path. It displays the same files and folders as `Get-ChildItem`, but it displays the fully qualified path to each item. In this command, the **Path** and **ChildPath** optional parameter names are omitted. ### Example 4: Use Join-Path with the PowerShell Registry provider ```powershell PS HKLM:\> Join-Path -Path System -ChildPath *ControlSet* -Resolve ``` ```output HKLM:\System\ControlSet001 HKLM:\System\CurrentControlSet ``` This command displays the registry keys in the `HKLM\System` registry subkey that include `ControlSet`. The **Resolve** parameter, attempts to resolve the joined path, including wildcards from the current provider path `HKLM:\` ### Example 5: Combine multiple path roots with a child path ```powershell Join-Path -Path C:, D:, E:, F: -ChildPath New ``` ```output C:\New D:\New E:\New F:\New ``` This command uses `Join-Path` to combine multiple path roots with a child path. > [!NOTE] > The Drives specified by **Path** must exist or the join of that entry will fail. ### Example 6: Combine the roots of a file system drive with a child path ```powershell Get-PSDrive -PSProvider FileSystem | ForEach-Object {$_.Root} | Join-Path -ChildPath "Subdir" ``` ```output C:\Subdir D:\Subdir ``` This command combines the roots of each PowerShell file system drive in the console with the `Subdir` child path. The command uses the `Get-PSDrive` cmdlet to get the PowerShell drives supported by the FileSystem provider. The `ForEach-Object` statement selects only the **Root** property of the **PSDriveInfo** objects and combines it with the specified child path. The output shows that the PowerShell drives on the computer included a drive mapped to the `C:\Program Files` directory. ### Example 7: Combine an indefinite number of paths ```powershell Join-Path a b c d e f g ``` ```Output a\b\c\d\e\f\g ``` The **AdditionalChildPath** parameter allows the joining of an unlimited number of paths. In this example, no parameter names are used, thus "a" binds to **Path**, "b" to **ChildPath** and "c-g" to **AdditionalChildPath**. ### Example 8: Combine an indefinite number of paths The **ChildPath** parameter allows the joining of an array of paths. ```powershell Join-Path -Path a -ChildPath b, c, d, e, f, g ``` ```Output a\b\c\d\e\f\g ``` ## PARAMETERS ### -AdditionalChildPath Specifies additional elements to append to the value of the **Path** parameter. The **ChildPath** parameter is still mandatory and must be specified as well. This parameter is specified with the `ValueFromRemainingArguments` property, which enables joining an indefinite number of paths. This parameter was added in PowerShell 6.0. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 2 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ChildPath Specifies the elements to append to the value of the `Path` parameter. Wildcards are permitted. Beginning in PowerShell 7.6-preview.4, this parameter accepts an array of strings. This allows you to specify multiple child paths to join with the main path. You can use this parameter instead of the **AdditionalChildPath** parameter. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Credential > [!NOTE] > This parameter isn't supported by any providers installed with PowerShell. To impersonate another > user, or elevate your credentials when running this cmdlet, use > [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the main path (or paths) to which the child-path is appended. The value of **Path** determines which provider joins the paths and adds the path delimiters. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: PSPath Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Resolve Indicates that this cmdlet should attempt to resolve the joined path from the current provider. - If you use wildcards, the cmdlet returns all paths that match the joined path. - If you don't use wildcards, the cmdlet returns an error if the path doesn't exist. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns a string that contains the resulting path. ## NOTES The cmdlets that contain the Path noun manipulate path names and return the names in a concise format that all PowerShell providers can interpret. They're designed to be used where you want to display all or part of a path in a particular format. Use them like you would use `Dirname`, `Normpath`, `Realpath`, `Join`, or other path manipulators. You can use the path cmdlets with several providers, including the `FileSystem`, `Registry`, and `Certificate` providers. This cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Convert-Path](Convert-Path.md) [Resolve-Path](Resolve-Path.md) [Split-Path](Split-Path.md) [Test-Path](Test-Path.md) [Get-PSProvider](Get-PSProvider.md) [Get-ChildItem](Get-ChildItem.md) [Get-PSDrive](Get-PSDrive.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Microsoft.PowerShell.Management.md

--- Download Help Link: https://aka.ms/powershell75-help Help Version: 7.6.0.0 Locale: en-US Module Guid: eefcb906-b326-4e99-9f54-8b4bb6ef3c6d Module Name: Microsoft.PowerShell.Management ms.date: 03/01/2019 schema: 2.0.0 title: Microsoft.PowerShell.Management --- # Microsoft.PowerShell.Management Module ## Description This section contains the help topics for the cmdlets that are installed with PowerShell Microsoft.PowerShell.Management module. The Management module contains cmdlets that help you manage Windows in PowerShell. ## Microsoft.PowerShell.Management Cmdlets ### [Add-Content](Add-Content.md) Adds content to the specified items, such as adding words to a file. ### [Clear-Content](Clear-Content.md) Deletes the contents of an item, but does not delete the item. ### [Clear-Item](Clear-Item.md) Clears the contents of an item, but does not delete the item. ### [Clear-ItemProperty](Clear-ItemProperty.md) Clears the value of a property but does not delete the property. ### [Clear-RecycleBin](Clear-RecycleBin.md) Clears the contents of a recycle bin. ### [Convert-Path](Convert-Path.md) Converts a path from a PowerShell path to a PowerShell provider path. ### [Copy-Item](Copy-Item.md) Copies an item from one location to another. ### [Copy-ItemProperty](Copy-ItemProperty.md) Copies a property and value from a specified location to another location. ### [Debug-Process](Debug-Process.md) Debugs one or more processes running on the local computer. ### [Get-ChildItem](Get-ChildItem.md) Gets the items and child items in one or more specified locations. ### [Get-Clipboard](Get-Clipboard.md) Gets the contents of the clipboard. [!NOTE] > On Linux, this cmdlet requires the `xclip` utility to be in the path. ### [Get-ComputerInfo](Get-ComputerInfo.md) Gets a consolidated object of system and operating system properties. ### [Get-Content](Get-Content.md) Gets the content of the item at the specified location. ### [Get-HotFix](Get-HotFix.md) Gets the hotfixes that are installed on local or remote computers. ### [Get-Item](Get-Item.md) Gets the item at the specified location. ### [Get-ItemProperty](Get-ItemProperty.md) Gets the properties of a specified item. ### [Get-ItemPropertyValue](Get-ItemPropertyValue.md) Gets the value for one or more properties of a specified item. ### [Get-Location](Get-Location.md) Gets information about the current working location or a location stack. ### [Get-Process](Get-Process.md) Gets the processes that are running on the local computer. ### [Get-PSDrive](Get-PSDrive.md) Gets drives in the current session. ### [Get-PSProvider](Get-PSProvider.md) Gets information about the specified PowerShell provider. ### [Get-Service](Get-Service.md) Gets the services on the computer. ### [Get-TimeZone](Get-TimeZone.md) Gets the current time zone or a list of available time zones. ### [Invoke-Item](Invoke-Item.md) Performs the default action on the specified item. ### [Join-Path](Join-Path.md) Combines a path and a child path into a single path. ### [Move-Item](Move-Item.md) Moves an item from one location to another. ### [Move-ItemProperty](Move-ItemProperty.md) Moves a property from one location to another. ### [New-Item](New-Item.md) Creates a new item. ### [New-ItemProperty](New-ItemProperty.md) Creates a new property for an item and sets its value. ### [New-PSDrive](New-PSDrive.md) Creates temporary and persistent mapped network drives. ### [New-Service](New-Service.md) Creates a new Windows service. ### [Pop-Location](Pop-Location.md) Changes the current location to the location most recently pushed onto the stack. ### [Push-Location](Push-Location.md) Adds the current location to the top of a location stack. ### [Remove-Item](Remove-Item.md) Deletes the specified items. ### [Remove-ItemProperty](Remove-ItemProperty.md) Deletes the property and its value from an item. ### [Remove-PSDrive](Remove-PSDrive.md) Deletes temporary PowerShell drives and disconnects mapped network drives. ### [Remove-Service](Remove-Service.md) Removes a Windows service. ### [Rename-Computer](Rename-Computer.md) Renames a computer. ### [Rename-Item](Rename-Item.md) Renames an item in a PowerShell provider namespace. ### [Rename-ItemProperty](Rename-ItemProperty.md) Renames a property of an item. ### [Resolve-Path](Resolve-Path.md) Resolves the wildcard characters in a path, and displays the path contents. ### [Restart-Computer](Restart-Computer.md) Restarts the operating system on local and remote computers. ### [Restart-Service](Restart-Service.md) Stops and then starts one or more services. ### [Resume-Service](Resume-Service.md) Resumes one or more suspended (paused) services. ### [Set-Clipboard](Set-Clipboard.md) Sets the contents of the clipboard. ### [Set-Content](Set-Content.md) Writes new content or replaces existing content in a file. ### [Set-Item](Set-Item.md) Changes the value of an item to the value specified in the command. ### [Set-ItemProperty](Set-ItemProperty.md) Creates or changes the value of a property of an item. ### [Set-Location](Set-Location.md) Sets the current working location to a specified location. ### [Set-Service](Set-Service.md) Starts, stops, and suspends a service, and changes its properties. ### [Set-TimeZone](Set-TimeZone.md) Sets the system time zone to a specified time zone. ### [Split-Path](Split-Path.md) Returns the specified part of a path. ### [Start-Process](Start-Process.md) Starts one or more processes on the local computer. ### [Start-Service](Start-Service.md) Starts one or more stopped services. ### [Stop-Computer](Stop-Computer.md) Stops (shuts down) local and remote computers. ### [Stop-Process](Stop-Process.md) Stops one or more running processes. ### [Stop-Service](Stop-Service.md) Stops one or more running services. ### [Suspend-Service](Suspend-Service.md) Suspends (pauses) one or more running services. ### [Test-Connection](Test-Connection.md) Sends ICMP echo request packets, or pings, to one or more computers. ### [Test-Path](Test-Path.md) Determines whether all elements of a path exist. ### [Wait-Process](Wait-Process.md) Waits for the processes to be stopped before accepting more input.

#File: reference/7.6/Microsoft.PowerShell.Management/Move-Item.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 02/26/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/move-item?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Move-Item --- # Move-Item ## SYNOPSIS Moves an item from one location to another. ## SYNTAX ### Path (Default) ``` Move-Item [-Path] <String[]> [[-Destination] <String>] [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-PassThru] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath ``` Move-Item -LiteralPath <String[]> [[-Destination] <String>] [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-PassThru] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Move-Item` cmdlet moves an item, including its properties, contents, and child items, from one location to another location. The locations must be supported by the same provider. For example, it can move a file or subdirectory from one directory to another or move a registry subkey from one key to another. When you move an item, it is added to the new location and deleted from its original location. ## EXAMPLES ### Example 1: Move a file to another directory and rename it This command moves the `Test.txt` file from the `C:` drive to the `E:\Temp` directory and renames it from `test.txt` to `tst.txt`. ```powershell Move-Item -Path C:\test.txt -Destination E:\Temp\tst.txt ``` ### Example 2: Move a directory and its contents to another directory This command moves the `C:\Temp` directory and its contents to the `C:\Logs` directory. The `Temp` directory, and all of its subdirectories and files, then appear in the `Logs` directory. ```powershell Move-Item -Path C:\Temp -Destination C:\Logs ``` ### Example 3: Move all files of a specified extension from the current directory to another directory This command moves all of the text files (`*.txt`) in the current directory (represented by a dot (`.`)) to the `C:\Logs` directory. ```powershell Move-Item -Path .\*.txt -Destination C:\Logs ``` ### Example 4: Recursively move all files of a specified extension from the current directory to another directory This command moves all of the text files from the current directory and all subdirectories, recursively, to the `C:\TextFiles` directory. ```powershell Get-ChildItem -Path ".\*.txt" -Recurse | Move-Item -Destination "C:\TextFiles" ``` The command uses the `Get-ChildItem` cmdlet to get all of the child items in the current directory (represented by the dot (`.`)) and its subdirectories that have a `*.txt` file name extension. It uses the **Recurse** parameter to make the retrieval recursive and the **Include** parameter to limit the retrieval to `*.txt` files. The pipeline operator (`|`) sends the results of this command to `Move-Item`, which moves the text files to the `TextFiles` directory. If files that are to be moved to `C:\Textfiles` have the same name, `Move-Item` displays an error and continues, but it moves only one file with each name to `C:\Textfiles`. The other files remain in their original directories. If the `Textfiles` directory (or any other element of the destination path) does not exist, the command fails. The missing directory is not created for you, even if you use the **Force** parameter. `Move-Item` moves the first item to a file called `Textfiles` and then displays an error explaining that the file already exists. Also, by default, `Get-ChildItem` does not move hidden files. To move hidden files, use the **Force** parameter with `Get-ChildItem`. > [!NOTE] > In Windows PowerShell 2.0, when using the **Recurse** parameter of the `Get-ChildItem` cmdlet, the > value of the **Path** parameter must be a container. Use the **Include** parameter to specify the > `*.txt` file name extension filter > (`Get-ChildItem -Path .\* -Include *.txt -Recurse | Move-Item -Destination C:\TextFiles`). ### Example 5: Move registry keys and values to another key This command moves the registry keys and values within the `MyCompany` registry key in `HKLM\Software` to the `MyNewCompany` key. The wildcard character (`*`) indicates that the contents of the `MyCompany` key should be moved, not the key itself. In this command, the optional **Path** and **Destination** parameter names are omitted. ```powershell Move-Item "HKLM:\software\mycompany\*" "HKLM:\software\mynewcompany" ``` ### Example 6: Move a directory and its contents to a subdirectory of the specified directory This command moves the ``Logs[Sept`06]`` directory (and its contents) into the `Logs[2006]` directory. ```powershell Move-Item -LiteralPath 'Logs[Sept`06]' -Destination 'Logs[2006]' ``` The **LiteralPath** parameter is used instead of **Path**, because the original directory name includes left bracket and right bracket characters (`[` and `]`). The path is also enclosed in single quotation marks (`'`), so that the backtick symbol (`` ` ``) is not misinterpreted. The **Destination** parameter must also be enclosed in single quotation marks because it includes brackets that can be misinterpreted. ## PARAMETERS ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Destination Specifies the path to the location where the items are being moved. The default is the current directory. Wildcards aren't permitted. To rename the item being moved, specify a new name in the value of the **Destination** parameter. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: Current directory Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Forces the command to run without asking for user confirmation. Implementation varies from provider to provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks (`'`). Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Returns an object representing the moved item. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to the current location of the items. The default is the current directory. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: Current directory Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSObject When you use the **PassThru** parameter, this cmdlet returns an object representing the moved item. ## NOTES PowerShell includes the following aliases for `Move-Item`: - All platforms: - `mi` - `move` - Windows: - `mv` - This cmdlet will move files between drives that are supported by the same provider, but it will move directories only within the same drive. - Because a `Move-Item` command moves the properties, contents, and child items of an item, all moves are recursive by default. - This cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Clear-Item](Clear-Item.md) [Copy-Item](Copy-Item.md) [Get-Item](Get-Item.md) [Invoke-Item](Invoke-Item.md) [New-Item](New-Item.md) [Remove-Item](Remove-Item.md) [Rename-Item](Rename-Item.md) [Set-Item](Set-Item.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Move-ItemProperty.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/move-itemproperty?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Move-ItemProperty --- # Move-ItemProperty ## SYNOPSIS Moves a property from one location to another. ## SYNTAX ### Path (Default) ``` Move-ItemProperty [-Path] <String[]> [-Name] <String[]> [-Destination] <String> [-PassThru] [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath ``` Move-ItemProperty -LiteralPath <String[]> [-Name] <String[]> [-Destination] <String> [-PassThru] [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Move-ItemProperty` cmdlet moves a property of an item from one item to another item. For instance, it can move a registry entry from one registry key to another registry key. When you move an item property, it is added to the new location and deleted from its original location. ## EXAMPLES ### Example 1: Move a registry value and its data to another key This command moves the Version registry value, and its data, from the "MyApp" subkey to the NewApp subkey of the `HKLM\Software\MyCompany` registry key. ```powershell Move-ItemProperty "HKLM:\Software\MyCompany\MyApp" -Name "Version" -Destination "HKLM:\Software\MyCompany\NewApp" ``` ## PARAMETERS ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Destination Specifies the path to the destination location. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Forces the command to run without asking for user confirmation. Implementation varies from provider to provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies the name of the property to be moved. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: PSProperty Required: True Position: 2 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to the current location of the property. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSCustomObject When you use the **PassThru** parameter, this cmdlet returns a **PSCustomObject** representing the moved item property. ## NOTES PowerShell includes the following aliases for `Move-ItemProperty`: - All platforms: - `mp` This cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Clear-ItemProperty](Clear-ItemProperty.md) [Copy-ItemProperty](Copy-ItemProperty.md) [Get-ItemProperty](Get-ItemProperty.md) [New-ItemProperty](New-ItemProperty.md) [Remove-ItemProperty](Remove-ItemProperty.md) [Rename-ItemProperty](Rename-ItemProperty.md) [Set-ItemProperty](Set-ItemProperty.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/New-Item.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 02/23/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/new-item?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-Item --- # New-Item ## SYNOPSIS Creates a new item. ## SYNTAX ### pathSet (Default) - All providers ``` New-Item [-Path] <String[]> [-ItemType <String>] [-Value <Object>] [-Force] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### nameSet - All providers ``` New-Item [[-Path] <String[]>] -Name <String> [-ItemType <String>] [-Value <Object>] [-Force] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### pathSet (Default) - WSMan provider ``` New-Item [-Path] <string[]> -ConnectionURI <uri> [-ItemType <string>] [-Value <Object>] [-Force] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-OptionSet <hashtable>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <string>] [-SessionOption <SessionOption>] [-Port <int>] [<CommonParameters>] ``` ### nameSet - WSMan provider ``` New-Item [[-Path] <string[]>] -Name <string> [-ItemType <string>] [-Value <Object>] [-Force] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-OptionSet <hashtable>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <string>] [-SessionOption <SessionOption>] [-ApplicationName <string>] [-Port <int>] [-UseSSL] [<CommonParameters>] ``` ### pathSet (Default) - Alias provider ``` New-Item [-Path] <string[]> [-ItemType <string>] [-Value <Object>] [-Force] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-Options <ScopedItemOptions>] [<CommonParameters>] ``` ### nameSet - Alias provider ``` New-Item [[-Path] <string[]>] -Name <string> [-ItemType <string>] [-Value <Object>] [-Force] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-Options <ScopedItemOptions>] [<CommonParameters>] ``` ## DESCRIPTION The `New-Item` cmdlet creates a new item and sets its value. The types of items that can be created depend on the location of the item. For example, in the file system, `New-Item` creates files and folders. In the registry, `New-Item` creates registry keys and entries. `New-Item` can also set the value of the items that it creates. For example, when it creates a new file, `New-Item` can add initial content to the file. ## EXAMPLES ### Example 1: Create a file in the current directory This command creates a text file that is named "testfile1.txt" in the current directory. The dot ('.') in the value of the **Path** parameter indicates the current directory. The quoted text that follows the **Value** parameter is added to the file as content. ```powershell New-Item -Path . -Name "testfile1.txt" -ItemType "File" -Value "This is a text string." ``` ### Example 2: Create a directory This command creates a directory named "Logfiles" in the `C:` drive. The **ItemType** parameter specifies that the new item is a directory, not a file or other file system object. ```powershell New-Item -Path "C:\" -Name "Logfiles" -ItemType "Directory" ``` ### Example 3: Create a profile This command creates a PowerShell profile in the path that is specified by the `$PROFILE` variable. You can use profiles to customize PowerShell. `$PROFILE` is an automatic (built-in) variable that stores the path and file name of the "CurrentUser/CurrentHost" profile. By default, the profile does not exist, even though PowerShell stores a path and file name for it. In this command, the `$PROFILE` variable represents the path of the file. **ItemType** parameter specifies that the command creates a file. The **Force** parameter lets you create a file in the profile path, even when the directories in the path do not exist. After you create a profile, you can enter aliases, functions, and scripts in the profile to customize your shell. For more information, see [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md) and [about_Profiles](../Microsoft.PowerShell.Core/About/about_Profiles.md). ```powershell New-Item -Path $PROFILE -ItemType "File" -Force ``` ### Example 4: Create a directory in a different directory This example creates a new Scripts directory in the "C:\PS-Test" directory. The name of the new directory item, "Scripts", is included in the value of **Path** parameter, instead of being specified in the value of **Name**. As indicated by the syntax, either command form is valid. ```powershell New-Item -ItemType "Directory" -Path "C:\ps-test\scripts" ``` ### Example 5: Create multiple files This example creates files in two different directories. Because **Path** takes multiple strings, you can use it to create multiple items. ```powershell New-Item -ItemType "File" -Path "C:\ps-test\test.txt", "C:\ps-test\Logs\test.log" ``` ### Example 6: Use wildcards to create files in multiple directories The `New-Item` cmdlet supports wildcards in the **Path** parameter. The following command creates a `temp.txt` file in all of the directories specified by the wildcards in the **Path** parameter. ```powershell Get-ChildItem -Path C:\Temp\ ``` ```Output Directory: C:\Temp Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 5/15/2019 6:45 AM 1 One d----- 5/15/2019 6:45 AM 1 Two d----- 5/15/2019 6:45 AM 1 Three ``` ```powershell New-Item -Path C:\Temp\* -Name temp.txt -ItemType File | Select-Object FullName ``` ```Output FullName -------- C:\Temp\One\temp.txt C:\Temp\Three\temp.txt C:\Temp\Two\temp.txt ``` The `Get-ChildItem` cmdlet shows three directories under the `C:\Temp` directory. Using wildcards the `New-Item` cmdlet creates a `temp.txt` file in all of the directories under the current directory. The `New-Item` cmdlet outputs the items you created, which is piped to `Select-Object` to verify the paths of the newly created files. ### Example 7: Create a symbolic link to a file or folder This example creates a symbolic link to the Notice.txt file in the current folder. ```powershell $link = New-Item -ItemType SymbolicLink -Path .\link -Target .\Notice.txt $link | Select-Object LinkType, Target ``` ```Output LinkType Target -------- ------ SymbolicLink {.\Notice.txt} ``` In this example, **Target** is an alias for the **Value** parameter. The target of the symbolic link can be a relative path. Prior to PowerShell v6.2, the target must be a fully-qualified path. Beginning in PowerShell 7.1, you can now create to a **SymbolicLink** to a folder on Windows using a relative path. ### Example 8: Use the -Force parameter to attempt to recreate folders This example creates a folder with a file inside. Then, attempts to create the same folder using `-Force`. It will not overwrite the folder but simply return the existing folder object with the file created intact. ```powershell PS> New-Item -Path .\TestFolder -ItemType Directory PS> New-Item -Path .\TestFolder\TestFile.txt -ItemType File PS> New-Item -Path .\TestFolder -ItemType Directory -Force Directory: C:\ Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 5/1/2020 8:03 AM TestFolder PS> Get-ChildItem .\TestFolder\ Directory: C:\TestFolder Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 5/1/2020 8:03 AM 0 TestFile.txt ``` ### Example 9: Use the -Force parameter to overwrite existing files This example creates a file with a value and then recreates the file using `-Force`. This overwrites the existing file, as you can see by the **Length** property. ```powershell PS> New-Item ./TestFile.txt -ItemType File -Value 'This is just a test file' Directory: C:\Source\Test Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 5/1/2020 8:32 AM 24 TestFile.txt New-Item ./TestFile.txt -ItemType File -Force Directory: C:\Source\Test Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 5/1/2020 8:32 AM 0 TestFile.txt ``` > [!NOTE] > When using `New-Item` with the `-Force` switch to create registry keys, the command will behave > the same as when overwriting a file. If the registry key already exists, the key and all > properties and values will be overwritten with an empty registry key. ## PARAMETERS ### -ApplicationName This is a dynamic parameter made available by the **WSMan** provider. The **WSMan** provider and this parameter are only available on Windows. Specifies the application name in the connection. The default value of the **ApplicationName** parameter is **WSMAN**. For more information, see [New-WSManInstance](../Microsoft.WSMan.Management/New-WSManInstance.md). ```yaml Type: System.String Parameter Sets: nameSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Authentication This is a dynamic parameter made available by the **WSMan** provider. The **WSMan** provider and this parameter are only available on Windows. Specifies the authentication mechanism to be used at the server. For more information, see [New-WSManInstance](../Microsoft.WSMan.Management/New-WSManInstance.md). ```yaml Type: Microsoft.WSMan.Management.AuthenticationMechanism Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint This is a dynamic parameter made available by the **WSMan** provider. The **WSMan** provider and this parameter are only available on Windows. Specifies the digital public key certificate (X509) of a user account that has permission to perform this WSMan action. Enter the certificate thumbprint of the certificate. For more information, see [New-WSManInstance](../Microsoft.WSMan.Management/New-WSManInstance.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ConnectionURI This is a dynamic parameter made available by the **WSMan** provider. The **WSMan** provider and this parameter are only available on Windows. Specifies the connection endpoint for WSMan. For more information, see [New-WSManInstance](../Microsoft.WSMan.Management/New-WSManInstance.md). ```yaml Type: System.Uri Parameter Sets: pathSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential > [!NOTE] > This parameter isn't supported by any providers installed with PowerShell. To impersonate another > user or elevate your credentials when running this cmdlet, use `Invoke-Command`. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Force Forces this cmdlet to create an item that writes over an existing read-only item. Implementation varies from provider to provider. Even using the **Force** parameter, the cmdlet can't override security restrictions. Beginning in PowerShell 7.4, this parameter also allows you to overwrite an existing Junction. Previously, this would fail with a "cannot be removed because it is not empty" error. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ItemType Specifies the provider-specified type of the new item. The available values of this parameter depend on the current provider you are using. If your location is in a `FileSystem` drive, the following values are allowed: - `File` - `Directory` - `SymbolicLink` - `Junction` - `HardLink` > [!NOTE] > Creating a `SymbolicLink` type on Windows requires elevation as administrator. However, Windows 10 > (build 14972 or newer) with Developer Mode enabled no longer requires elevation creating symbolic > links. In a `Certificate` drive, these are the values you can specify: - `Certificate Provider` - `Certificate` - `Store` - `StoreLocation` For more information see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Type Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies the name of the new item. You can specify the name of the new item in the **Name** or **Path** parameter value, and you can specify the path of the new item in **Name** or **Path** value. Items names passed using the **Name** parameter are created relative to the value of the **Path** parameter. ```yaml Type: System.String Parameter Sets: nameSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Options This is a dynamic parameter made available by the **Alias** provider. For more information, see [New-Alias](../Microsoft.PowerShell.Utility/New-Alias.md). Specifies the value of the **Options** property of an alias. Valid values are: - `None`: The alias has no constraints (default value) - `ReadOnly`: The alias can be deleted but can't be changed without using the **Force** parameter - `Constant`: The alias can't be deleted or changed - `Private`: The alias is available only in the current scope - `AllScope`: The alias is copied to any new scopes that are created - `Unspecified`: The option isn't specified ```yaml Type: System.Management.Automation.ScopedItemOptions Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OptionSet This is a dynamic parameter made available by the **WSMan** provider. The **WSMan** provider and this parameter are only available on Windows. Passes a set of switches to a service to modify or refine the nature of the request. For more information, see [New-WSManInstance](../Microsoft.WSMan.Management/New-WSManInstance.md). ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: OS Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path of the location of the new item. The default is the current location when **Path** is omitted. You can specify the name of the new item in **Name**, or include it in **Path**. Items names passed using the **Name** parameter are created relative to the value of the **Path** parameter. For this cmdlet, the **Path** parameter works like the **LiteralPath** parameter of other cmdlets. Wildcard characters are not interpreted. All characters are passed to the location's provider. The provider may not support all characters. For example, you can't create a filename that contains an asterisk (`*`) character. ```yaml Type: System.String[] Parameter Sets: pathSet, nameSet Aliases: Required: True (pathSet), False (nameSet) Position: 0 Default value: Current location Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Port This is a dynamic parameter made available by the **WSMan** provider. The **WSMan** provider and this parameter are only available on Windows. Specifies the port to use when the client connects to the WinRM service. For more information, see [New-WSManInstance](../Microsoft.WSMan.Management/New-WSManInstance.md). ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SessionOption This is a dynamic parameter made available by the **WSMan** provider. The **WSMan** provider and this parameter are only available on Windows. Defines a set of extended options for the WS-Management session. For more information, see [New-WSManInstance](../Microsoft.WSMan.Management/New-WSManInstance.md). ```yaml Type: Microsoft.WSMan.Management.SessionOption Parameter Sets: (All) Aliases: SO Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL This is a dynamic parameter made available by the **WSMan** provider. The **WSMan** provider and this parameter are only available on Windows. Specifies that the Secure Sockets Layer (SSL) protocol should be used to establish a connection to the remote computer. By default, SSL isn't used. For more information, see [New-WSManInstance](../Microsoft.WSMan.Management/New-WSManInstance.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: nameSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Value Specifies the value of the new item. You can also pipe a value to `New-Item`. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Target Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.Object You can pipe a value for the new item to this cmdlet. ## OUTPUTS ### System.Collections.DictionaryEntry The cmdlet returns a **DictionaryEntry** object when creating a new environment variable. ### System.IO.DirectoryInfo The cmdlet returns a **DirectoryInfo** object when creating a new directory in the filesystem. ### System.IO.FileInfo The cmdlet returns a **FileInfo** object when creating a new file in the filesystem. ### System.Management.Automation.AliasInfo The cmdlet returns an **AliasInfo** object when creating a new alias. ### System.Management.Automation.FunctionInfo The cmdlet returns a **FunctionInfo** object when creating a new function. ### System.Management.Automation.PSVariable The cmdlet returns a **PSVariable** object when creating a new variable. ## NOTES PowerShell includes the following aliases for `New-Item`: - All platforms: - `ni` `New-Item` is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Clear-Item](Clear-Item.md) [Copy-Item](Copy-Item.md) [Get-Item](Get-Item.md) [Invoke-Item](Invoke-Item.md) [Move-Item](Move-Item.md) [Remove-Item](Remove-Item.md) [Rename-Item](Rename-Item.md) [Set-Item](Set-Item.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/New-ItemProperty.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/new-itemproperty?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-ItemProperty --- # New-ItemProperty ## SYNOPSIS Creates a new property for an item and sets its value. ## SYNTAX ### Path (Default) ``` New-ItemProperty [-Path] <String[]> [-Name] <String> [-PropertyType <String>] [-Value <Object>] [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath ``` New-ItemProperty -LiteralPath <String[]> [-Name] <String> [-PropertyType <String>] [-Value <Object>] [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `New-ItemProperty` cmdlet creates a new property for a specified item and sets its value. Typically, this cmdlet is used to create new registry values, because registry values are properties of a registry key item. This cmdlet does not add properties to an object. - To add a property to an instance of an object, use the `Add-Member` cmdlet. - To add a property to all objects of a particular type, modify the Types.ps1xml file. ## EXAMPLES ### Example 1: Add a registry entry This command adds a new registry entry, `NoOfEmployees`, to the `MyCompany` key of the `HKLM:\Software hive`. The first command uses the **Path** parameter to specify the path of the `MyCompany` registry key. It uses the **Name** parameter to specify a name for the entry and the **Value** parameter to specify its value. The second command uses the `Get-ItemProperty` cmdlet to see the new registry entry. ```powershell New-ItemProperty -Path "HKLM:\Software\MyCompany" -Name "NoOfEmployees" -Value 822 Get-ItemProperty "HKLM:\Software\MyCompany" ``` ```output PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\mycompany PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software PSChildName : mycompany PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry NoOfLocations : 2 NoOfEmployees : 822 ``` ### Example 2: Add a registry entry to a key This command adds a new registry entry to a registry key. To specify the key, it uses a pipeline operator (`|`) to send an object that represents the key to `New-ItemProperty`. The first part of the command uses the `Get-Item` cmdlet to get the `MyCompany` registry key. The pipeline operator sends the results of the command to `New-ItemProperty`, which adds the new registry entry (`NoOfLocations`), and its value (`3`), to the `MyCompany` key. ```powershell Get-Item -Path "HKLM:\Software\MyCompany" | New-ItemProperty -Name NoOfLocations -Value 3 ``` This command works because the parameter-binding feature of PowerShell associates the path of the **RegistryKey** object that `Get-Item` returns with the **LiteralPath** parameter of `New-ItemProperty`. For more information, see [about_Pipelines](../Microsoft.PowerShell.Core/About/about_pipelines.md). ### Example 3: Create a MultiString value in the registry using a Here-String This example creates a `MultiString` value using a Here-String. ```powershell $newValue = New-ItemProperty -Path "HKLM:\SOFTWARE\ContosoCompany\" -Name 'HereString' -PropertyType MultiString -Value @" This is text which contains newlines It can also contain "quoted" strings "@ $newValue.HereString ``` ```output This is text which contains newlines It can also contain "quoted" strings ``` ### Example 4: Create a MultiString value in the registry using an array The example shows how to use an array of values to create the `MultiString` value. ```powershell $newValue = New-ItemProperty -Path "HKLM:\SOFTWARE\ContosoCompany\" -Name 'MultiString' -PropertyType MultiString -Value ('a','b','c') $newValue.MultiString[0] ``` ```output a ``` ## PARAMETERS ### -Credential Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as `User01` or `Domain01\User01`, or enter a **PSCredential** object, such as one generated by the `Get-Credential` cmdlet. If you type a user name, you are prompted for a password. > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Forces the cmdlet to create a property on an object that cannot otherwise be accessed by the user. Implementation varies from provider to provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks (`'`). Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies a name for the new property. If the property is a registry entry, this parameter specifies the name of the entry. ```yaml Type: System.String Parameter Sets: (All) Aliases: PSProperty Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the path of the item. Wildcard characters are permitted. This parameter identifies the item to which this cmdlet adds the new property. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -PropertyType Specifies the type of property that this cmdlet adds. The acceptable values for this parameter are: - `String`: Specifies a null-terminated string. Used for **REG_SZ** values. - `ExpandString`: Specifies a null-terminated string that contains unexpanded references to environment variables that are expanded when the value is retrieved. Used for **REG_EXPAND_SZ** values. - `Binary`: Specifies binary data in any form. Used for **REG_BINARY** values. - `DWord`: Specifies a 32-bit binary number. Used for **REG_DWORD** values. - `MultiString`: Specifies an array of null-terminated strings terminated by two null characters. Used for **REG_MULTI_SZ** values. - `Qword`: Specifies a 64-bit binary number. Used for **REG_QWORD** values. - `Unknown`: Indicates an unsupported registry data type, such as **REG_RESOURCE_LIST** values. ```yaml Type: System.String Parameter Sets: (All) Aliases: Type Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Value Specifies the property value. If the property is a registry entry, this parameter specifies the value of the entry. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSCustomObject This cmdlet returns a custom object representing the new property. ## NOTES `New-ItemProperty` is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Clear-ItemProperty](Clear-ItemProperty.md) [Copy-ItemProperty](Copy-ItemProperty.md) [Get-ItemProperty](Get-ItemProperty.md) [Move-ItemProperty](Move-ItemProperty.md) [Remove-ItemProperty](Remove-ItemProperty.md) [Rename-ItemProperty](Rename-ItemProperty.md) [Set-ItemProperty](Set-ItemProperty.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/New-PSDrive.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 01/18/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/new-psdrive?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-PSDrive --- # New-PSDrive ## SYNOPSIS Creates temporary and persistent drives that are associated with a location in an item data store. ## SYNTAX ### All ``` New-PSDrive [-Name] <String> [-PSProvider] <String> [-Root] <String> [-Description <String>] [-Scope <String>] [-Persist] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `New-PSDrive` cmdlet creates temporary and persistent drives that are mapped to or associated with a location in a data store, such as a network drive, a directory on the local computer, or a registry key, and persistent Windows mapped network drives that are associated with a file system location on a remote computer. Temporary drives exist only in the current PowerShell session and in sessions that you create in the current session. They can have any name that is valid in PowerShell and can be mapped to any local or remote resource. You can use temporary PowerShell drives to access data in the associated data store, just as you would do with any mapped network drive. You can change locations into the drive, by using `Set-Location`, and access the contents of the drive by using `Get-Item` or `Get-ChildItem`. Because temporary drives are known only to PowerShell, you can't access them by using File Explorer, Windows Management Instrumentation (WMI), Component Object Model (COM), Microsoft .NET Framework, or with tools such as `net use`. The following features were added to `New-PSDrive` in PowerShell 3.0: - Mapped network drives. You can use the **Persist** parameter of `New-PSDrive` to create Windows mapped network drives. Unlike temporary PowerShell drives, Windows mapped network drives aren't session-specific. They're saved in Windows and they can be managed by using standard Windows tools, such as File Explorer and **net use**. Mapped network drives must have a drive-letter name and be connected to a remote file system location. When your command is scoped locally, no dot-sourcing, the **Persist** parameter doesn't persist the creation of a **PSDrive** beyond the scope in which the command is running. If you're running `New-PSDrive` inside a script, and you want the drive to persist indefinitely, you must dot-source the script. For best results, to force a new drive to persist indefinitely, add the **Scope** parameter to your command, and set its value to **Global**. For more information about dot-sourcing, see [about_Scripts](../Microsoft.PowerShell.Core/About/about_Scripts.md#script-scope-and-dot-sourcing). - External drives. When an external drive is connected to the computer, PowerShell automatically adds a **PSDrive** to the file system that represents the new drive. You don't have to restart PowerShell. Similarly, when an external drive is disconnected from the computer, PowerShell automatically deletes the **PSDrive** that represents the removed drive. - Credentials for Universal Naming Convention (UNC) paths. When the value of the **Root** parameter is a UNC path, such as `\\Server\Share`, the credential specified in the value of the **Credential** parameter is used to create the **PSDrive**. Otherwise, **Credential** isn't effective when you're creating new file system drives. Some code samples use splatting to reduce the line length and improve readability. For more information, see [about_Splatting](../Microsoft.PowerShell.Core/About/about_Splatting.md). > [!NOTE] > Unless you use the **Scope** parameter, PSDrives are created in the scope in which the > `New-PSDrive` command is run. ## EXAMPLES ### Example 1: Create a temporary drive mapped to a network share This example creates a temporary PowerShell drive that's mapped to a network share. ```powershell New-PSDrive -Name "Public" -PSProvider "FileSystem" -Root "\\Server01\Public" ``` ```Output Name Provider Root ---- -------- ---- Public FileSystem \\Server01\Public ``` `New-PSDrive` uses the **Name** parameter to specify PowerShell drive named `Public` and the **PSProvider** parameter to specify the PowerShell `FileSystem` provider. The **Root** parameter specifies the network share's UNC path. To view the contents from a PowerShell session: `Get-ChildItem -Path Public:` ### Example 2: Create a temporary drive mapped to a local directory This example creates a temporary PowerShell drive that provides access to a directory on the local computer. ```powershell $parameters = @{ Name = "MyDocs" PSProvider = "FileSystem" Root = "C:\Users\User01\Documents" Description = "Maps to my My Documents folder." } New-PSDrive @parameters ``` ```Output Name Provider Root ---- -------- ---- MyDocs FileSystem C:\Users\User01\Documents ``` Splatting creates the parameter keys and values. The **Name** parameter specifies the drive name, **MyDocs**. The **PSProvider** parameter specifies the PowerShell `FileSystem` provider. **Root** specifies the local computer's directory. The **Description** parameter describes the drive's purpose. `New-PSDrive` uses the splatted parameters to create the `MyDocs` drive. To view the contents from a PowerShell session: `Get-ChildItem -Path MyDocs:` ### Example 3: Create a temporary drive for a registry key This example creates a temporary PowerShell drive that provides access to a registry key. It creates a drive named MyCompany that is mapped to the `HKLM:\Software\MyCompany` registry key. ```powershell New-PSDrive -Name "MyCompany" -PSProvider "Registry" -Root "HKLM:\Software\MyCompany" ``` ```Output Name Provider Root ---- -------- ---- MyCompany Registry HKLM:\Software\MyCompany ``` `New-PSDrive` uses the **Name** parameter to specify PowerShell drive named `MyCompany` and the **PSProvider** parameter to specify the PowerShell `Registry` provider. The **Root** parameter specifies the registry location. To view the contents from a PowerShell session: `Get-ChildItem -Path MyCompany:` ### Example 4: Create a persistent mapped network drive using credentials This example maps a network drive that's authenticated with a domain service account's credentials. For more information about the **PSCredential** object that stores credentials and how passwords are stored as a **SecureString**, see the **Credential** parameter's description. ```powershell $cred = Get-Credential -Credential Contoso\ServiceAccount New-PSDrive -Name "S" -Root "\\Server01\Scripts" -Persist -PSProvider "FileSystem" -Credential $cred Net Use ``` ```Output Status Local Remote Network --------------------------------------------------------- OK S: \\Server01\Scripts Microsoft Windows Network ``` > [!NOTE] > Remember, if you use the above snippet in a script, set the **Scope** parameter value to > "Global" to ensure the drive persists outside the current scope. The `$cred` variable stores a **PSCredential** object that contains the service account's credentials. `Get-Credential` prompts you to enter the password that's stored in a **SecureString**. `New-PSDrive` creates the mapped network drive by using several parameters. **Name** specifies the `S` drive letter that Windows accepts. and **Root** defines `\\Server01\Scripts` as the location on a remote computer. **Persist** creates a Windows mapped network drive that's saved on the local computer. **PSProvider** specifies the `FileSystem` provider. **Credential** uses the `$cred` variable to get the service account credentials for authentication. The mapped drive can be viewed on the local computer in PowerShell sessions, File Explorer, and with tools such as **net use**. To view the contents from a PowerShell session: `Get-ChildItem -Path S:` ### Example 5: Create persistent and temporary drives This example shows the difference between a persistent mapped network drive and a temporary PowerShell drive that is mapped to the same network share. If you close the PowerShell session and then open a new session, the temporary `PSDrive:` isn't available, but the persistent `X:` drive is available. When deciding which method to use to map network drives, consider how you'll use the drive. For example, whether it has to be persistent, and whether the drive has to be visible to other Windows features. ```powershell # Create a temporary PowerShell drive called PSDrive: # that's mapped to the \\Server01\Public network share. New-PSDrive -Name "PSDrive" -PSProvider "FileSystem" -Root "\\Server01\Public" # Use the Persist parameter of New-PSDrive to create the X: mapped network drive, # which is also mapped to the \\Server01\Public network share. New-PSDrive -Persist -Name "X" -PSProvider "FileSystem" -Root "\\Server01\Public" # Now, you can use the Get-PSDrive drive cmdlet to examine the two drives. # The drives appear to be the same, although the network share name appears only # in the root of the PSDrive: drive. Get-PSDrive -Name "PSDrive", "X" ``` ```Output Name Provider Root ---- -------- ---- PSDrive FileSystem \\Server01\public X FileSystem X:\ ``` ```powershell # Get-Member cmdlet shows that the drives have the same object type, # System.Management.Automation.PSDriveInfo. Get-PSDrive "PSDrive", "x" | Get-Member ``` ```Output TypeName: System.Management.Automation.PSDriveInfo Name MemberType Definition ---- ---------- ---------- CompareTo Method System.Int32 CompareTo(PSDriveInfo drive), Equals Method System.Boolean Equals(Object obj), GetHashCode Method System.Int32 GetHashCode() ... ``` ```powershell # Net Use and Get-CimInstance for the Win32_LogicalDisk class, # and Win32_NetworkConnection class find only the persistent X: drive. # PowerShell temporary drives are known only to PowerShell. Net Use Get-CimInstance Win32_LogicalDisk | Format-Table -Property DeviceID Get-CimInstance Win32_NetworkConnection ``` ```Output Status Local Remote Network -------------------------------------------------------- OK X: \\contoso-pc\data Microsoft Windows Network deviceid -------- C: D: X: LocalName RemoteName ConnectionState Status --------- ---------- --------------- ------ X: \\products\public Disconnected Unavailable ``` ### Example 6: Create persistent drive in a script PSDrives are created in the scope in which the `New-PSDrive` command is run. When the command is run within a script, the drive mapping is local to the script. When the script exits, the drive is no longer available. ```powershell New-PSDrive -Persist -Name "X" -PSProvider "FileSystem" -Root "\\Server01\Public" -Scope Global ``` To ensure that the drive is available outside of the script you must use the **Scope** parameter to create the drive in the **Global** scope. ## PARAMETERS ### -Credential Specifies a user account that has permission to do this action. The default is the current user. Since PowerShell 3.0, when the value of the **Root** parameter is a UNC path, you can use credentials to create file system drives. Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. If you type a user name, you're prompted to enter the password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Description Specifies a brief text description of the drive. Type any string. To see the descriptions of all the session's drives, `Get-PSDrive | Format-Table Name, Description`. To see the description of a particular drive, type `(Get-PSDrive <DriveName>).Description`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies a name for the new drive. For persistent mapped network drives, use a drive letter. For temporary PowerShell drives, you aren't limited to drive letters, use any valid string. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Persist Indicates that this cmdlet creates a Windows mapped network drive. The **Persist** parameter is only available on Windows. Mapped network drives are saved in Windows on the local computer. They're persistent, not session-specific, and can be viewed and managed in File Explorer and other tools. When you scope the command locally, without dot-sourcing, the **Persist** parameter doesn't persist the creation of a **PSDrive** beyond the scope in which you run the command. If you run `New-PSDrive` inside a script, and you want the new drive to persist indefinitely, you must dot-source the script. For best results, to force a new drive to persist, specify **Global** as the value of the **Scope** parameter and include **Persist** in your command. The name of the drive must be a letter, such as `D` or `E`. The value of **Root** parameter must be a UNC path of a different computer. The **PSProvider** parameter's value must be `FileSystem`. To disconnect a Windows mapped network drive, use the `Remove-PSDrive` cmdlet. When you disconnect a Windows mapped network drive, the mapping is permanently deleted from the computer, not just deleted from the current session. Mapped network drives are specific to a user account. Mapped drives created in elevated sessions or sessions using the credential of another user aren't visible in sessions started using different credentials. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PSProvider Specifies the PowerShell provider that supports drives of this kind. For example, if the drive is associated with a network share or file system directory, the PowerShell provider is `FileSystem`. If the drive is associated with a registry key, the provider is `Registry`. Temporary PowerShell drives can be associated with any PowerShell provider. Mapped network drives can be associated only with the `FileSystem` provider. To see a list of the providers in your PowerShell session, use the `Get-PSProvider` cmdlet. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Root Specifies the data store location to which a PowerShell drive is mapped. For example, specify a network share, such as `\\Server01\Public`, a local directory, such as `C:\Program Files`, or a registry key, such as `HKLM:\Software\Microsoft`. Temporary PowerShell drives can be associated with a local or remote location on any supported provider drive. Mapped network drives can be associated only with a file system location on a remote computer. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 2 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Scope Specifies a scope for the drive. The acceptable values for this parameter are: **Global**, **Local**, and **Script**, or a number relative to the current scope. Scopes number 0 through the number of scopes. The current scope number is 0 and its parent is 1. For more information, see [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Local Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet ## OUTPUTS ### System.Management.Automation.PSDriveInfo This cmdlet returns a **PSDriveInfo** object representing the created drive. ## NOTES PowerShell includes the following aliases for `Get-PSDrive`: - All platforms: - `ndr` - Windows: - `mount` `New-PSDrive` is designed to work with the data exposed by any provider. To list the providers available in your session, use `Get-PSProvider`. For more information about providers, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). Mapped network drives are specific to a user account. Mapped drives created in elevated sessions or sessions using the credential of another user aren't visible in sessions started using different credentials. ## RELATED LINKS [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md) [Get-Credential](../Microsoft.PowerShell.Security/Get-Credential.md) [Get-PSDrive](Get-PSDrive.md) [Remove-PSDrive](Remove-PSDrive.md)

#File: reference/7.6/Microsoft.PowerShell.Management/New-Service.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/new-service?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-Service --- # New-Service ## SYNOPSIS Creates a new Windows service. ## SYNTAX ``` New-Service [-Name] <String> [-BinaryPathName] <String> [-DisplayName <String>] [-Description <String>] [-SecurityDescriptorSddl <String>] [-StartupType <ServiceStartupType>] [-Credential <PSCredential>] [-DependsOn <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `New-Service` cmdlet creates a new entry for a Windows service in the registry and in the service database. A new service requires an executable file that runs during the service. The parameters of this cmdlet let you set the display name, description, startup type, and dependencies of the service. ## EXAMPLES ### Example 1: Create a service ```powershell New-Service -Name "TestService" -BinaryPathName 'C:\WINDOWS\System32\svchost.exe -k netsvcs' ``` This command creates a service named TestService. ### Example 2: Create a service that includes description, startup type, and display name ```powershell $params = @{ Name = "TestService" BinaryPathName = 'C:\WINDOWS\System32\svchost.exe -k netsvcs' DependsOn = "NetLogon" DisplayName = "Test Service" StartupType = "Manual" Description = "This is a test service." } New-Service @params ``` This command creates a service named TestService. It uses the parameters of `New-Service` to specify a description, startup type, and display name for the new service. ### Example 3: View the new service ```powershell Get-CimInstance -ClassName Win32_Service -Filter "Name='testservice'" ``` ```Output ExitCode : 0 Name : testservice ProcessId : 0 StartMode : Auto State : Stopped Status : OK ``` This command uses `Get-CimInstance` to get the **Win32_Service** object for the new service. This object includes the start mode and the service description. ### Example 4: Set the SecurityDescriptor of a service when creating. This example adds the **SecurityDescriptor** of the service being created. ```powershell $SDDL = "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;SU)" $params = @{ BinaryPathName = 'C:\WINDOWS\System32\svchost.exe -k netsvcs' DependsOn = "NetLogon" DisplayName = "Test Service" StartupType = "Manual" Description = "This is a test service." SecurityDescriptorSddl = $SDDL } New-Service @params ``` The **SecurityDescriptor** is stored in the `$SDDLToSet` variable. The **SecurityDescriptorSddl** parameter uses `$SDDL` to set the **SecurityDescriptor** of the new service. ## PARAMETERS ### -BinaryPathName Specifies the path of the executable file for the service. This parameter is required. The fully qualified path to the service binary file. If the path contains a space, it must be quoted so that it is correctly interpreted. For example, `D:\my share\myservice.exe` should be specified as `'"D:\my share\myservice.exe"'`. The path can also include arguments for an auto-start service. For example, `'"D:\my share\myservice.exe" arg1 arg2'`. These arguments are passed to the service entry point. For more information, see the **lpBinaryPathName** parameter of [CreateServiceW](/windows/win32/api/winsvc/nf-winsvc-createservicew) API. ```yaml Type: System.String Parameter Sets: (All) Aliases: Path Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential Specifies the account used by the service as the [Service Logon Account](/windows/desktop/ad/about-service-logon-accounts). Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object, such as one generated by the `Get-Credential` cmdlet. If you type a user name, this cmdlet prompts you for a password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DependsOn Specifies the names of other services upon which the new service depends. To enter multiple service names, use a comma to separate the names. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Description Specifies a description of the service. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DisplayName Specifies a display name for the service. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies the name of the service. This parameter is required. ```yaml Type: System.String Parameter Sets: (All) Aliases: ServiceName Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SecurityDescriptorSddl Specifies the **SecurityDescriptor** for the service in **Sddl** format. ```yaml Type: System.String Parameter Sets: (All) Aliases: sd Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -StartupType Sets the startup type of the service. The acceptable values for this parameter are: - **Automatic** - The service is started or was started by the operating system, at system start-up. If an automatically started service depends on a manually started service, the manually started service is also started automatically at system startup. - **AutomaticDelayedStart** - Starts shortly after the system boots. - **Disabled** - The service is disabled and cannot be started by a user or application. - **InvalidValue** - This value is not supported. Using this value results in an error. - **Manual** - The service is started only manually, by a user, using the Service Control Manager, or by an application. The default value is **Automatic**. ```yaml Type: Microsoft.PowerShell.Commands.ServiceStartupType Parameter Sets: (All) Aliases: Accepted values: Automatic, Manual, Disabled, AutomaticDelayedStart, InvalidValue Required: False Position: Named Default value: Automatic Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.ServiceProcess.ServiceController This cmdlet returns an object representing the new service. ## NOTES This cmdlet is only available on Windows platforms. To run this cmdlet, start PowerShell by using the **Run as administrator** option. ## RELATED LINKS [Get-Service](Get-Service.md) [Restart-Service](Restart-Service.md) [Resume-Service](Resume-Service.md) [Set-Service](Set-Service.md) [Start-Service](Start-Service.md) [Stop-Service](Stop-Service.md) [Suspend-Service](Suspend-Service.md) [Remove-Service](Remove-Service.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Pop-Location.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/pop-location?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Pop-Location --- # Pop-Location ## SYNOPSIS Changes the current location to the location most recently pushed onto the stack. ## SYNTAX ``` Pop-Location [-PassThru] [-StackName <String>] [<CommonParameters>] ``` ## DESCRIPTION The `Pop-Location` cmdlet changes the current location to the location most recently pushed onto the stack by using the `Push-Location` cmdlet. You can pop a location from the default stack or from a stack that you create by using a `Push-Location` command. ## EXAMPLES ### Example 1: Change to most recent location ``` PS C:\> Pop-Location ``` This command changes your location to the location most recently added to the current stack. ### Example 2: Change to most recent location in a named stack ``` PS C:\> Pop-Location -StackName "Stack2" ``` This command changes your location to the location most recently added to the Stack2 location stack. For more information about location stacks, see the [Notes](#notes). ### Example 3: Move between locations for different providers ``` PS C:\> pushd HKLM:\Software\Microsoft\PowerShell PS HKLM:\Software\Microsoft\PowerShell> pushd Cert:\LocalMachine\TrustedPublisher PS Cert:\LocalMachine\TrustedPublisher> popd PS HKLM:\Software\Microsoft\PowerShell> popd PS C:\> ``` These commands use the `Push-Location` and `Pop-Location` cmdlets to move between locations supported by different PowerShell providers. The commands use the `pushd` alias for `Push-Location` and the `popd` alias for `Pop-Location`. The first command pushes the current file system location onto the stack and moves to the HKLM drive supported by the PowerShell Registry provider. The second command pushes the registry location onto the stack and moves to a location supported by the PowerShell Certificate provider. The last two commands pop those locations off the stack. The first `popd` command returns to the Registry drive, and the second command returns to the file system drive. ## PARAMETERS ### -PassThru Passes an object that represents the location to the pipeline. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -StackName Specifies the location stack from which the location is popped. Enter a location stack name. Without this parameter, `Pop-Location` pops a location from the current location stack. By default, the current location stack is the unnamed default location stack that PowerShell creates. To make a location stack the current location stack, use the **StackName** parameter of the `Set-Location` cmdlet. For more information about location stacks, see the [Notes](#notes). `Pop-Location` cannot pop a location from the unnamed default stack unless it is the current location stack. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PathInfo When you use the **PassThru** parameter, this cmdlet returns a **PathInfo** object representing the current path after the cmdlet's operation. ## NOTES PowerShell includes the following aliases for `Pop-Location`: - All Platforms: - `popd` PowerShell supports multiple runspaces per process. Each runspace has its own _current directory_. This is not the same as `[System.Environment]::CurrentDirectory`. This behavior can be an issue when calling .NET APIs or running native applications without providing explicit directory paths. Even if the location cmdlets did set the process-wide current directory, you can't depend on it because another runspace might change it at any time. You should use the location cmdlets to perform path-based operations using the current working directory specific to the current runspace. A stack is a last-in, first-out list in which only the most recently added item can be accessed. You add items to a stack in the order that you use them, and then retrieve them for use in the reverse order. PowerShell lets you store provider locations in location stacks. PowerShell creates an unnamed default location stack and you can create multiple named location stacks. If you do not specify a stack name, PowerShell uses the current location stack. By default, the unnamed default location is the current location stack, but you can use the `Set-Location` cmdlet to change the current location stack. To manage location stacks, use the PowerShell `*-Location` cmdlets, as follows: - To add a location to a location stack, use the `Push-Location` cmdlet. - To get a location from a location stack, use the `Pop-Location` cmdlet. - To display the locations in the current location stack, use the **Stack** parameter of the `Get-Location` cmdlet. - To display the locations in a named location stack, use the **StackName** parameter of the `Get-Location` cmdlet. - To create a new location stack, use the **StackName** parameter of the `Push-Location` cmdlet. If you specify a stack that does not exist, `Push-Location` creates the stack. - To make a location stack the current location stack, use the **StackName** parameter of the `Set-Location` cmdlet. The unnamed default location stack is fully accessible only when it is the current location stack. If you make a named location stack the current location stack, you can no longer use the `Push-Location` or `Pop-Location` cmdlets to add or get items from the default stack or use the `Get-Location` cmdlet to display the locations in the unnamed stack. To make the unnamed stack the current stack, use the **StackName** parameter of the `Set-Location` cmdlet with a value of `$null` or an empty string (`""`). You can also refer to `Pop-Location` by its built-in alias, `popd`. For more information, see [about_Aliases](../Microsoft.PowerShell.Core/About/about_Aliases.md). `Pop-Location` is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Get-Location](Get-Location.md) [Push-Location](Push-Location.md) [Set-Location](Set-Location.md) [about_Aliases](../Microsoft.PowerShell.Core/About/about_Aliases.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Push-Location.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/push-location?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Push-Location --- # Push-Location ## SYNOPSIS Adds the current location to the top of a location stack. ## SYNTAX ### Path (Default) ``` Push-Location [[-Path] <String>] [-PassThru] [-StackName <String>] [<CommonParameters>] ``` ### LiteralPath ``` Push-Location [-LiteralPath <String>] [-PassThru] [-StackName <String>] [<CommonParameters>] ``` ## DESCRIPTION The `Push-Location` cmdlet adds ("pushes") the current location onto a location stack. If you specify a path, `Push-Location` pushes the current location onto a location stack and then changes the current location to the location specified by the path. You can use the `Pop-Location` cmdlet to get locations from the location stack. By default, the `Push-Location` cmdlet pushes the current location onto the current location stack, but you can use the **StackName** parameter to specify an alternate location stack. If the stack does not exist, `Push-Location` creates it. For more information about location stacks, see the [Notes](#notes). ## EXAMPLES ### Example 1 This example pushes the current location onto the default location stack and then changes the location to `C:\Windows`. ``` PS C:\> Push-Location C:\Windows ``` ### Example 2 This example pushes the current location onto the RegFunction stack and changes the current location to the `HKLM:\Software\Policies` location. ``` PS C:\> Push-Location HKLM:\Software\Policies -StackName RegFunction ``` You can use the Location cmdlets in any PowerShell drive (PSDrive). ### Example 3 This command pushes the current location onto the default stack. It does not change the location. ``` PS C:\> Push-Location ``` ### Example 4 - Create and use a named stack These commands show how to create and use a named location stack. ``` PS C:\> Push-Location ~ -StackName Stack2 PS C:\Users\User01> Pop-Location -StackName Stack2 PS C:\> ``` The first command pushes the current location onto a new stack named Stack2, and then changes the current location to the home directory, represented in the command by the tilde symbol (`~`), which when used on a FileSystem provider drives is equivalent to `$HOME`. If Stack2 does not already exist in the session, `Push-Location` creates it. The second command uses the `Pop-Location` cmdlet to pop the original location (`C:\`) from the Stack2 stack. Without the **StackName** parameter, `Pop-Location` would pop the location from the unnamed default stack. For more information about location stacks, see the [Notes](#notes). ## PARAMETERS ### -LiteralPath Specifies the path to the new location. Unlike the **Path** parameter, the value of the **LiteralPath** parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String Parameter Sets: LiteralPath Aliases: PSPath, LP Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Passes an object representing the location to the pipeline. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Changes your location to the location specified by this path after it adds (pushes) the current location onto the top of the stack. Enter a path to any location whose provider supports this cmdlet. Wildcards are permitted. The parameter name is optional. ```yaml Type: System.String Parameter Sets: Path Aliases: Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -StackName Specifies the location stack to which the current location is added. Enter a location stack name. If the stack does not exist, `Push-Location` creates it. Without this parameter, `Push-Location` adds the location to the current location stack. By default, the current location stack is the unnamed default location stack that PowerShell creates. To make a location stack the current location stack, use the **StackName** parameter of the `Set-Location` cmdlet. For more information about location stacks, see the [Notes](#notes). > [!NOTE] > `Push-Location` cannot add a location to the unnamed default stack unless it is the current > location stack. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Default stack Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a path (but not a literal path) to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PathInfo When you use the **PassThru** parameter, this cmdlet returns a **PathInfo** object representing the current path after the cmdlet's operation. ## NOTES PowerShell includes the following aliases for `Push-Location`: - All Platforms: - `pushd` PowerShell supports multiple runspaces per process. Each runspace has its own _current directory_. This is not the same as `[System.Environment]::CurrentDirectory`. This behavior can be an issue when calling .NET APIs or running native applications without providing explicit directory paths. Even if the location cmdlets did set the process-wide current directory, you can't depend on it because another runspace might change it at any time. You should use the location cmdlets to perform path-based operations using the current working directory specific to the current runspace. A stack is a last-in, first-out list in which only the most recently added item is accessible. You add items to a stack in the order that you use them, and then retrieve them for use in the reverse order. PowerShell lets you store provider locations in location stacks. PowerShell creates an unnamed default location stack and you can create multiple named location stacks. If you do not specify a stack name, PowerShell uses the current location stack. By default, the unnamed default location is the current location stack, but you can use the `Set-Location` cmdlet to change the current location stack. To manage location stacks, use the PowerShell Location cmdlets, as follows. - To add a location to a location stack, use the `Push-Location` cmdlet. - To get a location from a location stack, use the `Pop-Location` cmdlet. - To display the locations in the current location stack, use the **Stack** parameter of the `Get-Location` cmdlet. - To display the locations in a named location stack, use the **StackName** parameter of the `Get-Location` cmdlet. - To create a new location stack, use the StackName parameter of the `Push-Location` cmdlet. If you specify a stack that does not exist, `Push-Location` creates the stack. - To make a location stack the current location stack, use the StackName parameter of the `Set-Location` cmdlet. The unnamed default location stack is fully accessible only when it is the current location stack. If you make a named location stack the current location stack, you can no longer use the `Push-Location` or `Pop-Location` cmdlets to add or get items from the default stack or use the `Get-Location` cmdlet to display the locations in the unnamed stack. To make the unnamed stack the current stack, use the **StackName** parameter of the `Set-Location` cmdlet with a value of `$null` or an empty string (`""`). You can also refer to `Push-Location` by its built-in alias, `pushd`. For more information, see [about_Aliases](../Microsoft.PowerShell.Core/About/about_Aliases.md). The `Push-Location` cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Get-Location](Get-Location.md) [Pop-Location](Pop-Location.md) [Set-Location](Set-Location.md) [about_Aliases](../Microsoft.PowerShell.Core/About/about_Aliases.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Remove-Item.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 02/14/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/remove-item?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-Item --- # Remove-Item ## SYNOPSIS Deletes the specified items. ## SYNTAX ### Path (Default) - FileSystem provider ``` Remove-Item [-Path] <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Recurse] [-Force] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [-Stream <String[]>] [<CommonParameters>] ``` ### LiteralPath - FileSystem provider ``` Remove-Item -LiteralPath <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Recurse] [-Force] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [-Stream <String[]>] [<CommonParameters>] ``` ### Path (Default) - Certificate provider ``` Remove-Item [-Path] <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Recurse] [-Force] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [-DeleteKey] [<CommonParameters>] ``` ### LiteralPath - Certificate provider ``` Remove-Item -LiteralPath <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Recurse] [-Force] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [-DeleteKey] [<CommonParameters>] ``` ### Path (Default) - All providers ``` Remove-Item [-Path] <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-Force] [-Credential <pscredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath - All providers ``` Remove-Item -LiteralPath <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Recurse] [-Force] [-Credential <pscredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Remove-Item` cmdlet deletes one or more items. Because it's supported by many providers, it can delete many different types of items, including files, folders, registry keys, variables, aliases, and functions. ## EXAMPLES ### Example 1: Delete files that have any file extension This example deletes all files with names that include a dot (`.`) from the `C:\Test` folder. Because the command specifies a dot, the command doesn't delete folders or files that have no file extension. ```powershell Remove-Item C:\Test\*.* ``` ### Example 2: Delete document files in a folder This example deletes from the current folder all files that have a `.doc` file extension and a name that doesn't include `*1*`. ```powershell Remove-Item * -Include *.doc -Exclude *1* ``` It uses the wildcard character (`*`) to specify the contents of the current folder. It uses the **Include** and **Exclude** parameters to specify the files to delete. ### Example 3: Delete hidden, read-only files This command deletes a file that's both _hidden_ and _read-only_. ```powershell Remove-Item -Path C:\Test\hidden-RO-file.txt -Force ``` It uses the **Path** parameter to specify the file. It uses the **Force** parameter to delete it. Without **Force**, you can't delete _read-only_ or _hidden_ files. ### Example 4: Delete files in subfolders recursively This command deletes all the CSV files in the current folder and all subfolders recursively. Because the **Recurse** parameter in `Remove-Item` has a known issue, the command in this example uses `Get-ChildItem` to get the desired files, and then uses the pipeline operator to pass them to `Remove-Item`. ```powershell Get-ChildItem * -Include *.csv -Recurse | Remove-Item ``` In the `Get-ChildItem` command, **Path** has a value of (`*`), which represents the contents of the current folder. It uses **Include** to specify the CSV file type, and it uses **Recurse** to make the retrieval recursive. If you try to specify the file type in the path, such as `-Path *.csv`, the cmdlet interprets the subject of the search to be a file that has no child items, and **Recurse** fails. > [!NOTE] > This behavior was fixed in Windows versions 1909 and up. ### Example 5: Delete subkeys recursively This command deletes the "OldApp" registry key and all its subkeys and values. It uses `Remove-Item` to remove the key. The path is specified, but the optional parameter name (**Path**) is omitted. The **Recurse** parameter deletes all of the contents of the "OldApp" key recursively. If the key contains subkeys and you omit the **Recurse** parameter, you are prompted to confirm that you want to delete the contents of the key. ```powershell Remove-Item HKLM:\Software\MyCompany\OldApp -Recurse ``` ### Example 6: Deleting files with special characters The following example shows how to delete files that contain special characters like brackets or parentheses. ```powershell Get-ChildItem ``` ```Output Directory: C:\temp\Downloads Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 6/1/2018 12:19 PM 1362 myFile.txt -a--- 6/1/2018 12:30 PM 1132 myFile[1].txt -a--- 6/1/2018 12:19 PM 1283 myFile[2].txt -a--- 6/1/2018 12:19 PM 1432 myFile[3].txt ``` ```powershell Get-ChildItem | Where-Object Name -Like '*`[*' ``` ```Output Directory: C:\temp\Downloads Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 6/1/2018 12:30 PM 1132 myFile[1].txt -a--- 6/1/2018 12:19 PM 1283 myFile[2].txt -a--- 6/1/2018 12:19 PM 1432 myFile[3].txt ``` ```powershell Get-ChildItem | Where-Object Name -Like '*`[*' | ForEach-Object { Remove-Item -LiteralPath $_.Name } Get-ChildItem ``` ```Output Directory: C:\temp\Downloads Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 6/1/2018 12:19 PM 1362 myFile.txt ``` ### Example 7: Remove an alternate data stream This example shows how to use the **Stream** dynamic parameter of the `Remove-Item` cmdlet to delete an alternate data stream. The stream parameter is introduced in Windows PowerShell 3.0. ```powershell Get-Item C:\Test\Copy-Script.ps1 -Stream Zone.Identifier ``` ```Output FileName: \\C:\Test\Copy-Script.ps1 Stream Length ------ ------ Zone.Identifier 26 ``` ```powershell Remove-Item C:\Test\Copy-Script.ps1 -Stream Zone.Identifier Get-Item C:\Test\Copy-Script.ps1 -Stream Zone.Identifier ``` ```Output Get-Item : Could not open alternate data stream 'Zone.Identifier' of file 'C:\Test\Copy-Script.ps1'. ``` The **Stream** parameter `Get-Item` gets the `Zone.Identifier` stream of the `Copy-Script.ps1` file. `Remove-Item` uses the **Stream** parameter to remove the `Zone.Identifier` stream of the file. Finally, the `Get-Item` cmdlet shows that the `Zone.Identifier` stream was deleted. ## PARAMETERS ### -Credential > [!NOTE] > This parameter isn't supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -DeleteKey This is a dynamic parameter made available by the **Certificate** provider. The **Certificate** provider and this parameter are only available on Windows platforms. When provided, the cmdlet deletes the private key when the certificate is deleted. For more information, see [about_Certificate_Provider](../Microsoft.PowerShell.Security/About/about_Certificate_Provider.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. When using **Recurse** with **Exclude**, **Exclude** only filters results of the current directory. If there are files that match the **Exclude** pattern in subfolders, those files are removed along with its parent directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they're retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Forces the cmdlet to remove items that can't otherwise be changed, such as hidden or read-only files or read-only aliases or variables. The cmdlet can't remove constant aliases or variables. Implementation varies from provider to provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). Even using the **Force** parameter, the cmdlet can't override security restrictions. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies a path of the items being removed. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Recurse Indicates that this cmdlet deletes the items in the specified locations and in all child items of the locations. The **Recurse** parameter might not delete all subfolders or all child items. This is a known issue. > [!NOTE] > This behavior was fixed in Windows versions 1909 and newer. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Stream This is a dynamic parameter made available by the **FileSystem** provider. This parameter is only available on Windows. This parameter can't be used in combination with the **Recurse** parameter. You can use `Remove-Item` to delete an alternative data stream, such as `Zone.Identifier`. However, it isn't the recommended way to eliminate security checks that block files that are downloaded from the Internet. If you verify that a downloaded file is safe, use the `Unblock-File` cmdlet. This parameter was introduced in Windows PowerShell 3.0. As of Windows PowerShell 7.2, `Remove-Item` can remove alternative data streams from directories as well as files. For more information, see [about_FileSystem_Provider](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md). ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. For more information, see the following articles: - [about_Preference_Variables](../microsoft.powershell.core/about/about_preference_variables.md#confirmpreference) - [about_Functions_CmdletBindingAttribute](../microsoft.powershell.core/about/about_functions_cmdletbindingattribute.md?#confirmimpact) ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a path, but not a literal path, to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Remove-Item`: - All platforms: - `del` - `erase` - `rd` - `ri` - Windows: - `rm` - `rmdir` The `Remove-Item` cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). When you try to delete a folder that contains items without using the **Recurse** parameter, the cmdlet prompts for confirmation. Using `-Confirm:$false` doesn't suppress the prompt. This is by design. ## RELATED LINKS [Clear-Item](Clear-Item.md) [Copy-Item](Copy-Item.md) [Get-Item](Get-Item.md) [Invoke-Item](Invoke-Item.md) [Move-Item](Move-Item.md) [New-Item](New-Item.md) [Remove-ItemProperty](Remove-ItemProperty.md) [Rename-Item](Rename-Item.md) [Set-Item](Set-Item.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md) [about_Preference_Variables](../microsoft.powershell.core/about/about_preference_variables.md#confirmpreference) [about_Functions_CmdletBindingAttribute](../microsoft.powershell.core/about/about_functions_cmdletbindingattribute.md?#confirmimpact)

#File: reference/7.6/Microsoft.PowerShell.Management/Remove-ItemProperty.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/remove-itemproperty?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-ItemProperty --- # Remove-ItemProperty ## SYNOPSIS Deletes the property and its value from an item. ## SYNTAX ### Path (Default) ``` Remove-ItemProperty [-Path] <String[]> [-Name] <String[]> [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-InformationAction <ActionPreference>] [-InformationVariable <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath ``` Remove-ItemProperty -LiteralPath <String[]> [-Name] <String[]> [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Remove-ItemProperty` cmdlet deletes a property and its value from an item. You can use it to delete registry values and the data that they store. ## EXAMPLES ### Example 1: Delete a registry value This command deletes the "SmpProperty" registry value, and its data, from the "SmpApplication" subkey of the `HKEY_LOCAL_MACHINE\Software` registry key. ```powershell Remove-ItemProperty -Path "HKLM:\Software\SmpApplication" -Name "SmpProperty" ``` Because the command is issued from a file system drive (`PS C:\>`), it includes the fully qualified path of the "SmpApplication" subkey, including the drive, `HKLM:`, and the "Software" key. ### Example 2: Delete a registry value from the HKCU location These commands delete the "Options" registry value, and its data, from the "MyApp" subkey of "HKEY_CURRENT_USER\Software\MyCompany". ``` PS C:\> Set-Location HKCU:\Software\MyCompany\MyApp PS HKCU:\Software\MyCompany\MyApp> Remove-ItemProperty -Path . -Name "Options" -Confirm ``` The first command uses the `Set-Location` cmdlet to change the current location to the **HKEY_CURRENT_USER** drive (`HKCU:`) and the `Software\MyCompany\MyApp` subkey. The second command uses `Remove-ItemProperty` to remove the "Options" registry value, and its data, from the "MyApp" subkey. Because **Path** is required, the command uses a dot (`.`) to indicate the current location. The **Confirm** parameter requests a user prompt before deleting the value. ### Example 3: Remove a registry value by using the pipeline This command deletes the "NoOfEmployees" registry value, and its data, from the `HKLM\Software\MyCompany` registry key. ```powershell Get-Item -Path HKLM:\Software\MyCompany | Remove-ItemProperty -Name NoOfEmployees ``` The command uses the `Get-Item` cmdlet to get an item that represents the registry key. It uses a pipeline operator (`|`) to send the object to `Remove-ItemProperty`. Then, it uses the **Name** parameter of `Remove-ItemProperty` to specify the name of the registry value. ## PARAMETERS ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Forces the cmdlet to remove a property of an object that cannot otherwise be accessed by the user. Implementation varies from provider to provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies the names of the properties to remove. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: PSProperty Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Path Specifies the path of the item whose properties are being removed. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string that contains a path, but not a literal path, to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Remove-ItemProperty`: - All platforms: - `rp` - In the PowerShell Registry provider, registry values are considered to be properties of a registry key or subkey. You can use the **ItemProperty** cmdlets to manage these values. - `Remove-ItemProperty` is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Get-Item](Get-Item.md) [Clear-ItemProperty](Clear-ItemProperty.md) [Copy-ItemProperty](Copy-ItemProperty.md) [Get-ItemProperty](Get-ItemProperty.md) [Move-ItemProperty](Move-ItemProperty.md) [New-ItemProperty](New-ItemProperty.md) [Remove-Item](Remove-Item.md) [Rename-ItemProperty](Rename-ItemProperty.md) [Set-ItemProperty](Set-ItemProperty.md) [Set-Location](Set-Location.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Remove-PSDrive.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 01/18/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/remove-psdrive?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-PSDrive --- # Remove-PSDrive ## SYNOPSIS Deletes temporary PowerShell drives and disconnects mapped network drives. ## SYNTAX ### Name (Default) ``` Remove-PSDrive [-Name] <String[]> [-PSProvider <String[]>] [-Scope <String>] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralName ``` Remove-PSDrive [-LiteralName] <String[]> [-PSProvider <String[]>] [-Scope <String>] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Remove-PSDrive` cmdlet deletes temporary PowerShell drives that were created by using the `New-PSDrive` cmdlet. Beginning in Windows PowerShell 3.0, `Remove-PSDrive` also disconnects mapped network drives, including, but not limited to, drives created by using the **Persist** parameter of `New-PSDrive`. `Remove-PSDrive` cannot delete Windows physical or logical drives. Beginning in Windows PowerShell 3.0, when an external drive is connected to the computer, PowerShell automatically adds a PSDrive to the file system that represents the new drive. You do not need to restart PowerShell. Similarly, when an external drive is disconnected from the computer, PowerShell automatically deletes the PSDrive that represents the removed drive. ## EXAMPLES ### Example 1: Remove a file system drive This command removes a temporary file system drive named `smp`. ```powershell Remove-PSDrive -Name smp ``` ### Example 2: Remove mapped network drives This command uses `Remove-PSDrive` to disconnect the `X:` and `S:` mapped network drives. ```powershell Get-PSDrive X, S | Remove-PSDrive ``` ## PARAMETERS ### -Force Removes the current PowerShell drive. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralName Specifies the name of the drive. The value of **LiteralName** is used exactly as typed. No characters are interpreted as wildcards. If the name includes escape characters, enclose it in single quotation marks (`'`). Single quotation marks instruct PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: LiteralName Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies the names of the drives to remove. Do not type a colon (`:`) after the drive name. ```yaml Type: System.String[] Parameter Sets: Name Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -PSProvider Specifies an array of **PSProvider** objects. This cmdlet removes and disconnects all of the drives associated with the specified PowerShell provider. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Scope Specifies a scope for the drive. The acceptable values for this parameter are: `Global`, `Local`, and `Script`, or a number relative to the current scope. Scopes number `0` through the number of scopes. The current scope number is `0` and its parent is `1`. For more information, see [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Local Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.Management.Automation.PSDriveInfo You can pipe a drive object, such as from the `Get-PSDrive` cmdlet, to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Remove-PSDrive`: - All platforms: - `rdr` - The `Remove-PSDrive` cmdlet is designed to work with the data exposed by any PowerShell provider. To list the providers in your session, use the `Get-PSProvider` cmdlet. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Get-PSDrive](Get-PSDrive.md) [New-PSDrive](New-PSDrive.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Remove-Service.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/remove-service?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-Service --- # Remove-Service ## SYNOPSIS Removes a Windows service. ## SYNTAX ### Name (Default) ``` Remove-Service [-Name] <String> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### InputObject ``` Remove-Service [-InputObject <ServiceController>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Remove-Service` cmdlet removes a Windows service in the registry and in the service database. The `Remove-Service` cmdlet was introduced in PowerShell 6.0. ## EXAMPLES ### Example 1: Remove a service This removes a service named TestService. ```powershell Remove-Service -Name "TestService" ``` ### Example 2: Remove a service using the display name This example removes a service named TestService. The command uses `Get-Service` to get an object that represents the TestService service using the display name. The pipeline operator (`|`) pipes the object to `Remove-Service`, which removes the service. ```powershell Get-Service -DisplayName "Test Service" | Remove-Service ``` ## PARAMETERS ### -InputObject Specifies **ServiceController** objects that represent the services to remove. Enter a variable that contains the objects, or type a command or expression that gets the objects. The **InputObject** parameter doesn't enumerate collections. If a collection is passed, an error is thrown. When working with collections, pipe the input to enumerate the values. ```yaml Type: System.ServiceProcess.ServiceController Parameter Sets: InputObject Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies the service names of the services to remove. Wildcard characters are permitted. ```yaml Type: System.String Parameter Sets: Name Aliases: ServiceName, SN Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.ServiceProcess.ServiceController You can pipe a service object to this cmdlet. ### System.String You can pipe a string that contains the name of a service to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES This cmdlet is only available on Windows platforms. To run this cmdlet, start PowerShell by using the **Run as administrator** option. ## RELATED LINKS [Get-Service](Get-Service.md) [Restart-Service](Restart-Service.md) [Resume-Service](Resume-Service.md) [Set-Service](Set-Service.md) [Start-Service](Start-Service.md) [Stop-Service](Stop-Service.md) [Suspend-Service](Suspend-Service.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Rename-Computer.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/rename-computer?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Rename-Computer --- # Rename-Computer ## SYNOPSIS Renames a computer. ## SYNTAX ``` Rename-Computer [-ComputerName <String>] [-PassThru] [-DomainCredential <PSCredential>] [-LocalCredential <PSCredential>] [-NewName] <String> [-Force] [-Restart] [-WsmanAuthentication <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Rename-Computer` cmdlet renames the local computer or a remote computer. It renames one computer in each command. This cmdlet was introduced in Windows PowerShell 3.0. ## EXAMPLES ### Example 1: Rename the local computer This command renames the local computer to `Server044` and then restarts it to make the change effective. ```powershell Rename-Computer -NewName "Server044" -DomainCredential Domain01\Admin01 -Restart ``` ### Example 2: Rename a remote computer This command renames the `Srv01` computer to `Server001`. The computer is not restarted. The **DomainCredential** parameter specifies the credentials of a user who has permission to rename computers in the domain. The **Force** parameter suppresses the confirmation prompt. ```powershell Rename-Computer -ComputerName "Srv01" -NewName "Server001" -DomainCredential Domain01\Admin01 -Force ``` ## PARAMETERS ### -ComputerName Renames the specified remote computer. The default is the local computer. Type the NetBIOS name, an IP address, or a fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot (`.`), or `localhost`. This parameter does not rely on PowerShell remoting. You can use the **ComputerName** parameter of `Rename-Computer` even if your computer is not configured to run remote commands. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Local Computer Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -DomainCredential Specifies a user account that has permission to connect to the domain. Explicit credentials are required to rename a computer that is joined to a domain. Type a user name, such as `User01` or `Domain01\User01`, or enter a **PSCredential** object, such as one generated by the `Get-Credential` cmdlet. If you type a user name, this cmdlet prompts you for a password. To specify a user account that has permission to connect to the computer that is specified by the **ComputerName** parameter, use the **LocalCredential** parameter. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Forces the command to run without asking for user confirmation. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LocalCredential Specifies a user account that has permission to connect to the computer specified by the **ComputerName** parameter. The default is the current user. Type a user name, such as `User01` or `Domain01\User01`, or enter a **PSCredential** object, such as one generated by the `Get-Credential` cmdlet. If you type a user name, this cmdlet prompts you for a password. To specify a user account that has permission to connect to the domain, use the **DomainCredential** parameter. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current User Accept pipeline input: False Accept wildcard characters: False ``` ### -NewName Specifies a new name for the computer. This parameter is required. 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 ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Returns the results of the command. Otherwise, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Restart Indicates that this cmdlet restarts the computer that was renamed. A restart is often required to make the change effective. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WsmanAuthentication Specifies the mechanism that is used to authenticate the user credentials when this cmdlet uses the WSMan protocol. The acceptable values for this parameter are: - **Basic** - **CredSSP** - **Default** - **Digest** - **Kerberos** - **Negotiate** The default value is **Default**. For more information about the values of this parameter, see [AuthenticationMechanism Enumeration](/dotnet/api/system.management.automation.runspaces.authenticationmechanism). > [!WARNING] > Credential Security Service Provider (CredSSP) authentication, in which the user > credentials are passed to a remote computer to be authenticated, is designed for commands that > require authentication on more than one resource, such as accessing a remote network share. > This mechanism increases the security risk of the remote operation. > If the remote computer is compromised, the credentials that are passed to it can be used to > control > the network session. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: Default, Basic, Negotiate, CredSSP, Digest, Kerberos Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### None This cmdlet has no parameters that take input by value. However, you can pipe the values of the **ComputerName** and **NewName** properties of objects to this cmdlet. ## OUTPUTS ### None By default, this cmdlet doesn't return any output. ### Microsoft.PowerShell.Commands.RenameComputerChangeInfo When you use the **PassThru** parameter, this cmdlet returns a **RenameComputerChangeInfo** object. ## NOTES This cmdlet is only available on Windows platforms. ## RELATED LINKS [Restart-Computer](Restart-Computer.md) [Stop-Computer](Stop-Computer.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Rename-Item.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/rename-item?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Rename-Item --- # Rename-Item ## SYNOPSIS Renames an item in a PowerShell provider namespace. ## SYNTAX ### ByPath (Default) ``` Rename-Item [-Path] <String> [-NewName] <String> [-Force] [-PassThru] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ByLiteralPath ``` Rename-Item -LiteralPath <String> [-NewName] <String> [-Force] [-PassThru] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Rename-Item` cmdlet changes the name of a specified item. This cmdlet does not affect the content of the item being renamed. You can't use `Rename-Item` to move an item, such as by specifying a path together with the new name. To move and rename an item, use the `Move-Item` cmdlet. ## EXAMPLES ### Example 1: Rename a file This command renames the file `daily_file.txt` to `monday_file.txt`. ```powershell Rename-Item -Path "C:\logfiles\daily_file.txt" -NewName "monday_file.txt" ``` ### Example 2: Rename and move an item You can't use `Rename-Item` to both rename and move an item. Specifically, you can't supply a path for the value of the **NewName** parameter, unless the path is identical to the path specified in the **Path** parameter. Otherwise, only a new name is permitted. ```powershell Rename-Item -Path "project.txt" -NewName "D:\archive\old-project.txt" ``` ```Output Rename-Item : can't rename because the target specified represents a path or device name. At line:1 char:12 + Rename-Item <<<< -Path project.txt -NewName D:\archive\old-project.txt + CategoryInfo : InvalidArgument: (:) [Rename-Item], PS> Move-Item -Path "project.txt" -De stination "D:\archive\old-project.txt" ``` This example attempts to rename the `project.txt` file in the current directory to `old-project.txt` in the `D:\Archive` directory. The result is the error shown in the output. Use the `Move-Item` cmdlet, instead. ### Example 3: Rename a registry key This example renames a registry key from **Advertising** to **Marketing**. When the command is complete, the key is renamed, but the registry entries in the key are unchanged. ```powershell Rename-Item -Path "HKLM:\Software\MyCompany\Advertising" -NewName "Marketing" ``` ### Example 4: Rename multiple files This example renames all the `*.txt` files in the current directory to `*.log`. ```powershell Get-ChildItem *.txt ``` ```Output Directory: C:\temp\files Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 10/3/2019 7:47 AM 2918 Friday.TXT -a---- 10/3/2019 7:46 AM 2918 Monday.Txt -a---- 10/3/2019 7:47 AM 2918 Wednesday.txt ``` ```powershell Get-ChildItem *.txt | Rename-Item -NewName { $_.Name -replace '.txt','.log' } Get-ChildItem *.log ``` ```Output Directory: C:\temp\files Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 10/3/2019 7:47 AM 2918 Friday.log -a---- 10/3/2019 7:46 AM 2918 Monday.log -a---- 10/3/2019 7:47 AM 2918 Wednesday.log ``` The `Get-ChildItem` cmdlet gets all the files in the current folder that have a `.txt` file extension then pipes them to `Rename-Item`. The value of **NewName** is a script block that runs before the value is submitted to the **NewName** parameter. In the script block, the `$_` automatic variable represents each file object as it comes to the command through the pipeline. The script block uses the `-replace` operator to replace the file extension of each file with `.log`. Notice that matching using the `-replace` operator is not case sensitive. ## PARAMETERS ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. To impersonate another > user, or elevate your credentials when running this cmdlet, use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Force Forces the cmdlet to rename items that can't otherwise be changed, such as hidden or read-only files or read-only aliases or variables. The cmdlet can't change constant aliases or variables. Implementation varies from provider to provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). Even using the **Force** parameter, the cmdlet can't override security restrictions. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String Parameter Sets: ByLiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -NewName Specifies the new name of the item. Enter only a name, not a path and name. If you enter a path that differs from the path that is specified in the **Path** parameter, `Rename-Item` generates an error. To rename and move an item, use `Move-Item`. You can't use wildcard characters in the value of the **NewName** parameter. To specify a name for multiple files, use the `-replace` operator in a regular expression. For more information about the `-replace` operator, see [about_Comparison_Operators](../Microsoft.PowerShell.Core/About/about_Comparison_Operators.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Returns an object that represents the item to the pipeline. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path of the item to rename. ```yaml Type: System.String Parameter Sets: ByPath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSObject When you use the **PassThru** parameter, this cmdlet returns an object representing the renamed item. ## NOTES PowerShell includes the following aliases for `Rename-Item`: - All platforms: - `ren` - `rni` `Rename-Item` is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Clear-Item](Clear-Item.md) [Copy-Item](Copy-Item.md) [Get-ChildItem](Get-ChildItem.md) [Get-Item](Get-Item.md) [Invoke-Item](Invoke-Item.md) [Move-Item](Move-Item.md) [New-Item](New-Item.md) [Remove-Item](Remove-Item.md) [Rename-ItemProperty](Rename-ItemProperty.md) [Set-Item](Set-Item.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Rename-ItemProperty.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 02/07/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/rename-itemproperty?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Rename-ItemProperty --- # Rename-ItemProperty ## SYNOPSIS Renames a property of an item. ## SYNTAX ### Path (Default) ``` Rename-ItemProperty [-Path] <String> [-Name] <String> [-NewName] <String> [-PassThru] [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath ``` Rename-ItemProperty -LiteralPath <String> [-Name] <String> [-NewName] <String> [-PassThru] [-Force] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Rename-ItemProperty` cmdlet changes the name of a specified item property. The value of the property is not changed. For example, you can use `Rename-ItemProperty` to change the name of a registry entry. ## EXAMPLES ### Example 1: Rename a registry entry This command renames the config registry entry that is contained in the `HKEY_LOCAL_MACHINE\Software\SmpApplication` key to "oldconfig". ```powershell Rename-ItemProperty -Path HKLM:\Software\SmpApplication -Name config -NewName oldconfig ``` ## PARAMETERS ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Forces the cmdlet to rename a property of an object that cannot otherwise be accessed by the user. Implementation varies from provider to provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to the item. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies the current name of the property to rename. ```yaml Type: System.String Parameter Sets: (All) Aliases: PSProperty Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -NewName Specifies the new name for the property. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 2 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Returns an object that represents the item property. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies a path to the item. Wildcard characters are permitted. ```yaml Type: System.String Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string that contains a path, but not a literal path, to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSCustomObject When you use the **PassThru** parameter, this cmdlet returns a **PSCustomObject** representing the renamed item property. ## NOTES PowerShell includes the following aliases for `Rename-ItemProperty`: - All platforms: - `rnp` `Rename-ItemProperty` is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Clear-ItemProperty](Clear-ItemProperty.md) [Copy-ItemProperty](Copy-ItemProperty.md) [Get-ItemProperty](Get-ItemProperty.md) [Move-ItemProperty](Move-ItemProperty.md) [New-ItemProperty](New-ItemProperty.md) [Remove-ItemProperty](Remove-ItemProperty.md) [Rename-Item](Rename-Item.md) [Set-ItemProperty](Set-ItemProperty.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Resolve-Path.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 09/25/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/resolve-path?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Resolve-Path --- # Resolve-Path ## SYNOPSIS Resolves the wildcard characters in a path, and displays the path contents. ## SYNTAX ### Path (Default) ``` Resolve-Path [-Path] <string[]> [-Relative] [-RelativeBasePath <string>] [-Credential <pscredential>] [-Force] [<CommonParameters>] ``` ### LiteralPath ``` Resolve-Path -LiteralPath <string[]> [-Relative] [-RelativeBasePath <string>] [-Credential <pscredential>] [-Force] [<CommonParameters>] ``` ## DESCRIPTION The `Resolve-Path` cmdlet displays the items and containers that match the wildcard pattern at the location specified. The match can include files, folders, registry keys, or any other object accessible from a **PSDrive** provider. ## EXAMPLES ### Example 1: Resolve the home folder path The tilde character (`~`) is shorthand notation for the current user's home folder. This example shows `Resolve-Path` returning the fully qualified path value. ```powershell Resolve-Path ~ ``` ```Output Path ---- C:\Users\User01 ``` ### Example 2: Resolve the path of the Windows folder ```powershell Resolve-Path -Path "windows" ``` ```Output Path ---- C:\Windows ``` When run from the root of the `C:` drive, this command returns the path of the `Windows` folder in the `C:` drive. ### Example 3: Get all paths in the Windows folder ```powershell "C:\windows\*" | Resolve-Path ``` This command returns all the files and folders in the `C:\Windows` folder. The command uses a pipeline operator (`|`) to send a path string to `Resolve-Path`. ### Example 4: Resolve a UNC path ```powershell Resolve-Path -Path "\\Server01\public" ``` This command resolves a Universal Naming Convention (UNC) path and returns the shares in the path. ### Example 5: Get relative paths ```powershell Resolve-Path -Path "C:\prog*" -Relative ``` ```Output .\Program Files .\Program Files (x86) .\programs.txt ``` This command returns relative paths for the directories at the root of the `C:` drive. ### Example 6: Resolve a path containing brackets This example uses the **LiteralPath** parameter to resolve the path of the `Test[xml]` subfolder. Using **LiteralPath** causes the brackets to be treated as normal characters rather than a regular expression. ```powershell Resolve-Path -LiteralPath 'test[xml]' ``` ### Example 7: Resolve a path relative to another folder This example uses the **RelativeBasePath** parameter to resolve the path of the `pwsh` executable relative to `$Env:TEMP`. When the command includes the **Relative** switch parameter, it returns a **String** representing the relative path from `$Env:TEMP` to the `pwsh` executable. ```powershell $ExecutablePath = Get-Command -Name pwsh | Select-Object -ExpandProperty Source Resolve-Path -Path $ExecutablePath -RelativeBasePath $Env:TEMP -Relative ``` ```Output ..\..\..\..\..\Program Files\PowerShell\7\pwsh.exe ``` ### Example 8: Resolve paths for hidden items By default, `Resolve-Path` does not return hidden items. This example uses the **Force** parameter to resolve hidden items. The `Get-Item` command confirms that the `.git` folder is hidden. Using `Resolve-Path` without the **Force** parameter returns only the visible items. Adding the **Force** parameter returns all items, including hidden items. ```powershell PS> Get-Item .git -Force Directory: D:\Git\PS-Docs\PowerShell-Docs Mode LastWriteTime Length Name ---- ------------- ------ ---- d--h- 9/25/2024 4:46 PM .git PS> Resolve-Path .git* Path ---- D:\Git\PS-Docs\PowerShell-Docs\.github D:\Git\PS-Docs\PowerShell-Docs\.gitattributes D:\Git\PS-Docs\PowerShell-Docs\.gitignore PS> Resolve-Path .git* -Force Path ---- D:\Git\PS-Docs\PowerShell-Docs\.git D:\Git\PS-Docs\PowerShell-Docs\.github D:\Git\PS-Docs\PowerShell-Docs\.gitattributes D:\Git\PS-Docs\PowerShell-Docs\.gitignore ``` ## PARAMETERS ### -Credential Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as `User01` or `Domain01\User01`, or pass a **PSCredential** object. You can create a **PSCredential** object using the `Get-Credential` cmdlet. If you type a user name, this cmdlet prompts you for a password. This parameter is not supported by any providers installed with PowerShell. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Accepted values: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Force Allows the cmdlet to get items that otherwise can't be accessed by the user, such as hidden or system files. The **Force** parameter doesn't override security restrictions. Implementation varies among providers. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). This parameter was added in PowerShell 7.5-preview.5. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to be resolved. The value of the **LiteralPath** parameter is used exactly as typed. No characters are interpreted as wildcard characters. If the path includes escape characters, enclose it in single quotation marks (`'`). Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Accepted values: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the PowerShell path to resolve. This parameter is required. You can also pipe a path string to `Resolve-Path`. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Accepted values: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Relative Indicates that this cmdlet returns a relative path. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Path, LiteralPath Aliases: Accepted values: Required: True (None) False (Path, LiteralPath) Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -RelativeBasePath Specifies a path to resolve the relative path from. When you use this parameter, the cmdlet returns the **System.Management.Automation.PathInfo** object for the resolved path. When you use this parameter with the **Relative** switch parameter, the cmdlet returns a string representing the relative path from **RelativeBasePath** to **Path**. This parameter was added in PowerShell 7.4. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### System.Management.Automation.PathInfo By default, this cmdlet returns a **PathInfo** object. ### System.String If you specify the **Relative** parameter, this cmdlet returns a string value for the resolved path. ## NOTES PowerShell includes the following aliases for `Resolve-Path`: - All platforms: - `rvpa` The `*-Path` cmdlets work with the **FileSystem**, **Registry**, and **Certificate** providers. `Resolve-Path` is designed to work with any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../microsoft.powershell.core/about/about_providers.md). `Resolve-Path` only resolves existing paths. It cannot be used to resolve a location that does not exist yet. ## RELATED LINKS [Convert-Path](Convert-Path.md) [Join-Path](Join-Path.md) [Split-Path](Split-Path.md) [Test-Path](Test-Path.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Restart-Computer.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/restart-computer?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Restart-Computer --- # Restart-Computer ## SYNOPSIS Restarts the operating system on local and remote computers. ## SYNTAX ### DefaultSet (Default) ``` Restart-Computer [-WsmanAuthentication <String>] [[-ComputerName] <String[]>] [[-Credential]<PSCredential>] [-Force] [-Wait] [-Timeout <Int32>] [-For <WaitForServiceTypes>] [-Delay <Int16>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Restart-Computer` cmdlet restarts the operating system on the local and remote computers. You can use the parameters of `Restart-Computer` to run the restart operations, to specify the authentication levels and alternate credentials, to limit the operations that run at the same time, and to force an immediate restart. Starting in Windows PowerShell 3.0, you can wait for the restart to complete before you run the next command. Specify a waiting time-out and query interval, and wait for particular services to be available on the restarted computer. This feature makes it practical to use `Restart-Computer` in scripts and functions. In PowerShell 7.1, `Restart-Computer` was added for Linux and macOS. The non-Windows platforms only have the **WhatIf**, **Confirm**, and **CommonParameters** parameters. The cmdlet is just calling the native command `/sbin/shutdown`. ## EXAMPLES ## EXAMPLES ### Example 1: Restart the local computer `Restart-Computer` restarts the local computer. ```powershell Restart-Computer ``` ### Example 2: Restart multiple computers `Restart-Computer` can restart remote and local computers. The **ComputerName** parameter accepts an array of computer names. ```powershell Restart-Computer -ComputerName Server01, Server02, localhost ``` ### Example 3: Get computer names from a text file `Restart-Computer` gets a list of computer names from a text file and restarts the computers. The **ComputerName** parameter isn't specified. But because it's the first position parameter, it accepts the computer names from the text file that are sent down the pipeline. ```powershell Get-Content -Path C:\Domain01.txt | Restart-Computer ``` `Get-Content` uses the **Path** parameter to get a list of computer names from a text file, **Domain01.txt**. The computer names are sent down the pipeline. `Restart-Computer` restarts each computer. ### Example 4: Force restart of computers listed in a text file This example forces an immediate restart of the computers listed in the `Domain01.txt` file. The computer names from the text file are stored in a variable. The **Force** parameter forces an immediate restart. ```powershell $Names = Get-Content -Path C:\Domain01.txt $Creds = Get-Credential Restart-Computer -ComputerName $Names -Credential $Creds -Force ``` `Get-Content` uses the **Path** parameter to get a list of computer names from a text file, **Domain01.txt**. The computer names are stored in the variable `$Names`. `Get-Credential` prompts you for a username and password and stores the values in the variable `$Creds`. `Restart-Computer` uses the **ComputerName** and **Credential** parameters with their variables. The **Force** parameter causes an immediate restart of each computer. ### Example 6: Restart a remote computer and wait for PowerShell `Restart-Computer` restarts the remote computer and then waits up to 5 minutes (300 seconds) for PowerShell to become available on the restarted computer before it continues. ```powershell Restart-Computer -ComputerName Server01 -Wait -For PowerShell -Timeout 300 -Delay 2 ``` `Restart-Computer` uses the **ComputerName** parameter to specify **Server01**. The **Wait** parameter waits for the restart to finish. The **For** specifies that PowerShell can run commands on the remote computer. The **Timeout** parameter specifies a five-minute wait. The **Delay** parameter queries the remote computer every two seconds to determine whether it's restarted. ### Example 7: Restart a computer by using WsmanAuthentication `Restart-Computer` restarts the remote computer using the **WsmanAuthentication** mechanism. Kerberos authentication determines whether the current user has permission to restart the remote computer. For more information, see [AuthenticationMechanism](xref:System.Management.Automation.Runspaces.AuthenticationMechanism). ```powershell Restart-Computer -ComputerName Server01 -WsmanAuthentication Kerberos ``` `Restart-Computer` uses the **ComputerName** parameter to specify the remote computer, **Server01**. The **WsmanAuthentication** parameter specifies the authentication method as **Kerberos**. ## PARAMETERS ### -ComputerName Specifies one computer name or a comma-separated array of computer names. `Restart-Computer` accepts **ComputerName** objects from the pipeline or variables. Type the NetBIOS name, an IP address, or a fully qualified domain name of a remote computer. To specify the local computer, type the computer name, a dot `.`, or localhost. This parameter doesn't rely on PowerShell remoting. You can use the **ComputerName** parameter even if your computer isn't configured to run remote commands. If the **ComputerName** parameter isn't specified, `Restart-Computer` restarts the local computer. This parameter is only available on Windows platforms. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: CN, __SERVER, Server, IPAddress Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to do this action. The default is the current user. Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. If you type a user name, you're prompted to enter the password. Credentials are stored in a [PSCredential](xref:System.Management.Automation.PSCredential) object and the password is stored as a [SecureString](xref:System.Security.SecureString). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](xref:System.Security.SecureString#how-secure-is-securestring). This parameter is only available on Windows platforms. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: Current user Accept pipeline input: False Accept wildcard characters: False ``` ### -Delay Specifies the frequency of queries, in seconds. PowerShell queries the service specified by the **For** parameter to determine whether the service is available after the computer is restarted. This parameter is valid only together with the **Wait** and **For** parameters. This parameter was introduced in Windows PowerShell 3.0. If the **Delay** parameter isn't specified, `Restart-Computer` uses a five second delay. This parameter is only available on Windows platforms. ```yaml Type: System.Int16 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -For Specifies the behavior of PowerShell as it waits for the specified service or feature to become available after the computer restarts. This parameter is only valid with the **Wait** parameter. The acceptable values for this parameter are: - **Default**: Waits for PowerShell to restart. - **PowerShell**: Can run commands in a PowerShell remote session on the computer. - **WMI**: Receives a reply to a **Win32_ComputerSystem** query for the computer. - **WinRM**: Can establish a remote session to the computer by using WS-Management. This parameter was introduced in Windows PowerShell 3.0. This parameter is only available on Windows platforms. ```yaml Type: Microsoft.PowerShell.Commands.WaitForServiceTypes Parameter Sets: (All) Aliases: Accepted values: Wmi, WinRM, PowerShell Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Forces an immediate restart of the computer. This parameter is only available on Windows platforms. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: f Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Timeout Specifies the duration of the wait, in seconds. When the timeout elapses, `Restart-Computer` returns to the command prompt, even if the computers aren't restarted. The **Timeout** parameter is only valid with the **Wait** parameter. **Timeout** overrides the **Wait** parameter's indefinite waiting period. This parameter was introduced in Windows PowerShell 3.0. This parameter is only available on Windows platforms. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: TimeoutSec Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Wait `Restart-Computer` suppresses the PowerShell prompt and blocks the pipeline until the computers have restarted. You can use this parameter in a script to restart computers and then continue to process when the restart is finished. The **Wait** parameter waits indefinitely for the computers to restart. You can use **Timeout** to adjust the timing and the **For** and **Delay** parameters to wait for particular services to become available on the restarted computers. The **Wait** parameter isn't valid when you're restarting the local computer. If the value of the **ComputerName** parameter contains the names of remote computers and the local computer, `Restart-Computer` generates a non-terminating error for **Wait** on the local computer, but waits for the remote computers to restart. This parameter was introduced in Windows PowerShell 3.0. This parameter is only available on Windows platforms. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WsmanAuthentication Specifies the mechanism that is used to authenticate the user credentials. This parameter was introduced in Windows PowerShell 3.0. The acceptable values for this parameter are: **Basic**, **CredSSP**, **Default**, **Digest**, **Kerberos**, and **Negotiate**. For more information, see [AuthenticationMechanism](xref:System.Management.Automation.Runspaces.AuthenticationMechanism). > [!WARNING] > Credential Security Service Provider (CredSSP) authentication, in which the user credentials are > passed to a remote computer to be authenticated, is designed for commands that require > authentication on more than one resource, such as accessing a remote network share. This mechanism > increases the security risk of the remote operation. If the remote computer is compromised, the > credentials that are passed to it can be used to control the network session. This parameter is only available on Windows platforms. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: Basic, CredSSP, Default, Digest, Kerberos, Negotiate Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running `Restart-Computer`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the `Restart-Computer` runs. The `Restart-Computer` cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a computer name to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES - In Windows, `Restart-Computer` uses the [Win32Shutdown method](/windows/desktop/CIMWin32Prov/win32shutdown-method-in-class-win32-operatingsystem) of the Windows Management Instrumentation (WMI) [Win32_OperatingSystem](/windows/desktop/CIMWin32Prov/win32-operatingsystem) class. This method requires the **SeShutdownPrivilege** privilege be enabled for the user account used to restart the machine. - This cmdlet was added for Linux and macOS in PowerShell 7.1. On Linux and macOS, `Restart-Computer` uses the `/sbin/shutdown` bash tool. ## RELATED LINKS [About Windows Remote Management](/windows/desktop/WinRM/about-windows-remote-management) [Get-Credential](../Microsoft.PowerShell.Security/Get-Credential.md) [WS-Management Protocol](/windows/desktop/WinRM/ws-management-protocol)

#File: reference/7.6/Microsoft.PowerShell.Management/Restart-Service.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 09/03/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/restart-service?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Restart-Service --- # Restart-Service ## SYNOPSIS Stops and then starts one or more services. ## SYNTAX ### InputObject (Default) ``` Restart-Service [-Force] [-InputObject] <ServiceController[]> [-PassThru] [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Default ``` Restart-Service [-Force] [-Name] <String[]> [-PassThru] [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### DisplayName ``` Restart-Service [-Force] [-PassThru] -DisplayName <String[]> [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Restart-Service` cmdlet sends a stop message and then a start message to the Windows Service Controller for a specified service. If a service was already stopped, it is started without notifying you of an error. You can specify the services by their service names or display names, or you can use the **InputObject** parameter to pass an object that represents each service that you want to restart. ## EXAMPLES ### Example 1: Restart a service on the local computer ```powershell PS C:\> Restart-Service -Name winmgmt ``` This command restarts the Windows Management Instrumentation service (WinMgmt) on the local computer. ### Example 2: Exclude a service ```powershell PS C:\> Restart-Service -DisplayName "net*" -Exclude "net logon" ``` This command restarts the services that have a display name that starts with Net, except for the Net Logon service. ### Example 3: Start all stopped network services ```powershell PS C:\> Get-Service -Name "net*" | Where-Object {$_.Status -eq "Stopped"} | Restart-Service ``` This command starts all of the stopped network services on the computer. This command uses the `Get-Service` cmdlet to get objects that represent the services whose service name starts with net. The pipeline operator (`|`) sends the services object to the `Where-Object` cmdlet, which selects only the services that have a status of stopped. Another pipeline operator sends the selected services to `Restart-Service`. In practice, you would use the **WhatIf** parameter to determine the effect of the command before you run it. ## PARAMETERS ### -DisplayName Specifies the display names of the services to restarted. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: DisplayName Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Exclude Specifies services that this cmdlet omits. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as s*. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Forces the command to run without asking for user confirmation. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies services that this cmdlet restarts. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as s*. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -InputObject Specifies **ServiceController** objects that represent the services to restart. Enter a variable that contains the objects, or type a command or expression that gets the objects. ```yaml Type: System.ServiceProcess.ServiceController[] Parameter Sets: InputObject Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies the service names of the services to restart. ```yaml Type: System.String[] Parameter Sets: Default Aliases: ServiceName Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -PassThru Returns an object that represents the service. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.ServiceProcess.ServiceController You can pipe a service object to this cmdlet. ### System.String You can pipe a string that contains a service name to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.ServiceProcess.ServiceController When you use the **PassThru** parameter, this cmdlet returns a **ServiceController** object representing the restarted service. ## NOTES This cmdlet is only available on Windows platforms. - `Restart-Service` can control services only when the current user has permission to do this. If a command does not work correctly, you might not have the required permissions. - To find the service names and display names of the services on your system, type `Get-Service`". The service names appear in the **Name** column, and the display names appear in the **DisplayName** column. ## RELATED LINKS [Get-Service](Get-Service.md) [New-Service](New-Service.md) [Resume-Service](Resume-Service.md) [Set-Service](Set-Service.md) [Start-Service](Start-Service.md) [Stop-Service](Stop-Service.md) [Suspend-Service](Suspend-Service.md) [Remove-Service](Remove-Service.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Resume-Service.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/resume-service?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Resume-Service --- # Resume-Service ## SYNOPSIS Resumes one or more suspended (paused) services. ## SYNTAX ### InputObject (Default) ``` Resume-Service [-InputObject] <ServiceController[]> [-PassThru] [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Default ``` Resume-Service [-Name] <String[]> [-PassThru] [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### DisplayName ``` Resume-Service [-PassThru] -DisplayName <String[]> [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Resume-Service` cmdlet sends a resume message to the Windows Service Controller for each of the specified services. If a service is suspended, it resumes. If it is currently running, the message is ignored. You can specify the services by their service names or display names, or you can use the **InputObject** parameter to pass a service object that represents the services that you want to resume. ## EXAMPLES ### Example 1: Resume a service on the local computer ``` PS C:\> Resume-Service "sens" ``` This command resumes the System Event Notification service on the local computer. The service name is represented in the command by sens. The command uses the **Name** parameter to specify the service name of the service, but the command omits the parameter name because the parameter name is optional. ### Example 2: Resume all suspended services ``` PS C:\> Get-Service | Where-Object {$_.Status -eq "Paused"} | Resume-Service ``` This command resumes all of the suspended services on the computer. The `Get-Service` cmdlet command gets all of the services on the computer. The pipeline operator (`|`) passes the results to the `Where-Object` cmdlet, which selects the services that have a **Status** property of Paused. The next pipeline operator sends the results to `Resume-Service`, which resumes the paused services. In practice, you would use the **WhatIf** parameter to determine the effect of the command before you run it. ## PARAMETERS ### -DisplayName Specifies the display names of the services to be resumed. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: DisplayName Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Exclude Specifies services that this cmdlet omits. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as s*. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Include Specifies services to resume. The value of this parameter qualifies **Name** parameter. Enter a name element or pattern, such as s*. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -InputObject Specifies **ServiceController** objects that represent the services to resumed. Enter a variable that contains the objects, or type a command or expression that gets the objects. ```yaml Type: System.ServiceProcess.ServiceController[] Parameter Sets: InputObject Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies the service names of the services to be resumed. ```yaml Type: System.String[] Parameter Sets: Default Aliases: ServiceName Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -PassThru Returns an object that represents the service. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.ServiceProcess.ServiceController You can pipe a service object to this cmdlet. ### System.String You can pipe a string that contains a service name to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.ServiceProcess.ServiceController When you use the **PassThru** parameter, this cmdlet returns a **ServiceController** object representing the resumed service. ## NOTES This cmdlet is only available on Windows platforms. - The status of services that have been suspended is Paused. When services are resumed, their status is Running. - `Resume-Service` can control services only when the current user has permission to do this. If a command does not work correctly, you might not have the required permissions. - To find the service names and display names of the services on your system, type `Get-Service`. The service names appear in the **Name** column, and the display names appear in the **DisplayName** column. ## RELATED LINKS [Get-Service](Get-Service.md) [New-Service](New-Service.md) [Restart-Service](Restart-Service.md) [Set-Service](Set-Service.md) [Start-Service](Start-Service.md) [Stop-Service](Stop-Service.md) [Suspend-Service](Suspend-Service.md) [Remove-Service](Remove-Service.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Set-Clipboard.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 08/30/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/set-clipboard?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-Clipboard --- # Set-Clipboard ## SYNOPSIS Sets the contents of the clipboard. ## SYNTAX ``` Set-Clipboard [-Value] <string[]> [-Append] [-PassThru] [-AsOSC52] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Set-Clipboard` cmdlet sets the contents of the clipboard. > [!NOTE] > On Linux, this cmdlet requires the `xclip` utility to be in the path. On macOS, this cmdlet uses > the `pbcopy` utility. ## EXAMPLES ### Example 1: Copy text to the clipboard ```powershell Set-Clipboard -Value "This is a test string" ``` ### Example 2: Copy the contents of a file to the clipboard This example pipes the contents of a file, a public ssh key, to the clipboard. Then, the key can be pasted into another application, like GitHub. ```powershell Get-Content C:\Users\user1\.ssh\id_ed25519.pub | Set-Clipboard ``` ### Example 3: Copy text to the clipboard of the local host over an SSH remote session The **AsOSC52** parameter allows you to set the clipboard of the local machine when connected to a remote session over SSH. ```powershell Set-Clipboard -Value "This is a test string" -AsOSC52 ``` ### Example 4: Set the default value of the **AsOSC52** parameter You can detect if you are connected to a remote session over SSH by checking the value of the `$Env:SSH_CLIENT` or `$Env:SSH_TTY` environment variables. If either of these variables are set, then you are connected to a remote session over SSH. You can use this information to set the default value of the **AsOSC52** parameter. Add one of the following lines to your PowerShell profile script. ```powershell $PSDefaultParameterValues['Set-Clipboard:AsOSC52'] = $Env:SSH_CLIENT $PSDefaultParameterValues['Set-Clipboard:AsOSC52'] = $Env:SSH_TTY ``` For more information about `$PSDefaultParameterValues`, see [about_Parameters_Default_Values](/powershell/module/microsoft.powershell.core/about/about_parameters_default_values). ## PARAMETERS ### -Append Indicates that the cmdlet should add to the clipboard instead of replacing it. By default, the cmdlet clears the current content from the clipboard and sets it to the new content. When this parameter is specified, the cmdlet appends the new content after a newline to the current content. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -AsOSC52 When connected to a remote session over SSH, `Set-Clipboard` sets the clipboard of the remote machine, not the local host. When you use this parameter, `Set-Clipboard` uses the OSC52 ANSI escape sequence to set the clipboard of the local machine. For this feature to work, your terminal application must support the OSC52 ANSI escape sequence. The [Windows Terminal](/windows/terminal/) supports this feature. This parameter was added in PowerShell 7.4. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: ToLocalhost Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns an object representing the item with which you're working. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Value The string values to be added to the clipboard. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string containing the content to set to the clipboard to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Set-Clipboard`: - All platforms: - `scb` Support for this cmdlet on macOS was added in the PowerShell 7.0.0 release. ## RELATED LINKS [Get-Clipboard](Get-Clipboard.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Set-Content.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 03/15/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/set-content?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-Content --- # Set-Content ## SYNOPSIS Writes new content or replaces existing content in a file. ## SYNTAX ### Path (Default) - FileSystem provider ``` Set-Content [-Path] <string[]> [-Value] <Object[]> [-PassThru] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-NoNewline] [-Encoding <Encoding>] [-AsByteStream] [-Stream <string>] [<CommonParameters>] ``` ### LiteralPath - FileSystem provider ``` Set-Content [-Value] <Object[]> -LiteralPath <string[]> [-PassThru] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-NoNewline] [-Encoding <Encoding>] [-AsByteStream] [-Stream <string>] [<CommonParameters>] ``` ### Path (Default) - All providers ``` Set-Content [-Path] <string[]> [-Value] <Object[]> [-PassThru] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath - All providers ``` Set-Content [-Value] <Object[]> -LiteralPath <string[]> [-PassThru] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Force] [-Credential <pscredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION `Set-Content` is a string-processing cmdlet that writes new content or replaces the content in a file. `Set-Content` replaces the existing content and differs from the `Add-Content` cmdlet that appends content to a file. To send content to `Set-Content` you can use the **Value** parameter on the command line or send content through the pipeline. If you need to create files or directories for the following examples, see [New-Item](New-Item.md). ## EXAMPLES ### Example 1: Replace the contents of multiple files in a directory This example replaces the content for multiple files in the current directory. ```powershell Get-ChildItem -Path .\Test*.txt ``` ```Output Test1.txt Test2.txt Test3.txt ``` ```powershell Set-Content -Path .\Test*.txt -Value 'Hello, World' Get-Content -Path .\Test*.txt ``` ```Output Hello, World Hello, World Hello, World ``` The `Get-ChildItem` cmdlet uses the **Path** parameter to list **.txt** files that begin with `Test*` in the current directory. The `Set-Content` cmdlet uses the **Path** parameter to specify the `Test*.txt` files. The **Value** parameter provides the text string **Hello, World** that replaces the existing content in each file. The `Get-Content` cmdlet uses the **Path** parameter to specify the `Test*.txt` files and displays each file's content in the PowerShell console. ### Example 2: Create a new file and write content This example creates a new file and writes the current date and time to the file. ```powershell Set-Content -Path .\DateTime.txt -Value (Get-Date) Get-Content -Path .\DateTime.txt ``` ```Output 1/30/2019 09:55:08 ``` `Set-Content` uses the **Path** and **Value** parameters to create a new file named **DateTime.txt** in the current directory. The **Value** parameter uses `Get-Date` to get the current date and time. `Set-Content` writes the **DateTime** object to the file as a string. The `Get-Content` cmdlet uses the **Path** parameter to display the content of **DateTime.txt** in the PowerShell console. ### Example 3: Replace text in a file This command replaces all instances of word within an existing file. ```powershell Get-Content -Path .\Notice.txt ``` ```Output Warning Replace Warning with a new word. The word Warning was replaced. ``` ```powershell (Get-Content -Path .\Notice.txt) | ForEach-Object {$_ -replace 'Warning', 'Caution'} | Set-Content -Path .\Notice.txt Get-Content -Path .\Notice.txt ``` ```Output Caution Replace Caution with a new word. The word Caution was replaced. ``` The `Get-Content` cmdlet uses the **Path** parameter to specify the **Notice.txt** file in the current directory. The `Get-Content` command is wrapped with parentheses so that the command finishes before being sent down the pipeline. The contents of the **Notice.txt** file are sent down the pipeline to the `ForEach-Object` cmdlet. `ForEach-Object` uses the automatic variable `$_` and replaces each occurrence of **Warning** with **Caution**. The objects are sent down the pipeline to the `Set-Content` cmdlet. `Set-Content` uses the **Path** parameter to specify the **Notice.txt** file and writes the updated content to the file. The last `Get-Content` cmdlet displays the updated file content in the PowerShell console. ### Example 4: Use Filters with Set-Content You can specify a filter to the `Set-Content` cmdlet. When using filters to qualify the **Path** parameter, you need to include a trailing asterisk (`*`) to indicate the contents of the path. The following command set the content all `*.txt` files in the `C:\Temp` directory to the **Value** empty. ```powershell Set-Content -Path C:\Temp\* -Filter *.txt -Value "Empty" ``` ## PARAMETERS ### -AsByteStream This is a dynamic parameter made available by the **FileSystem** provider. For more information, see [about_FileSystem_Provider](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md). Specifies that the content should be written as a stream of bytes. This parameter was introduced in PowerShell 6.0. A warning occurs when you use the **AsByteStream** parameter with the **Encoding** parameter. The **AsByteStream** parameter ignores any encoding and the output is written as a stream of bytes. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Encoding This is a dynamic parameter made available by the **FileSystem** provider. For more information, see [about_FileSystem_Provider](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md). Specifies the type of encoding for the target file. The default value is `utf8NoBOM`. Encoding is a dynamic parameter that the FileSystem provider adds to `Set-Content`. This parameter works only in file system drives. The acceptable values for this parameter are as follows: - `ascii`: Uses the encoding for the ASCII (7-bit) character set. - `ansi`: Uses the encoding for the for the current culture's ANSI code page. This option was added in PowerShell 7.4. - `bigendianunicode`: Encodes in UTF-16 format using the big-endian byte order. - `bigendianutf32`: Encodes in UTF-32 format using the big-endian byte order. - `oem`: Uses the default encoding for MS-DOS and console programs. - `unicode`: Encodes in UTF-16 format using the little-endian byte order. - `utf7`: Encodes in UTF-7 format. - `utf8`: Encodes in UTF-8 format. - `utf8BOM`: Encodes in UTF-8 format with Byte Order Mark (BOM) - `utf8NoBOM`: Encodes in UTF-8 format without Byte Order Mark (BOM) - `utf32`: Encodes in UTF-32 format. Beginning with PowerShell 6.2, the **Encoding** parameter also allows numeric IDs of registered code pages (like `-Encoding 1251`) or string names of registered code pages (like `-Encoding "windows-1251"`). For more information, see the .NET documentation for [Encoding.CodePage](/dotnet/api/system.text.encoding.codepage?view=netcore-2.2). Starting with PowerShell 7.4, you can use the `Ansi` value for the **Encoding** parameter to pass the numeric ID for the current culture's ANSI code page without having to specify it manually. > [!NOTE] > **UTF-7*** is no longer recommended to use. As of PowerShell 7.1, a warning is written if you > specify `utf7` for the **Encoding** parameter. ```yaml Type: System.Text.Encoding Parameter Sets: (All) Aliases: Accepted values: ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 Required: False Position: Named Default value: utf8NoBOM Accept pipeline input: False Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Forces the cmdlet to set the contents of a file, even if the file is read-only. Implementation varies from provider to provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). The **Force** parameter does not override security restrictions. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -NoNewline This is a dynamic parameter made available by the **FileSystem** provider. For more information, see [about_FileSystem_Provider](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md). The string representations of the input objects are concatenated to form the output. No spaces or newlines are inserted between the output strings. No newline is added after the last output string. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns an object that represents the content. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path of the item that receives the content. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Stream This is a dynamic parameter made available by the **FileSystem** provider. This Parameter is only available on Windows. For more information, see [about_FileSystem_Provider](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md). Specifies an alternative data stream for content. If the stream does not exist, this cmdlet creates it. Wildcard characters are not supported. **Stream** is a dynamic parameter that the **FileSystem** provider adds to `Set-Content`. This parameter works only in file system drives. You can use the `Set-Content` cmdlet to create or update the content of any alternate data stream, such as `Zone.Identifier`. However, we do not recommend this as a way to eliminate security checks that block files that are downloaded from the Internet. If you verify that a downloaded file is safe, use the `Unblock-File` cmdlet. This parameter was introduced in PowerShell 3.0. As of PowerShell 7.2, `Set-Content` can set the content of alternative data streams from directories as well as files. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Value Specifies the new content for the item. ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Object You can pipe an object that contains the new value for the item to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.String When you use the **PassThru** parameter, this cmdlet returns a string representing the content. ## NOTES - `Set-Content` is designed for string processing. If you pipe non-string objects to `Set-Content`, it converts the object to a string before writing it. To write objects to files, use `Out-File`. - The `Set-Content` cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [about_Aliases](../Microsoft.PowerShell.Core/About/about_Aliases.md) [about_Automatic_Variables.md](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md) [Add-Content](Add-Content.md) [Clear-Content](Clear-Content.md) [Get-ChildItem](Get-ChildItem.md) [Get-Content](Get-Content.md) [ForEach-Object](../Microsoft.PowerShell.Core/ForEach-Object.md) [New-Item](New-Item.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Set-Item.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 02/16/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/set-item?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-Item --- # Set-Item ## SYNOPSIS Changes the value of an item to the value specified in the command. ## SYNTAX ### Path (Default) - All providers ``` Set-Item [-Path] <String[]> [[-Value] <Object>] [-Force] [-PassThru] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### LiteralPath - All providers ``` Set-Item -LiteralPath <String[]> [[-Value] <Object>] [-Force] [-PassThru] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-Credential <PSCredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Path (Default) - Alias and Function providers ``` Set-Item [-Path] <string[]> [[-Value] <Object>] [-Force] [-PassThru] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-Options <ScopedItemOptions>] [<CommonParameters>] ``` ### LiteralPath - Alias and Function providers ``` Set-Item [[-Value] <Object>] -LiteralPath <string[]> [-Force] [-PassThru] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-Options <ScopedItemOptions>] [<CommonParameters>] ``` ### Path (Default) - Registry provider ``` Set-Item [-Path] <string[]> [[-Value] <Object>] [-Force] [-PassThru] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-Type <RegistryValueKind>] [<CommonParameters>] ``` ### LiteralPath - Registry provider ``` Set-Item [[-Value] <Object>] -LiteralPath <string[]> [-Force] [-PassThru] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-Type <RegistryValueKind>] [<CommonParameters>] ``` ## DESCRIPTION The `Set-Item` cmdlet changes the value of an item, such as a variable or registry key, to the value specified in the command. ## EXAMPLES ### Example 1: Create an alias This command creates an alias of np for Notepad. ```powershell Set-Item -Path Alias:np -Value "C:\windows\notepad.exe" ``` ### Example 2: Change the value of an environment variable This command changes the value of the UserRole environment variable to Administrator. ```powershell Set-Item -Path Env:UserRole -Value "Administrator" ``` ### Example 3: Modify your prompt function This command changes the prompt function so that it displays the time before the path. ```powershell Set-Item -Path Function:prompt -Value {'PS '+ (Get-Date -Format t) + " " + (Get-Location) + '> '} ``` ### Example 4: Set options for your prompt function This command sets the **AllScope** and **ReadOnly** options for the prompt function. This command uses the **Options** dynamic parameter of `Set-Item`. The **Options** parameter is available in `Set-Item` only when you use it with the **Alias** or **Function** provider. ```powershell Set-Item -Path Function:prompt -Options "AllScope,ReadOnly" ``` ## PARAMETERS ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Forces the cmdlet to set items that cannot otherwise be changed, such as read-only alias or variables. The cmdlet cannot change constant aliases or variables. Implementation varies from provider to provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). Even using the *Force* parameter, the cmdlet cannot override security restrictions. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Options This is a dynamic parameter made available by the **Alias** and **Function** providers. For more information, see [about_Alias_Provider](../Microsoft.PowerShell.Core/About/about_Alias_Provider.md) and [about_Function_Provider](../Microsoft.PowerShell.Core/About/about_Function_Provider.md). Specifies the value of the **Options** property of an alias. Valid values are: - `None`: The alias has no constraints (default value) - `ReadOnly`: The alias can be deleted but can't be changed without using the **Force** parameter - `Constant`: The alias can't be deleted or changed - `Private`: The alias is available only in the current scope - `AllScope`: The alias is copied to any new scopes that are created - `Unspecified`: The option isn't specified ```yaml Type: System.Management.Automation.ScopedItemOptions Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Passes an object that represents the item to the pipeline. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies a path of the location of the items. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Type This is a dynamic parameter made available by the **Registry** provider. The **Registry** provider and this parameter are only available on Windows. Specifies the type of property that this cmdlet adds. The acceptable values for this parameter are: - `String`: Specifies a null-terminated string. Used for **REG_SZ** values. - `ExpandString`: Specifies a null-terminated string that contains unexpanded references to environment variables that are expanded when the value is retrieved. Used for **REG_EXPAND_SZ** values. - `Binary`: Specifies binary data in any form. Used for **REG_BINARY** values. - `DWord`: Specifies a 32-bit binary number. Used for **REG_DWORD** values. - `MultiString`: Specifies an array of null-terminated strings terminated by two null characters. Used for **REG_MULTI_SZ** values. - `Qword`: Specifies a 64-bit binary number. Used for **REG_QWORD** values. - `Unknown`: Indicates an unsupported registry data type, such as **REG_RESOURCE_LIST** values. ```yaml Type: Microsoft.Win32.RegistryValueKind Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Value Specifies a new value for the item. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.Object You can pipe an object that represents the new value of the item to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Object When you use the **PassThru** parameter, this cmdlet returns an object representing the item. ## NOTES PowerShell includes the following aliases for `Set-Item`: - All platforms: - `si` - `Set-Item` is not supported by the PowerShell FileSystem provider. To change the values of items in the file system, use the `Set-Content` cmdlet. - In the Registry drives, `HKLM:` and `HKCU:`, `Set-Item` changes the data in the (Default) value of a registry key. - To create and change the names of registry keys, use the `New-Item` and `Rename-Item` cmdlet. - To change the names and data in registry values, use the `New-ItemProperty`, `Set-ItemProperty`, and `Rename-ItemProperty` cmdlets. - `Set-Item` is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Clear-Item](Clear-Item.md) [Copy-Item](Copy-Item.md) [Get-Item](Get-Item.md) [Invoke-Item](Invoke-Item.md) [Move-Item](Move-Item.md) [New-Item](New-Item.md) [Remove-Item](Remove-Item.md) [Rename-Item](Rename-Item.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Set-ItemProperty.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 02/16/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/set-itemproperty?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-ItemProperty --- # Set-ItemProperty ## SYNOPSIS Creates or changes the value of a property of an item. ## SYNTAX ### propertyValuePathSet (Default) - All providers ``` Set-ItemProperty [-Path] <string[]> [-Name] <string> [-Value] <Object> [-PassThru] [-Force] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Credential <pscredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### propertyPSObjectPathSet - All providers ``` Set-ItemProperty [-Path] <string[]> -InputObject <psobject> [-PassThru] [-Force] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Credential <pscredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### propertyValueLiteralPathSet - All providers ``` Set-ItemProperty [-Name] <string> [-Value] <Object> -LiteralPath <string[]> [-PassThru] [-Force] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Credential <pscredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### propertyPSObjectLiteralPathSet - All providers ``` Set-ItemProperty -LiteralPath <string[]> -InputObject <psobject> [-PassThru] [-Force] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Credential <pscredential>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### propertyValuePathSet (Default) - Registry provider ``` Set-ItemProperty [-Path] <string[]> [-Name] <string> [-Value] <Object> [-PassThru] [-Force] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-Type <RegistryValueKind>] [<CommonParameters>] ``` ### propertyPSObjectPathSet - Registry provider ``` Set-ItemProperty [-Path] <string[]> -InputObject <psobject> [-PassThru] [-Force] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-Type <RegistryValueKind>] [<CommonParameters>] ``` ### propertyValueLiteralPathSet - Registry provider ``` Set-ItemProperty [-Name] <string> [-Value] <Object> -LiteralPath <string[]> [-PassThru] [-Force] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-Type <RegistryValueKind>] [<CommonParameters>] ``` ### propertyPSObjectLiteralPathSet - Registry provider ``` Set-ItemProperty -LiteralPath <string[]> -InputObject <psobject> [-PassThru] [-Force] [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-Credential <pscredential>] [-WhatIf] [-Confirm] [-Type <RegistryValueKind>] [<CommonParameters>] ``` ## DESCRIPTION The `Set-ItemProperty` cmdlet changes the value of the property of the specified item. You can use the cmdlet to establish or change the properties of items. For example, you can use `Set-ItemProperty` to set the value of the **IsReadOnly** property of a file object to `$true`. You also use `Set-ItemProperty` to create and change registry values and data. For example, you can add a new registry entry to a key and establish or change its value. ## EXAMPLES ### Example 1: Set a property of a file This command sets the value of the **IsReadOnly** property of the "final.doc" file to "true". It uses **Path** to specify the file, **Name** to specify the name of the property, and the **Value** parameter to specify the new value. The file is a **System.IO.FileInfo** object and **IsReadOnly** is just one of its properties. To see all of the properties, type `Get-Item C:\GroupFiles\final.doc | Get-Member -MemberType Property`. The `$true` automatic variable represents a value of "TRUE". For more information, see [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md). ```powershell Set-ItemProperty -Path C:\GroupFiles\final.doc -Name IsReadOnly -Value $true ``` ### Example 2: Create a registry entry and value This example shows how to use `Set-ItemProperty` to create a new registry entry and to assign a value to the entry. It creates the "NoOfEmployees" entry in the "ContosoCompany" key in `HKLM\Software` key and sets its value to 823. Because registry entries are considered to be properties of the registry keys, which are items, you use `Set-ItemProperty` to create registry entries, and to establish and change their values. ```powershell Set-ItemProperty -Path "HKLM:\Software\ContosoCompany" -Name "NoOfEmployees" -Value 823 Get-ItemProperty -Path "HKLM:\Software\ContosoCompany" ``` ```Output PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\contosocompany PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software PSChildName : contosocompany PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry NoOfLocations : 2 NoOfEmployees : 823 ``` ```powershell Set-ItemProperty -Path "HKLM:\Software\ContosoCompany" -Name "NoOfEmployees" -Value 824 Get-ItemProperty -Path "HKLM:\Software\ContosoCompany" ``` ```Output PSPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software\contosocompany PSParentPath : Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\software PSChildName : contosocompany PSDrive : HKLM PSProvider : Microsoft.PowerShell.Core\Registry NoOfLocations : 2 NoOfEmployees : 824 ``` The first command creates the registry entry. It uses **Path** to specify the path of the `HKLM:` drive and the `Software\MyCompany` key. The command uses **Name** to specify the entry name and **Value** to specify a value. The second command uses the `Get-ItemProperty` cmdlet to see the new registry entry. If you use the `Get-Item` or `Get-ChildItem` cmdlets, the entries do not appear because they are properties of a key, not items or child items. The third command changes the value of the **NoOfEmployees** entry to 824. You can also use the `New-ItemProperty` cmdlet to create the registry entry and its value and then use `Set-ItemProperty` to change the value. For more information about the `HKLM:` drive, type `Get-Help Get-PSDrive`. For more information about how to use PowerShell to manage the registry, type `Get-Help Registry`. ### Example 3: Modify an item by using the pipeline Th example uses `Get-ChildItem` to get the `weekly.txt` file. The file object is piped to `Set-ItemProperty`. The `Set-ItemProperty` command uses the **Name** and **Value** parameters to specify the property and its new value. ```powershell Get-ChildItem weekly.txt | Set-ItemProperty -Name IsReadOnly -Value $true ``` ## PARAMETERS ### -Credential > [!NOTE] > This parameter is not supported by any providers installed with PowerShell. > To impersonate another user, or elevate your credentials when running this cmdlet, > use [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies, as a string array, an item or items that this cmdlet excludes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. The **Exclude** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter to qualify the **Path** parameter. The [FileSystem](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md) provider is the only installed PowerShell provider that supports the use of filters. You can find the syntax for the **FileSystem** filter language in [about_Wildcards](../Microsoft.PowerShell.Core/About/about_Wildcards.md). Filters are more efficient than other parameters, because the provider applies them when the cmdlet gets the objects rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Forces the cmdlet to set a property on items that cannot otherwise be accessed by the user. Implementation varies by provider. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies, as a string array, an item or items that this cmdlet includes in the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `"*.txt"`. Wildcard characters are permitted. The **Include** parameter is effective only when the command includes the contents of an item, such as `C:\Windows\*`, where the wildcard character specifies the contents of the `C:\Windows` directory. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -InputObject Specifies the object that has the properties that this cmdlet changes. Enter a variable that contains the object or a command that gets the object. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: propertyPSObjectPathSet, propertyPSObjectLiteralPathSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -LiteralPath Specifies a path to one or more locations. The value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: propertyValueLiteralPathSet, propertyPSObjectLiteralPathSet Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies the name of the property. ```yaml Type: System.String Parameter Sets: propertyValuePathSet, propertyValueLiteralPathSet Aliases: PSProperty Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Returns an object that represents the item property. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path of the items with the property to modify. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: propertyValuePathSet, propertyPSObjectPathSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Type This is a dynamic parameter made available by the **Registry** provider. The **Registry** provider and this parameter are only available on Windows. Specifies the type of property that this cmdlet adds. The acceptable values for this parameter are: - `String`: Specifies a null-terminated string. Used for **REG_SZ** values. - `ExpandString`: Specifies a null-terminated string that contains unexpanded references to environment variables that are expanded when the value is retrieved. Used for **REG_EXPAND_SZ** values. - `Binary`: Specifies binary data in any form. Used for **REG_BINARY** values. - `DWord`: Specifies a 32-bit binary number. Used for **REG_DWORD** values. - `MultiString`: Specifies an array of null-terminated strings terminated by two null characters. Used for **REG_MULTI_SZ** values. - `Qword`: Specifies a 64-bit binary number. Used for **REG_QWORD** values. - `Unknown`: Indicates an unsupported registry data type, such as **REG_RESOURCE_LIST** values. ```yaml Type: Microsoft.Win32.RegistryValueKind Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Value Specifies the value of the property. ```yaml Type: System.Object Parameter Sets: propertyValuePathSet, propertyValueLiteralPathSet Aliases: Required: True Position: 2 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.Management.Automation.PSObject You can pipe objects to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSCustomObject When you use the **PassThru** parameter, this cmdlet returns a **PSCustomObject** object representing the item that was changed and its new property value. ## NOTES PowerShell includes the following aliases for `Set-ItemProperty`: - All platforms: - `sp` `Set-ItemProperty` is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Clear-ItemProperty](Clear-ItemProperty.md) [Copy-ItemProperty](Copy-ItemProperty.md) [Get-ItemProperty](Get-ItemProperty.md) [Move-ItemProperty](Move-ItemProperty.md) [New-ItemProperty](New-ItemProperty.md) [Remove-ItemProperty](Remove-ItemProperty.md) [Rename-ItemProperty](Rename-ItemProperty.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Set-Location.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/set-location?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-Location --- # Set-Location ## SYNOPSIS Sets the current working location to a specified location. ## SYNTAX ### Path (Default) ``` Set-Location [[-Path] <String>] [-PassThru] [<CommonParameters>] ``` ### LiteralPath ``` Set-Location -LiteralPath <String> [-PassThru] [<CommonParameters>] ``` ### Stack ``` Set-Location [-PassThru] [-StackName <String>] [<CommonParameters>] ``` ## DESCRIPTION The `Set-Location` cmdlet sets the working location to a specified location. That location could be a directory, a subdirectory, a registry location, or any provider path. PowerShell 6.2 added support for `-` and `+` as a values for the **Path** parameter. PowerShell maintains a history of the last 20 locations that can be accessed with `-` and `+`. This list is independent from the location stack that is accessed using the **StackName** parameter. ## EXAMPLES ### Example 1: Set the current location ```powershell PS C:\> Set-Location -Path "HKLM:\" PS HKLM:\> ``` This command sets the current location to the root of the `HKLM:` drive. ### Example 2: Set the current location and display that location ```powershell PS C:\> Set-Location -Path "Env:\" -PassThru ``` ```Output Path ---- Env:\ PS Env:\> ``` This command sets the current location to the root of the `Env:` drive. It uses the **PassThru** parameter to direct PowerShell to return a **PathInfo** object that represents the `Env:\` location. ### Example 3: Set location to the current location in the C: drive ```powershell PS C:\Windows\> Set-Location HKLM:\ PS HKLM:\> Set-Location C: PS C:\Windows\> ``` The first command sets the location to the root of the `HKLM:` drive in the Registry provider. The second command sets the location to the current location of the `C:` drive in the FileSystem provider. When the drive name is specified in the form `<DriveName>:` (without backslash), the cmdlet sets the location to the current location in the PSDrive. To get the current location in the PSDrive use `Get-Location -PSDrive <DriveName>` command. ### Example 4: Set the current location to a named stack ```powershell PS C:\> Push-Location -Path 'C:\Program Files\PowerShell\' -StackName "Paths" PS C:\Program Files\PowerShell\> Set-Location -StackName "Paths" PS C:\Program Files\PowerShell\> Get-Location -Stack ``` ```Output Path ---- C:\ ``` The first command adds the current location to the Paths stack. The second command makes the Paths location stack the current location stack. The third command displays the locations in the current location stack. The `*-Location` cmdlets use the current location stack unless a different location stack is specified in the command. For information about location stacks, see the [Notes](#notes). ### Example 5: Navigate location history using `+` or `-` ``` PS C:\> Set-Location -Path $Env:SystemRoot PS C:\Windows> Set-Location -Path Cert:\ PS Cert:\> Set-Location -Path HKLM:\ PS HKLM:\> # Navigate back through the history using "-" PS HKLM:\> Set-Location -Path - PS Cert:\> Set-Location -Path - PS C:\Windows> # Navigate using the Set-Location alias "cd" and the implicit positional Path parameter PS C:\Windows> cd - PS C:\> cd + PS C:\Windows> cd + PS Cert:\> ``` Using the alias, `cd -` or `cd +` is an easy way to navigate through your location history while in your terminal. For more information on navigating with `-`/`+`, see the **Path** parameter. ## PARAMETERS ### -LiteralPath Specifies a path of the location. The value of the **LiteralPath** parameter is used exactly as it is typed. No characters are interpreted as wildcard characters. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Returns a **PathInfo** object that represents the location. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specify the path of a new working location. If no path is provided, `Set-Location` defaults to the current user's home directory. When wildcards are used, the cmdlet chooses the container (directory, registry key, certificate store) that matches the wildcard pattern. If the wildcard pattern matches more than one container, the cmdlet returns an error. PowerShell keeps a history of the last 20 locations you have set. If the **Path** parameter value is the `-` character, then the new working location will be the previous working location in history (if it exists). Similarly, if the value is the `+` character, then the new working location will be the next working location in history (if it exists). This is similar to using `Pop-Location` and `Push-Location` except that the history is a list, not a stack, and is implicitly tracked, not manually controlled. There is no way to view the history list. ```yaml Type: System.String Parameter Sets: Path Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -StackName Specifies an existing location stack name that this cmdlet makes the current location stack. Enter a location stack name. To indicate the unnamed default location stack, type `$null` or an empty string (`""`). Using this parameter does not change the current location. It only changes the stack used by the `*-Location` cmdlets. The `*-Location` cmdlets act on the current stack unless you use the **StackName** parameter to specify a different stack. For more information about location stacks, see the [Notes](#notes). ```yaml Type: System.String Parameter Sets: Stack Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a path, but not a literal path, to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PathInfo When you use the **PassThru** parameter with **Path** or **LiteralPath**, this cmdlet returns a **PathInfo** object representing the new location. ### System.Management.Automation.PathInfoStack When you use the **PassThru** parameter with **StackName**, this cmdlet returns a **PathInfoStack** object representing the new stack context. ## NOTES PowerShell includes the following aliases for `Set-Location`: - All Platforms: - `cd` - `chdir` - `sl` PowerShell supports multiple runspaces per process. Each runspace has its own _current directory_. This is not the same as `[System.Environment]::CurrentDirectory`. This behavior can be an issue when calling .NET APIs or running native applications without providing explicit directory paths. Even if the location cmdlets did set the process-wide current directory, you can't depend on it because another runspace might change it at any time. You should use the location cmdlets to perform path-based operations using the current working directory specific to the current runspace. The `Set-Location` cmdlet is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/about/about_Providers.md). A stack is a last-in, first-out list in which only the most recently added item can be accessed. You add items to a stack in the order that you use them, and then retrieve them for use in the reverse order. PowerShell lets you store provider locations in location stacks. PowerShell creates an unnamed default location stack. You can create multiple named location stacks. If you do not specify a stack name, PowerShell uses the current location stack. By default, the unnamed default location is the current location stack, but you can use the `Set-Location` cmdlet to change the current location stack. To manage location stacks, use the `*-Location` cmdlets, as follows: - To add a location to a location stack, use the `Push-Location` cmdlet. - To get a location from a location stack, use the `Pop-Location` cmdlet. - To display the locations in the current location stack, use the **Stack** parameter of the `Get-Location` cmdlet. To display the locations in a named location stack, use the **StackName** parameter of `Get-Location`. - To create a new location stack, use the **StackName** parameter of `Push-Location`. If you specify a stack that does not exist, `Push-Location` creates the stack. - To make a location stack the current location stack, use the **StackName** parameter of `Set-Location`. The unnamed default location stack is fully accessible only when it is the current location stack. If you make a named location stack the current location stack, you can no longer use the `Push-Location` or `Pop-Location` cmdlets to add or get items from the default stack or use the `Get-Location` cmdlet to display the locations in the unnamed stack. To make the unnamed stack the current stack, use the **StackName** parameter of the `Set-Location` cmdlet with a value of `$null` or an empty string (`""`). ## RELATED LINKS [Get-Location](Get-Location.md) [Pop-Location](Pop-Location.md) [Push-Location](Push-Location.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Set-Service.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 03/20/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/set-service?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-Service --- # Set-Service ## SYNOPSIS Starts, stops, and suspends a service, and changes its properties. ## SYNTAX ### Name (Default) ``` Set-Service [-Name] <String> [-DisplayName <String>] [-Credential <PSCredential>] [-Description <String>] [-StartupType <ServiceStartupType>] [-Status <String>] [-SecurityDescriptorSddl <String>] [-Force] [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### InputObject ``` Set-Service [-InputObject] <ServiceController> [-DisplayName <String>] [-Credential <PSCredential>] [-Description <String>] [-StartupType <ServiceStartupType>] [-SecurityDescriptorSddl <String>] [-Status <String>] [-Force] [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Set-Service` cmdlet changes the properties of a service such as the **Status**, **Description**, **DisplayName**, and **StartupType**. `Set-Service` can start, stop, suspend, or pause a service. To identify a service, enter its service name or submit a service object. Or, send a service name or service object down the pipeline to `Set-Service`. ## EXAMPLES ### Example 1: Change a display name In this example, a service's display name is changed. To view the original display name, use `Get-Service`. ```powershell Set-Service -Name LanmanWorkstation -DisplayName "LanMan Workstation" ``` `Set-Service` uses the **Name** parameter to specify the service's name, **LanmanWorkstation**. The **DisplayName** parameter specifies the new display name, **LanMan Workstation**. ### Example 2: Change the startup type of services This example shows how to change a service's startup type. ```powershell Set-Service -Name BITS -StartupType Automatic Get-Service BITS | Select-Object -Property Name, StartType, Status ``` ```Output Name StartType Status ---- --------- ------ BITS Automatic Running ``` `Set-Service` uses the **Name** parameter to specify the service's name, **BITS**. The **StartupType** parameter sets the service to **Automatic**. `Get-Service` uses the **Name** parameter to specify the **BITS** service and sends the object down the pipeline. `Select-Object` uses the **Property** parameter to display the **BITS** service's status. ### Example 3: Change the description of a service This example changes the BITS service's description and displays the result. The `Get-CimInstance` cmdlet is used because it returns a **Win32_Service** object that includes the service's **Description**. ```powershell Get-CimInstance Win32_Service -Filter 'Name = "BITS"' | Format-List Name, Description ``` ```Output Name : BITS Description : Transfers files in the background using idle network bandwidth. If the service is disabled, then any applications that depend on BITS, such as Windows Update or MSN Explorer, will be unable to automatically download programs and other information. ``` ```powershell Set-Service -Name BITS -Description "Transfers files in the background using idle network bandwidth." Get-CimInstance Win32_Service -Filter 'Name = "BITS"' | Format-List Name, Description ``` ```Output Name : BITS Description : Transfers files in the background using idle network bandwidth. ``` `Get-CimInstance` sends the object down the pipeline to `Format-List` and displays the service's name and description. For comparison purposes, the command is run before and after the description is updated. `Set-Service` uses the **Name** parameter to specify the **BITS** service. The **Description** parameter specifies the updated text for the services' description. ### Example 4: Start a service In this example, a service is started. ```powershell Set-Service -Name WinRM -Status Running -PassThru ``` ```Output Status Name DisplayName ------ ---- ----------- Running WinRM Windows Remote Management (WS-Manag... ``` `Set-Service` uses the **Name** parameter to specify the service, **WinRM**. The **Status** parameter uses the value **Running** to start the service. The **PassThru** parameter outputs a **ServiceController** object that displays the results. ### Example 5: Suspend a service This example uses the pipeline to pause to service. ```powershell Get-Service -Name Schedule | Set-Service -Status Paused ``` `Get-Service` uses the **Name** parameter to specify the **Schedule** service, and sends the object down the pipeline. `Set-Service` uses the **Status** parameter to set the service to **Paused**. ### Example 6: Stop a service This example uses a variable to stop a service. ```powershell $S = Get-Service -Name Schedule Set-Service -InputObject $S -Status Stopped ``` `Get-Service` uses the **Name** parameter to specify the service, **Schedule**. The object is stored in the variable, `$S`. `Set-Service` uses the **InputObject** parameter and specifies the object stored `$S`. The **Status** parameter sets the service to **Stopped**. ### Example 7: Stop a service on a remote system This example stops a service on a remote computer. For more information, see [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```powershell $Cred = Get-Credential $S = Get-Service -Name Schedule Invoke-Command -ComputerName server01.contoso.com -Credential $Cred -ScriptBlock { Set-Service -InputObject $S -Status Stopped } ``` `Get-Credential` prompts for a username and password, and stores the credentials in the `$Cred` variable. `Get-Service` uses the **Name** parameter to specify the **Schedule** service. The object is stored in the variable, `$S`. `Invoke-Command` uses the **ComputerName** parameter to specify a remote computer. The **Credential** parameter uses the `$Cred` variable to sign on to the computer. The **ScriptBlock** calls `Set-Service`. The **InputObject** parameter specifies the service object stored `$S`. The **Status** parameter sets the service to **Stopped**. ### Example 8: Change credential of a service This example changes the credentials that are used to manage a service. ```powershell $credential = Get-Credential Set-Service -Name Schedule -Credential $credential ``` `Get-Credential` prompts for a username and password, and stores the credentials in the `$credential` variable. `Set-Service` uses the **Name** parameter to specify the **Schedule** service. The **Credential** parameter uses the `$credential` variable and updates the **Schedule** service. ### Example 9: Change the SecurityDescriptor of a service This example changes a service's **SecurityDescriptor**. ```powershell $SDDL = "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;SU)" Set-Service -Name "BITS" -SecurityDescriptorSddl $SDDL ``` The **SecurityDescriptor** is stored in the `$SDDL` variable. `Set-Service` uses the **Name** parameter to specify the **BITS** service. The **SecurityDescriptorSddl** parameter uses `$SDDL` to change the **SecurityDescriptor** for the **BITS** service. ### Example 10: Set the startup type for multiple services The `Set-Service` cmdlet only accepts one service name at a time. However, you can pipe multiple services to `Set-Service` to change the configuration of multiple services. ```powershell Get-Service SQLWriter,spooler | Set-Service -StartupType Automatic -PassThru | Select-Object Name, StartType ``` ```Output Name StartType ---- --------- spooler Automatic SQLWriter Automatic ``` ## PARAMETERS ### -Credential Specifies the account used by the service as the [Service Logon Account](/windows/desktop/ad/about-service-logon-accounts). Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object, such as one generated by the `Get-Credential` cmdlet. If you type a user name, this cmdlet prompts you for a password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Description Specifies a new description for the service. The service description appears in **Computer Management, Services**. The **Description** isn't a property of the `Get-Service` **ServiceController** object. To see the service description, use `Get-CimInstance` that returns a **Win32_Service** object that represents the service. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DisplayName Specifies a new display name for the service. > [!NOTE] > Typically, `Set-Service` only operates on Windows services and not drivers. However, if you > specify the name of a driver, `Set-Service` can target the driver. ```yaml Type: System.String Parameter Sets: (All) Aliases: DN Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Specifies the Stop mode of the service. This parameter only works when `-Status Stopped` is used. If enabled, `Set-Service` stops the dependent services before the target service is stopped. By default, exceptions are raised when other running services depend on the target service. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies a **ServiceController** object that represents the service to change. Enter a variable that contains the object, or type a command or expression that gets the object, such as a `Get-Service` command. You can use the pipeline to send a service object to `Set-Service`. ```yaml Type: System.ServiceProcess.ServiceController Parameter Sets: InputObject Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies the service name of the service to be changed. Wildcard characters aren't permitted. You can use the pipeline to send a service name to `Set-Service`. > [!NOTE] > Typically, `Set-Service` only operates on Windows services and not drivers. However, if you > specify the name of a driver, `Set-Service` can target the driver. ```yaml Type: System.String Parameter Sets: Name Aliases: ServiceName, SN Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -PassThru Returns a **ServiceController** object that represents the services that were changed. By default, `Set-Service` doesn't generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -SecurityDescriptorSddl Specifies the **SecurityDescriptor** for the service in **Sddl** format. The account calling `Set-Service` with this parameter must have the WRITE_DAC and WRITE_OWNER permissions. For more information, see [Service security and access rights](/windows/win32/services/service-security-and-access-rights). ```yaml Type: System.String Parameter Sets: (All) Aliases: sd Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -StartupType Specifies the start mode of the service. The acceptable values for this parameter are as follows: - **Automatic** - The service is started or was started by the operating system, at system start-up. If an automatically started service depends on a manually started service, the manually started service is also started automatically at system startup. - **AutomaticDelayedStart** - Starts shortly after the system boots. - **Disabled** - The service is disabled and cannot be started by a user or application. - **InvalidValue** - Has no effect. The cmdlet does not return an error but the StartupType of the service is not changed. - **Manual** - The service is started only manually, by a user, using the Service Control Manager, or by an application. ```yaml Type: Microsoft.PowerShell.Commands.ServiceStartupType Parameter Sets: (All) Aliases: StartMode, SM, ST, StartType Accepted values: Automatic, AutomaticDelayedStart, Disabled, InvalidValue, Manual Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Status Specifies the status for the service. The acceptable values for this parameter are as follows: - **Paused**. Suspends the service. - **Running**. Starts the service. - **Stopped**. Stops the service. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: Paused, Running, Stopped Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running `Set-Service`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if `Set-Service` runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.ServiceProcess.ServiceController You can pipe a service object to this cmdlet. ### System.String You can pipe a string that contains a service name to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.ServiceProcess.ServiceController When you use the **PassThru** parameter, this cmdlet returns a **ServiceController** object. ## NOTES This cmdlet is only available on Windows platforms. `Set-Service` requires elevated permissions. Use the **Run as administrator** option. `Set-Service` can only control services when the current user has permissions to manage services. If a command doesn't work correctly, you might not have the required permissions. To find a service's service name or display name, use `Get-Service`. The service names are in the **Name** column and the display names are in the **DisplayName** column. ## RELATED LINKS [Get-Service](Get-Service.md) [New-Service](New-Service.md) [Restart-Service](Restart-Service.md) [Resume-Service](Resume-Service.md) [Start-Service](Start-Service.md) [Stop-Service](Stop-Service.md) [Suspend-Service](Suspend-Service.md) [Remove-Service](Remove-Service.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Set-TimeZone.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 06/28/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/set-timezone?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-TimeZone --- # Set-TimeZone ## SYNOPSIS Sets the system time zone to a specified time zone. ## SYNTAX ### Name (Default) ``` Set-TimeZone [-Name] <String> [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Id ``` Set-TimeZone -Id <String> [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### InputObject ``` Set-TimeZone [-InputObject] <TimeZoneInfo> [-PassThru] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Set-TimeZone` cmdlet sets the system time zone to a specified time zone. ## EXAMPLES ### Example 1: Set the time zone by Id This example sets the time zone on the local computer to UTC. ```powershell Set-TimeZone -Id "UTC" ``` ```Output Id : UTC HasIanaId : True DisplayName : (UTC) Coordinated Universal Time StandardName : Coordinated Universal Time DaylightName : Coordinated Universal Time BaseUtcOffset : 00:00:00 SupportsDaylightSavingTime : False ``` ### Example 2: Set the time zone by name This example sets the time zone on the local computer to UTC. ```powershell Set-TimeZone -Name 'Coordinated Universal Time' -PassThru ``` As we saw in the previous example, the **Id** and the **Name** of the Time Zone do not always match. The **Name** parameter must match the **StandardName** or **DaylightName** properties of the **TimeZoneInfo** object. > [!NOTE] > The time zone names can vary based on the Culture settings in Windows. This example shows the > values for a system set to `en-US`. ### Example 3 - List all available time zones A full list of Time Zone IDs can be obtained by running the following command: ```powershell Get-TimeZone -ListAvailable ``` ## PARAMETERS ### -Id Specifies the ID of the time zone that this cmdlet sets. ```yaml Type: System.String Parameter Sets: Id Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InputObject Specifies a **TimeZoneInfo** object to use as input. ```yaml Type: System.TimeZoneInfo Parameter Sets: InputObject Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies the name of the time zone that this cmdlet sets. A full list of Time Zone names can be obtained by running the following command: `Get-TimeZone -ListAvailable`. ```yaml Type: System.String Parameter Sets: Name Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String ### System.TimeZoneInfo ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.TimeZoneInfo When you use the **PassThru** parameter, this cmdlet returns a **TimeZoneInfo** object. ## NOTES PowerShell includes the following aliases for `Set-TimeZone`: - Windows: - `stz` This cmdlet is only available on Windows platforms. ## RELATED LINKS [Get-TimeZone](Get-TimeZone.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Split-Path.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 09/03/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/split-path?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Split-Path --- # Split-Path ## SYNOPSIS Returns the specified part of a path. ## SYNTAX ### ParentSet (Default) ``` Split-Path [-Path] <String[]> [-Parent] [-Resolve] [-Credential <PSCredential>] [<CommonParameters>] ``` ### LeafSet ``` Split-Path [-Path] <String[]> -Leaf [-Resolve] [-Credential <PSCredential>] [<CommonParameters>] ``` ### LeafBaseSet ``` Split-Path [-Path] <String[]> -LeafBase [-Resolve] [-Credential <PSCredential>] [<CommonParameters>] ``` ### ExtensionSet ``` Split-Path [-Path] <String[]> -Extension [-Resolve] [-Credential <PSCredential>] [<CommonParameters>] ``` ### QualifierSet ``` Split-Path [-Path] <String[]> -Qualifier [-Resolve] [-Credential <PSCredential>] [<CommonParameters>] ``` ### NoQualifierSet ``` Split-Path [-Path] <String[]> -NoQualifier [-Resolve] [-Credential <PSCredential>] [<CommonParameters>] ``` ### IsAbsoluteSet ``` Split-Path [-Path] <String[]> [-Resolve] -IsAbsolute [-Credential <PSCredential>] [<CommonParameters>] ``` ### LiteralPathSet ``` Split-Path -LiteralPath <String[]> [-Resolve] [-Credential <PSCredential>] [<CommonParameters>] ``` ## DESCRIPTION The `Split-Path` cmdlet returns only the specified part of a path, such as the parent folder, a subfolder, or a filename. It can also get items that are referenced by the split path and tell whether the path is relative or absolute. If you split a path without specifying any other parameters, `Split-Path` returns the parent part of the path provided. The `Split-Path` command returns strings. It doesn't return **FileInfo** or other item objects like the `*-Item` commands do. ## EXAMPLES ### Example 1: Get the qualifier of a path ```powershell Split-Path -Path "HKCU:\Software\Microsoft" -Qualifier ``` ```Output HKCU: ``` This command returns only the qualifier of the path. The qualifier is the drive. ### Example 2: Display filename portion of the path When using the **Leaf** parameter, `Split-Path` returns only the last item in the path string supplied, regardless whether that item is a file or a directory. ```powershell Split-Path -Path .\folder1\*.txt -Leaf ``` ```Output *.txt ``` ```powershell Split-Path -Path .\folder1\*.txt -Leaf -Resolve ``` ```Output file1.txt file2.txt ``` When you use the **Resolve** parameter, `Split-Path` resolves the path string provided and returns the items referenced by the path. ### Example 3: Get the parent container When using the **Parent** parameter, `Split-Path` returns only the parent container portion of the path string supplied. If the **Path** string doesn't contain a parent container, `Split-Path` returns an empty string. ```powershell Split-Path -Path .\folder1\file1.txt -Parent ``` ```Output .\folder1 ``` ```powershell Split-Path -Path .\folder1\file1.txt -Parent -Resolve ``` ```Output D:\temp\test\folder1 ``` When you use the **Resolve** parameter, `Split-Path` resolves the path string provided and returns the full path of the parent container. ### Example 4: Determines whether a path is absolute This command determines whether the path is relative or absolute. In this case, because the path is relative to the current folder, which is represented by a dot (`.`), it returns `$false`. ```powershell Split-Path -Path ".\My Pictures\*.jpg" -IsAbsolute ``` ```Output False ``` ### Example 5: Change location to a specified path This command changes your location to the folder that contains the PowerShell profile. ```powershell PS C:\> Set-Location (Split-Path -Path $PROFILE) PS C:\Users\User01\Documents\PowerShell> ``` The command in parentheses uses `Split-Path` to return only the parent of the path stored in the built-in `$PROFILE` variable. The **Parent** parameter is the default split location parameter. Therefore, you can omit it from the command. The parentheses direct PowerShell to run the command first. This is a useful way to move to a folder that has a long path name. ### Example 6: Split a path using the pipeline ```powershell 'C:\Users\User01\My Documents\My Pictures' | Split-Path ``` ```Output C:\Users\User01\My Documents ``` This command uses a pipeline operator (`|`) to send a path to `Split-Path`. The path is enclosed in quotation marks to indicate that it's a single token. ## PARAMETERS ### -Credential > [!NOTE] > This parameter isn't supported by any providers installed with PowerShell. To impersonate another > user, or elevate your credentials when running this cmdlet, use > [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Extension Indicates that this cmdlet returns only the extension of the leaf. For example, in the path `C:\Test\Logs\Pass1.log`, it returns only `.log`. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ExtensionSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -IsAbsolute Indicates that this cmdlet returns `$true` if the path is absolute and `$false` if it's relative. On Windows, an absolute path string must start with a provider drive specifier, like `C:` or `HKCU:`. A relative path starts with a dot (`.`) or a dot-dot (`..`). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: IsAbsoluteSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Leaf When using the **Leaf** parameter, `Split-Path` returns only the last item in the path string supplied, regardless whether that item is a file or a directory. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: LeafSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -LeafBase Indicates that this cmdlet returns only base name of the leaf. For example, in the path `C:\Test\Logs\Pass1.log`, it returns only `Pass1`. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: LeafBaseSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -LiteralPath Specifies the paths to be split. Unlike **Path**, the value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcard characters. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: LiteralPathSet Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -NoQualifier Indicates that this cmdlet returns the path without the qualifier. For the FileSystem or registry providers, the qualifier is the drive of the provider path, such as `C:` or `HKCU:`. For example, in the path `C:\Test\Logs\Pass1.log`, it returns only `\Test\Logs\Pass1.log`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: NoQualifierSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Parent `Split-Path` returns only the parent container portion of the path string supplied. If the **Path** string doesn't contain a parent container, `Split-Path` returns an empty string. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ParentSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the paths to be split. Wildcard characters are permitted. If the path includes spaces, enclose it in quotation marks. You can also pipe a path to this cmdlet. ```yaml Type: System.String[] Parameter Sets: ParentSet, LeafSet, LeafBaseSet, ExtensionSet, QualifierSet, NoQualifierSet, IsAbsoluteSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Qualifier Indicates that this cmdlet returns only the qualifier of the specified path. For the FileSystem or Registry providers, the qualifier is the drive of the provider path, such as `C:` or `HKCU:`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: QualifierSet Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Resolve Indicates that this cmdlet displays the items that are referenced by the resulting split path instead of displaying the path elements. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns text strings. When you specify the **Resolve** parameter, it returns a string that describes the location of the items. It doesn't return objects that represent the items, such as a **FileInfo** or **RegistryKey** object. ### System.Boolean When you specify the **IsAbsolute** parameter, this cmdlet returns a **Boolean** value. ## NOTES - The split location parameters (**Qualifier**, **Parent**, **Extension**, **Leaf**, **LeafBase**, and **NoQualifier**) are exclusive. You can use only one in each command. - The cmdlets that contain the **Path** noun (the **Path** cmdlets) work with path names and return the names in a concise format that all PowerShell providers can interpret. They're designed for use in programs and scripts where you want to display all or part of a path name in a particular format. Use them in the way that you would use **Dirname**, **Normpath**, **Realpath**, **Join**, or other path manipulators. - You can use the **Path** cmdlets together with several providers. These include the FileSystem, Registry, and Certificate providers. - `Split-Path` is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Convert-Path](Convert-Path.md) [Join-Path](Join-Path.md) [Resolve-Path](Resolve-Path.md) [Test-Path](Test-Path.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Start-Process.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 11/01/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/start-process?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Start-Process --- # Start-Process ## SYNOPSIS Starts one or more processes on the local computer. ## SYNTAX ``` Start-Process [-FilePath] <string> [[-ArgumentList] <string[]>] [-Credential <pscredential>] [-WorkingDirectory <string>] [-LoadUserProfile] [-NoNewWindow] [-PassThru] [-RedirectStandardError <string>] [-RedirectStandardInput <string>] [-RedirectStandardOutput <string>] [-WindowStyle <ProcessWindowStyle>] [-Wait] [-UseNewEnvironment] [-Environment <hashtable>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### UseShellExecute ``` Start-Process [-FilePath] <string> [[-ArgumentList] <string[]>] [-WorkingDirectory <string>] [-PassThru] [-Verb <string>] [-WindowStyle <ProcessWindowStyle>] [-Wait] [-Environment <hashtable>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Start-Process` cmdlet starts one or more processes on the local computer. By default, `Start-Process` creates a new process that inherits all the environment variables that are defined in the current process. To specify the program that runs in the process, enter an executable file or script file, or a file that can be opened using a program on the computer. If you specify a non-executable file, `Start-Process` starts the program that's associated with the file, similar to the `Invoke-Item` cmdlet. You can use the parameters of `Start-Process` to specify options, such as loading a user profile, starting the process in a new window, or using alternate credentials. ## EXAMPLES ### Example 1: Start a process that uses default values This example starts a process that uses the `Sort.exe` file in the current folder. The command uses all the default values, including the default window style, working folder, and credentials. ```powershell Start-Process -FilePath "sort.exe" ``` ### Example 2: Print a text file This example starts a process that prints the `C:\PS-Test\MyFile.txt` file. ```powershell Start-Process -FilePath "myfile.txt" -WorkingDirectory "C:\PS-Test" -Verb Print ``` ### Example 3: Start a process to sort items to a new file This example starts a process that sorts items in the `TestSort.txt` file and returns the sorted items in the `Sorted.txt` files. Any errors are written to the `SortError.txt` file. The **UseNewEnvironment** parameter specifies that the process runs with its own environment variables. ```powershell $processOptions = @{ FilePath = "sort.exe" RedirectStandardInput = "TestSort.txt" RedirectStandardOutput = "Sorted.txt" RedirectStandardError = "SortError.txt" UseNewEnvironment = $true } Start-Process @processOptions ``` This example uses splatting to pass parameters to the cmdlet. For more information, see [about_Splatting](../microsoft.powershell.core/about/about_splatting.md). ### Example 4: Start a process in a maximized window This example starts the `Notepad.exe` process. It maximizes the window and retains the window until the process completes. ```powershell Start-Process -FilePath "notepad" -Wait -WindowStyle Maximized ``` ### Example 5: Start PowerShell as an administrator This example starts PowerShell using the **Run as administrator** option. ```powershell Start-Process -FilePath "powershell" -Verb RunAs ``` ### Example 6: Using different verbs to start a process This example shows how to find the verbs that can be used when starting a process. The available verbs are determined by the filename extension of the file that runs in the process. ```powershell $startExe = New-Object System.Diagnostics.ProcessStartInfo -Args powershell.exe $startExe.Verbs ``` ```Output open runas runasuser ``` The example uses `New-Object` to create a **System.Diagnostics.ProcessStartInfo** object for `powershell.exe`, the file that runs in the PowerShell process. The **Verbs** property of the **ProcessStartInfo** object shows that you can use the **Open** and `RunAs` verbs with `powershell.exe`, or with any process that runs a `.exe` file. ### Example 7: Specifying arguments to the process Both commands start the Windows command interpreter, issuing a `dir` command on the `Program Files` folder. Because this foldername contains a space, the value needs surrounded with escaped quotes. Note that the first command specifies a string as **ArgumentList**. The second command is a string array. ```powershell Start-Process -FilePath "$Env:ComSpec" -ArgumentList "/c dir `"%SystemDrive%\Program Files`"" Start-Process -FilePath "$Env:ComSpec" -ArgumentList "/c","dir","`"%SystemDrive%\Program Files`"" ``` ### Example 8: Create a detached process on Linux On Windows, `Start-Process` creates an independent process that remains running independently of the launching shell. On non-Windows platforms, the newly started process is attached to the shell that launched. If the launching shell is closed, the child process is terminated. To avoid terminating the child process on Unix-like platforms, you can combine `Start-Process` with `nohup`. The following example launches a background instance of PowerShell on Linux that stays alive even after you close the launching session. The `nohup` command collects output in file `nohup.out` in the current directory. ```powershell # Runs for 2 minutes and appends output to ./nohup.out Start-Process nohup 'pwsh -NoProfile -c "1..120 | % { Write-Host . -NoNewline; sleep 1 }"' ``` In this example, `Start-Process` is running the Linux `nohup` command, which launches `pwsh` as a detached process. For more information, see the [nohup](https://wikipedia.org/wiki/Nohup) article on Wikipedia. ### Example 9: Overriding an environment variable for a process By default, when you use `Start-Process`, the new process is created with the same environment variables as the current session. You can use the **Environment** parameter to override the values of those variables. In this example, the environment variable `FOO` is added to the session with `foo` as the value. The example runs `Start-Process` three times, returning the value of `FOO` each time. The first command doesn't override the environment variable. In the second command, `FOO` is set to `bar`. In the third command, `FOO` is set to `$null`, which removes it. ```powershell $Env:FOO = 'foo' Start-Process pwsh -NoNewWindow -ArgumentList '-c', '$Env:FOO' Start-Process pwsh -NoNewWindow -ArgumentList '-c', '$Env:FOO' -Environment @{ FOO = 'bar' } Start-Process pwsh -NoNewWindow -ArgumentList '-c', '$Env:FOO' -Environment @{ FOO = $null } ``` ```Output foo bar ``` ## PARAMETERS ### -ArgumentList Specifies parameters or parameter values to use when this cmdlet starts the process. Arguments can be accepted as a single string with the arguments separated by spaces, or as an array of strings separated by commas. The cmdlet joins the array into a single string with each element of the array separated by a single space. The outer quotes of the PowerShell strings aren't included when the **ArgumentList** values are passed to the new process. If parameters or parameter values contain a space or quotes, they need to be surrounded with escaped double quotes. For more information, see [about_Quoting_Rules](../Microsoft.PowerShell.Core/About/about_Quoting_Rules.md). For the best results, use a single **ArgumentList** value containing all the arguments and any needed quote characters. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Args Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to perform this action. By default, the cmdlet uses the credentials of the current user. Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. If you type a user name, you're prompted to enter the password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: Default Aliases: RunAs Required: False Position: Named Default value: Current user Accept pipeline input: False Accept wildcard characters: False ``` ### -Environment Specifies one or more environment variables to override for the process as a hash table. Specify the name of an environment variable as a key in the hash table and the desired value. To unset an environment variable, specify its value as `$null`. The specified variables are replaced in the process. When you specify the `PATH` environment variable it's replaced with the value of `$PSHOME` followed by the specified value from this parameter. On Windows, the command appends the values for `PATH` in the Machine and User scopes after the new value. This parameter was added in PowerShell 7.4. ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FilePath Specifies the optional path and filename of the program that runs in the process. Enter the name of an executable file or of a document, such as a `.txt` or `.doc` file, that's associated with a program on the computer. This parameter is required. If you specify only a filename that does not correspond to a system command, use the **WorkingDirectory** parameter to specify the path. ```yaml Type: System.String Parameter Sets: (All) Aliases: PSPath, Path Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LoadUserProfile Indicates that this cmdlet loads the Windows user profile stored in the `HKEY_USERS` registry key for the current user. The parameter doesn't apply to non-Windows systems. This parameter doesn't affect the PowerShell profiles. For more information, see [about_Profiles](../Microsoft.PowerShell.Core/About/about_Profiles.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Default Aliases: Lup Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NoNewWindow Start the new process in the current console window. By default on Windows, PowerShell opens a new window. On non-Windows systems, you never get a new window. You can't use the **NoNewWindow** and **WindowStyle** parameters in the same command. The parameter doesn't apply to non-Windows systems. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Default Aliases: nnw Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns a process object for each process that the cmdlet started. By default, this cmdlet doesn't generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RedirectStandardError Specifies a file. This cmdlet sends any errors generated by the process to a file that you specify. Enter the path and filename. By default, the errors are displayed in the console. ```yaml Type: System.String Parameter Sets: Default Aliases: RSE Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RedirectStandardInput Specifies a file. This cmdlet reads input from the specified file. Enter the path and filename of the input file. By default, the process gets its input from the keyboard. ```yaml Type: System.String Parameter Sets: Default Aliases: RSI Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RedirectStandardOutput Specifies a file. This cmdlet sends the output generated by the process to a file that you specify. Enter the path and filename. By default, the output is displayed in the console. ```yaml Type: System.String Parameter Sets: Default Aliases: RSO Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseNewEnvironment Indicates that this cmdlet uses new environment variables specified for the process. By default, the started process runs with the environment variables inherited from the parent process. On Windows, when you use **UseNewEnvironment**, the new process starts only containing the default environment variables defined for the **Machine** scope. This has the side effect that the `$Env:USERNAME` is set to **SYSTEM**. None of the variables from the **User** scope are included. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Default Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Verb Specifies a verb to use when this cmdlet starts the process. The verbs that are available are determined by the filename extension of the file that runs in the process. The following table shows the verbs for some common process file types. | File type | Verbs | | --------- | --------------------------------------------- | | .cmd | `Edit`, `Open`, `Print`, `RunAs`, `RunAsUser` | | .exe | `Open`, `RunAs`, `RunAsUser` | | .txt | `Open`, `Print`, `PrintTo` | | .wav | `Open`, `Play` | To find the verbs that can be used with the file that runs in a process, use the `New-Object` cmdlet to create a **System.Diagnostics.ProcessStartInfo** object for the file. The available verbs are in the **Verbs** property of the **ProcessStartInfo** object. For details, see the examples. The parameter doesn't apply to non-Windows systems. ```yaml Type: System.String Parameter Sets: UseShellExecute Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Wait Indicates that this cmdlet waits for the specified process and its descendants to complete before accepting more input. This parameter suppresses the command prompt or retains the window until the processes finish. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WindowStyle Specifies the state of the window that's used for the new process. The default value is `Normal`. The acceptable values for this parameter are: - `Normal` - `Hidden` - `Minimized` - `Maximized` You can't use the **WindowStyle** and **NoNewWindow** parameters in the same command. The parameter doesn't apply to non-Windows systems. When using on non-Windows systems, you never get a new window. ```yaml Type: System.Diagnostics.ProcessWindowStyle Parameter Sets: (All) Aliases: Accepted values: Normal, Hidden, Minimized, Maximized Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WorkingDirectory Specifies the location that the new process should start in. When not specified, the cmdlet defaults to the fully-qualified location specified in the **FilePath** parameter. If the value of the **FilePath** parameter is not fully-qualified, it defaults to the current working directory of the calling process. Wildcards aren't supported. The path must not contain characters that would be interpreted as wildcards. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Diagnostics.Process When you use the **PassThru** parameter, this cmdlet returns a **Process** object. ## NOTES PowerShell includes the following aliases for `Start-Process`: - All platforms - `saps` - Windows - `start` Native commands are executable files installed in the operating system. These executables can be run from any command-line shell, like PowerShell. Usually you run the command exactly as you would in `bash` or `cmd.exe`. The `Start-Process` cmdlet can be used to run any native commands, but should only be used when you need to control how the command is executed. `Start-Process` is useful for running GUI programs on non-Windows platforms. For example, run `Start-Process gedit` to launch the graphical text editor common the GNOME Desktop environments. By default, `Start-Process` launches a process _asynchronously_. Control is instantly returned to PowerShell even if the new process is still running. - On the local system, the launched process lives on independent from the calling process. - On a remote system, the new process is terminated when the remote session ends, immediately following the `Start-Process` command. Therefore, you can't use `Start-Process` in a remote session expecting the launched process to outlive the session. If you do need to use `Start-Process` in a remote session, invoke it with the **Wait** parameter. Or you could use other methods to create a new process on the remote system. When using the **Wait** parameter, `Start-Process` waits for the process tree (the process and all its descendants) to exit before returning control. This is different than the behavior of the `Wait-Process` cmdlet, which only waits for the specified processes to exit. On Windows, the most common use case for `Start-Process` is to use the **Wait** parameter to block progress until the new process exits. On non-Windows system, this is rarely needed since the default behavior for command-line applications is equivalent to `Start-Process -Wait`. This cmdlet is implemented using the **Start** method of the **System.Diagnostics.Process** class. For more information about this method, see [Process.Start Method](/dotnet/api/system.diagnostics.process.start#overloads). ## RELATED LINKS [about_Quoting_Rules](../Microsoft.PowerShell.Core/About/about_Quoting_Rules.md) [Debug-Process](Debug-Process.md) [Get-Process](Get-Process.md) [Start-Service](Start-Service.md) [Stop-Process](Stop-Process.md) [Wait-Process](Wait-Process.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Start-Service.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 10/15/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/start-service?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Start-Service --- # Start-Service ## SYNOPSIS Starts one or more stopped services. ## SYNTAX ### InputObject (Default) ``` Start-Service [-InputObject] <ServiceController[]> [-PassThru] [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Default ``` Start-Service [-Name] <String[]> [-PassThru] [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### DisplayName ``` Start-Service [-PassThru] -DisplayName <String[]> [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Start-Service` cmdlet sends a start message to the Windows Service Controller for each of the specified services. If a service is already running, the message is ignored without error. You can specify the services by their service names or display names, or you can use the **InputObject** parameter to supply a service object that represents the services that you want to start. ## EXAMPLES ### Example 1: Start a service by using its name This example starts the EventLog service on the local computer. The **Name** parameter identifies the service by its service name. ```powershell Start-Service -Name "eventlog" ``` ### Example 2: Display information without starting a service This example shows what would occur if you started the services that have a display name that includes "remote". ```powershell Start-Service -DisplayName *remote* -WhatIf ``` The **DisplayName** parameter identifies the services by their display name instead of their service name. The **WhatIf** parameter causes the cmdlet to display what would happen when you run the command but does not make changes. ### Example 3: Start a service and record the action in a text file This example starts the Windows Management Instrumentation (WMI) service on the computer and adds a record of the action to the services.txt file. ```powershell $s = Get-Service wmi Start-Service -InputObject $s -PassThru | Format-List >> services.txt ``` First we use `Get-Service` to get an object that represent the WMI service and store it in the `$s` variable. Next, we start the service. Without the **PassThru** parameter, `Start-Service` does not create any output. The pipeline operator (`|`) passes the object output by `Start-Service` to the `Format-List` cmdlet to format the object as a list of its properties. The append redirection operator (`>>`) redirects the output to the services.txt file. The output is added to the end of the existing file. ### Example 4: Start a disabled service This example shows how to start a service when the start type of the service is **Disabled**. ``` PS> Start-Service tlntsvr Start-Service : Service 'Telnet (TlntSvr)' cannot be started due to the following error: Cannot start service TlntSvr on computer '.'. At line:1 char:14 + Start-Service <<<< tlntsvr PS> Get-CimInstance Win32_Service | Where-Object Name -EQ "tlntsvr" ExitCode : 0 Name : TlntSvr ProcessId : 0 StartMode : Disabled State : Stopped Status : OK PS> Set-Service tlntsvr -StartupType manual PS> Start-Service tlntsvr ``` The first attempt to start the Telnet service (tlntsvr) fails. The `Get-CimInstance` command shows that the **StartMode** property of the Tlntsvr service is **Disabled**. The `Set-Service` cmdlet changes the start type to **Manual**. Now, we can resubmit the `Start-Service` command. This time, the command succeeds. To verify that the command succeeded, run `Get-Service`. ## PARAMETERS ### -DisplayName Specifies the display names of the services to start. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: DisplayName Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Exclude Specifies services that this cmdlet omits. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as `s*`. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Include Specifies services that this cmdlet starts. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as `s*`. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -InputObject Specifies **ServiceController** objects representing the services to be started. Enter a variable that contains the objects, or type a command or expression that gets the objects. ```yaml Type: System.ServiceProcess.ServiceController[] Parameter Sets: InputObject Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies the service names for the service to be started. The parameter name is optional. You can use **Name** or its alias, **ServiceName**, or you can omit the parameter name. ```yaml Type: System.String[] Parameter Sets: Default Aliases: ServiceName Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -PassThru Returns an object that represents the service. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.ServiceProcess.ServiceController You can pipe a service object to this cmdlet. ### System.String You can pipe a string that contains the service name to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.ServiceProcess.ServiceController When you use the **PassThru** parameter, this cmdlet returns a **ServiceController** object representing the service. ## NOTES PowerShell includes the following aliases for `Start-Service`: - Windows: - `sasv` This cmdlet is only available on Windows platforms. - By default, only members of the Administrators group can start, stop, pause, resume, or restart a service. If you are a member of the Administrators group, you need to run `Start-Service` from an elevated PowerShell session. Use the **Run as Administrator** option to start PowerShell. - To find the service names and display names of the services on your system, type `Get-Service`. The service names appear in the **Name** column, and the display names appear in the **DisplayName** column. - You can start only the services that have a start type of Manual, Automatic, or Automatic (Delayed Start). You cannot start the services that have a start type of Disabled. If a `Start-Service` command fails with the message `Cannot start service \<service-name\> on computer`, use `Get-CimInstance` to find the start type of the service and, if you have to, use the `Set-Service` cmdlet to change the start type of the service. - Some services, such as Performance Logs and Alerts (SysmonLog) stop automatically if they have no work to do. When PowerShell starts a service that stops itself almost immediately, it displays the following message: `Service \<display-name\> start failed.` ## RELATED LINKS [Get-Service](Get-Service.md) [New-Service](New-Service.md) [Restart-Service](Restart-Service.md) [Resume-Service](Resume-Service.md) [Set-Service](Set-Service.md) [Stop-Service](Stop-Service.md) [Suspend-Service](Suspend-Service.md) [Remove-Service](Remove-Service.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Stop-Computer.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 05/07/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/stop-computer?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Stop-Computer --- # Stop-Computer ## SYNOPSIS Stops (shuts down) local and remote computers. ## SYNTAX ### All ``` Stop-Computer [-WsmanAuthentication <String>] [[-ComputerName] <String[]>] [[-Credential] <PSCredential>] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Stop-Computer` cmdlet shuts down the local computer and remote computers. You can use the parameters of `Stop-Computer` to specify the authentication levels and alternate credentials, and to force an immediate shut down. In PowerShell 7.1, `Stop-Computer` was added for Linux and macOS. The non-Windows platforms only have the **WhatIf**, **Confirm**, and **CommonParameters** parameters. The cmdlet is just calling the native command `/sbin/shutdown`. ## EXAMPLES ### Example 1: Shut down the local computer This example shuts down the local computer. ```powershell Stop-Computer -ComputerName localhost ``` ### Example 2: Shut down two remote computers and the local computer This example stops two remote computers and the local computer. ```powershell Stop-Computer -ComputerName "Server01", "Server02", "localhost" ``` `Stop-Computer` uses the **ComputerName** parameter to specify two remote computers and the local computer. Each computer is shut down. ### Example 3: Shut down remote computers as a background job In this example, `Stop-Computer` runs as a background job on two remote computers. The background operator `&` runs the `Stop-Computer` command as a background job. For more information, see [about_Operators](../microsoft.powershell.core/about/about_operators.md#background-operator-). ```powershell $j = Stop-Computer -ComputerName "Server01", "Server02" & $results = $j | Receive-Job $results ``` `Stop-Computer` uses the **ComputerName** parameter to specify two remote computers. The `&` background operator runs the command as a background job. The job objects are stored in the `$j` variable. The job objects in the `$j` variable are sent down the pipeline to `Receive-Job`, which gets the job results. The objects are stored in the `$results` variable. The `$results` variable displays the job information in the PowerShell console. ### Example 4: Shut down a remote computer This example shuts down a remote computer using specified authentication. ```powershell Stop-Computer -ComputerName "Server01" -WsmanAuthentication Kerberos ``` `Stop-Computer` uses the **ComputerName** parameter to specify the remote computer. The **WsmanAuthentication** parameter specifies to use Kerberos to establish a remote connection. ### Example 5: Shut down computers in a domain In this example, the commands force an immediate shut down of all computers in a specified domain. ```powershell $s = Get-Content -Path ./Domain01.txt $c = Get-Credential -Credential Domain01\Admin01 Stop-Computer -ComputerName $s -Force -Credential $c ``` `Get-Content` uses the **Path** parameter to get a file in the current directory with the list of domain computers. The objects are stored in the `$s` variable. `Get-Credential` uses the **Credential** parameter to specify the credentials of a domain administrator. The credentials are stored in the `$c` variable. `Stop-Computer` shuts down the computers specified with the **ComputerName** parameter's list of computers in the `$s` variable. The **Force** parameter forces an immediate shutdown. The **Credential** parameter submits the credentials saved in the `$c` variable. ## PARAMETERS ### -ComputerName Specifies the computers to stop. The default is the local computer. Type the NETBIOS name, IP address, or fully qualified domain name of one or more computers in a comma-separated list. To specify the local computer, type the computer name or localhost. This parameter doesn't rely on PowerShell remoting. You can use the **ComputerName** parameter even if your computer isn't configured to run remote commands. This parameter is only available on Windows platforms. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: CN, __SERVER, Server, IPAddress Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to do this action. The default is the current user. Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. If you type a user name, you're prompted to enter the password. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). This parameter is only available on Windows platforms. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: Current user Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Forces an immediate shut down of the computer. This parameter is only available on Windows platforms. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WsmanAuthentication Specifies the mechanism that is used to authenticate the user credentials when this cmdlet uses the WSMan protocol. The default value is **Default**. The acceptable values for this parameter are: - Basic - CredSSP - Default - Digest - Kerberos - Negotiate. For more information about the values of this parameter, see [AuthenticationMechanism](/dotnet/api/system.management.automation.runspaces.authenticationmechanism). > [!CAUTION] > Credential Security Service Provider (CredSSP) authentication, in which the user credentials are > passed to a remote computer to be authenticated, is designed for commands that require > authentication on more than one resource, such as accessing a remote network share. This mechanism > increases the security risk of the remote operation. If the remote computer is compromised, the > credentials that are passed to it can be used to control the network session. This parameter was introduced in PowerShell 3.0. This parameter is only available on Windows platforms. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: Default, Basic, Negotiate, CredSSP, Digest, Kerberos Required: False Position: Named Default value: Default Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES This cmdlet uses the [Win32Shutdown](/windows/desktop/CIMWin32Prov/win32shutdown-method-in-class-win32-operatingsystem) method of the [Win32_OperatingSystem](/windows/desktop/CIMWin32Prov/win32-operatingsystem) WMI class. This method requires the `SeShutdownPrivilege` privilege be enabled for the user account used to shutdown the machine. In PowerShell 7.1, `Stop-Computer` was added for Linux and macOS. For these platforms, the cmdlet calls the native command `/sbin/shutdown`. ## RELATED LINKS [Rename-Computer](Rename-Computer.md) [Restart-Computer](Restart-Computer.md) [Test-Connection](Test-Connection.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Stop-Process.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 01/05/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/stop-process?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Stop-Process --- # Stop-Process ## SYNOPSIS Stops one or more running processes. ## SYNTAX ### Id (Default) ``` Stop-Process [-Id] <Int32[]> [-PassThru] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Name ``` Stop-Process -Name <String[]> [-PassThru] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### InputObject ``` Stop-Process [-InputObject] <Process[]> [-PassThru] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Stop-Process` cmdlet stops one or more running processes. You can specify a process by process name or process ID (PID), or pass a process object to `Stop-Process`. `Stop-Process` works only on processes running on the local computer. On Windows Vista and later versions of the Windows operating system, to stop a process that is not owned by the current user, you must start PowerShell by using the Run as administrator option. Also, you are not prompted for confirmation unless you specify the **Confirm** parameter. ## EXAMPLES ### Example 1: Stop all instances of a process ``` PS C:\> Stop-Process -Name "notepad" ``` This command stops all instances of the Notepad process on the computer. Each instance of Notepad runs in its own process. It uses the **Name** parameter to specify the processes, all of which have the same name. If you were to use the **Id** parameter to stop the same processes, you would have to list the process IDs of each instance of Notepad. ### Example 2: Stop a specific instance of a process ```powershell PS C:\> Stop-Process -Id 3952 -Confirm -PassThru ``` ```Output Confirm Are you sure you want to perform this action? Performing operation "Stop-Process" on Target "notepad (3952)". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):y Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 41 2 996 3212 31 3952 notepad ``` This command stops a particular instance of the Notepad process. It uses the process ID, 3952, to identify the process. The **Confirm** parameter directs PowerShell to prompt you before it stops the process. Because the prompt includes the process name in addition to its ID, this is best practice. The **PassThru** parameter passes the process object to the formatter for display. Without this parameter, there would be no display after a `Stop-Process` command. ### Example 3: Stop a process and detect that it has stopped ```powershell calc $p = Get-Process -Name "calc" Stop-Process -InputObject $p Get-Process | Where-Object {$_.HasExited} ``` This series of commands starts and stops the `Calc` process, and then detects processes that have stopped. The first command starts an instance of the calculator. The second command uses `Get-Process` gets an object that represents the `Calc` process, and then stores it in the `$p` variable. The third command stops the `Calc` process. It uses the **InputObject** parameter to pass the object to `Stop-Process`. The last command gets all of the processes on the computer that were running but that are now stopped. It uses `Get-Process` to get all of the processes on the computer. The pipeline operator (`|`) passes the results to the `Where-Object` cmdlet, which selects the ones where the value of the **HasExited** property is $true. **HasExited** is just one property of process objects. To find all the properties, type `Get-Process | Get-Member`. ### Example 4: Stop a process not owned by the current user ```powershell PS> Get-Process -Name "lsass" | Stop-Process ``` ```Output Stop-Process : Cannot stop process 'lsass (596)' because of the following error: Access is denied At line:1 char:34 + Get-Process -Name "lsass" | Stop-Process <<<< ``` ```powershell [ADMIN]: PS> Get-Process -Name "lsass" | Stop-Process ``` ```Output Warning! Are you sure you want to perform this action? Performing operation 'Stop-Process' on Target 'lsass(596)' [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"): ``` ```powershell [ADMIN]: PS> Get-Process -Name "lsass" | Stop-Process -Force [ADMIN]: PS> ``` These commands show the effect of using **Force** to stop a process that is not owned by the user. The first command uses `Get-Process` to get the Lsass process. A pipeline operator sends the process to `Stop-Process` to stop it. As shown in the sample output, the first command fails with an Access denied message, because this process can be stopped only by a member of the Administrator group on the computer. When PowerShell is opened by using the Run as administrator option, and the command is repeated, PowerShell prompts you for confirmation. The second command specifies **Force** to suppress the prompt. As a result, the process is stopped without confirmation. ## PARAMETERS ### -Force Stops the specified processes without prompting for confirmation. By default, `Stop-Process` prompts for confirmation before stopping any process that is not owned by the current user. To find the owner of a process, use the `Get-CimInstance` cmdlet to get a **Win32_Process** object that represents the process, and then use the **GetOwner** method of the object. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies the process IDs of the processes to stop. To specify multiple IDs, use commas to separate the IDs. To find the PID of a process, type `Get-Process`. ```yaml Type: System.Int32[] Parameter Sets: Id Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InputObject Specifies the process objects to stop. Enter a variable that contains the objects, or type a command or expression that gets the objects. ```yaml Type: System.Diagnostics.Process[] Parameter Sets: InputObject Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies the process names of the processes to stop. You can type multiple process names, separated by commas, or use wildcard characters. ```yaml Type: System.String[] Parameter Sets: Name Aliases: ProcessName Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -PassThru Returns an object that represents the process. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Diagnostics.Process You can pipe a process object to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Diagnostics.Process When you use the **PassThru** parameter, this cmdlet returns a **Process** object representing the stopped process. ## NOTES PowerShell includes the following aliases for `Stop-Process`: - All platforms: - `spps` - Windows: - `kill` You can also use the properties and methods of the Windows Management Instrumentation (WMI) **Win32_Process** object in Windows PowerShell. For more information, see `Get-CimInstance` and the WMI SDK. - When stopping processes, realize that stopping a process can stop process and services that depend on the process. In an extreme case, stopping a process can stop Windows. ## RELATED LINKS [Debug-Process](Debug-Process.md) [Get-Process](Get-Process.md) [Start-Process](Start-Process.md) [Stop-Process](Stop-Process.md) [Wait-Process](Wait-Process.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Stop-Service.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 01/27/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/stop-service?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Stop-Service --- # Stop-Service ## SYNOPSIS Stops one or more running services. ## SYNTAX ### InputObject (Default) ``` Stop-Service [-Force] [-NoWait] [-InputObject] <ServiceController[]> [-PassThru] [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Default ``` Stop-Service [-Force] [-NoWait] [-Name] <String[]> [-PassThru] [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### DisplayName ``` Stop-Service [-Force] [-NoWait] [-PassThru] -DisplayName <String[]> [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Stop-Service` cmdlet sends a stop message to the Windows Service Controller for each of the specified services. You can specify the services by their service names or display names, or you can use the **InputObject** parameter to pass a service object that represents the service that you want to stop. ## EXAMPLES ### Example 1: Stop a service on the local computer ``` PS C:\> Stop-Service -Name "sysmonlog" ``` This command stops the Performance Logs and Alerts (SysmonLog) service on the local computer. ### Example 2: Stop a service by using the display name ``` PS C:\> Get-Service -DisplayName "telnet" | Stop-Service ``` This command stops the Telnet service on the local computer. The command uses `Get-Service` to get an object that represents the Telnet service. The pipeline operator (`|`) pipes the object to `Stop-Service`, which stops the service. ### Example 3: Stop a service that has dependent services ``` PS C:\> Get-Service -Name "iisadmin" | Format-List -Property Name, DependentServices PS C:\> Stop-Service -Name "iisadmin" -Force -Confirm ``` This example stops the IISAdmin service on the local computer. Because stopping this service also stops the services that depend on the IISAdmin service, it is best to precede `Stop-Service` with a command that lists the services that depend on the IISAdmin service. The first command lists the services that depend on IISAdmin. It uses `Get-Service` to get an object that represents the IISAdmin service. The pipeline operator (`|`) passes the result to the `Format-List` cmdlet. The command uses the **Property** parameter of `Format-List` to list only the **Name** and **DependentServices** properties of the service. The second command stops the IISAdmin service. The **Force** parameter is required to stop a service that has dependent services. The command uses the **Confirm** parameter to request confirmation from the user before it stops each service. ## PARAMETERS ### -DisplayName Specifies the display names of the services to stop. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: DisplayName Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Exclude Specifies services that this cmdlet omits. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as s*. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Forces the cmdlet to stop a service even if that service has dependent services. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies services that this cmdlet stops. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as s*. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -InputObject Specifies **ServiceController** objects that represent the services to stop. Enter a variable that contains the objects, or type a command or expression that gets the objects. ```yaml Type: System.ServiceProcess.ServiceController[] Parameter Sets: InputObject Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies the service names of the services to stop. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Default Aliases: ServiceName Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -NoWait Indicates that this cmdlet uses the no wait option. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns an object that represents the service. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.ServiceProcess.ServiceController You can pipe a service object to this cmdlet. ### System.String You can pipe a string that contains the name of a service to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.ServiceProcess.ServiceController When you use the **PassThru** parameter, this cmdlet returns a **ServiceController** object representing the service. ## NOTES PowerShell includes the following aliases for `Stop-Service`: - Windows: - `spsv` This cmdlet is only available on Windows platforms. `Stop-Service` can control services only when the current user has permission to do this. If a command does not work correctly, you might not have the required permissions. To find the service names and display names of the services on your system, type `Get-Service`. The service names appear in the **Name** column and the display names appear in the **DisplayName** column. ## RELATED LINKS [Get-Service](Get-Service.md) [New-Service](New-Service.md) [Restart-Service](Restart-Service.md) [Resume-Service](Resume-Service.md) [Set-Service](Set-Service.md) [Start-Service](Start-Service.md) [Suspend-Service](Suspend-Service.md) [Remove-Service](Remove-Service.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Suspend-Service.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/suspend-service?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Suspend-Service --- # Suspend-Service ## SYNOPSIS Suspends (pauses) one or more running services. ## SYNTAX ### InputObject (Default) ``` Suspend-Service [-InputObject] <ServiceController[]> [-PassThru] [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Default ``` Suspend-Service [-Name] <String[]> [-PassThru] [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### DisplayName ``` Suspend-Service [-PassThru] -DisplayName <String[]> [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Suspend-Service` cmdlet sends a suspend message to the Windows Service Controller for each of the specified services. While suspended, the service is still running, but its action is stopped until resumed, such as by using the `Resume-Service` cmdlet. You can specify the services by their service names or display names, or you can use the **InputObject** parameter to pass a service object that represents the services that you want to suspend. ## EXAMPLES ### Example 1: Suspend a service ``` PS C:\> Suspend-Service -DisplayName "Telnet" ``` This command suspends the Telnet service (Tlntsvr) service on the local computer. ### Example 2: Display what would happen if you suspend services ``` PS C:\> Suspend-Service -Name lanman* -WhatIf ``` This command tells what would happen if you suspended the services that have a service name that starts with lanman. To suspend the services, rerun the command without the **WhatIf** parameter. ### Example 3: Get and suspend a service ``` PS C:\> Get-Service schedule | Suspend-Service ``` This command uses the `Get-Service` cmdlet to get an object that represents the Task Scheduler (Schedule) service on the computer. The pipeline operator (`|`) passes the result to `Suspend-Service`, which suspends the service. ### Example 4: Suspend all services that can be suspended ``` PS C:\> Get-Service | Where-Object {$_.CanPauseAndContinue -eq "True"} | Suspend-Service -Confirm ``` This command suspends all of the services on the computer that can be suspended. It uses `Get-Service` to get objects that represent the services on the computer. The pipeline operator passes the results to the `Where-Object` cmdlet, which selects only the services that have a value of `$true` for the **CanPauseAndContinue** property. Another pipeline operator passes the results to `Suspend-Service`. The **Confirm** parameter prompts you for confirmation before suspending each of the services. ## PARAMETERS ### -DisplayName Specifies the display names of the services to be suspended. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: DisplayName Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Exclude Specifies services to omit from the specified services. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as "s*". Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Include Specifies services to suspend. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as "s*". Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -InputObject Specifies **ServiceController** objects that represent the services to suspend. Enter a variable that contains the objects, or type a command or expression that gets the objects. ```yaml Type: System.ServiceProcess.ServiceController[] Parameter Sets: InputObject Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies the service names of the services to suspend. Wildcard characters are permitted. The parameter name is optional. You can use **Name** or its alias, **ServiceName**, or you can omit the parameter name. ```yaml Type: System.String[] Parameter Sets: Default Aliases: ServiceName Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.ServiceProcess.ServiceController You can pipe a service object to this cmdlet. ### System.String You can pipe a string that contains a service name to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.ServiceProcess.ServiceController When you use the **PassThru** parameter, this cmdlet returns a **ServiceController** object representing the service. ## NOTES This cmdlet is only available on Windows platforms. - `Suspend-Service` can control services only when the current user has permission to do this. If a command does not work correctly, you might not have the required permissions. - `Suspend-Service` can suspend only services that support being suspended and resumed. To determine whether a particular service can be suspended, use the `Get-Service` cmdlet together with the **CanPauseAndContinue** property. For example, `Get-Service wmi | Format-List Name, CanPauseAndContinue`. To find all services on the computer that can be suspended, type `Get-Service | Where-Object {$_.CanPauseAndContinue -eq $true}`. - To find the service names and display names of the services on your system, type `Get-Service`. The service names appear in the **Name** column, and the display names appear in the **DisplayName** column. ## RELATED LINKS [Get-Service](Get-Service.md) [New-Service](New-Service.md) [Restart-Service](Restart-Service.md) [Resume-Service](Resume-Service.md) [Set-Service](Set-Service.md) [Start-Service](Start-Service.md) [Stop-Service](Stop-Service.md) [Remove-Service](Remove-Service.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Test-Connection.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 01/18/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/test-connection?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Test-Connection --- # Test-Connection ## SYNOPSIS Sends ICMP echo request packets, or pings, to one or more computers. ## SYNTAX ### DefaultPing (Default) ``` Test-Connection [-TargetName] <string[]> [-Ping] [-IPv4] [-IPv6] [-ResolveDestination] [-Source <string>] [-MaxHops <int>] [-Count <int>] [-Delay <int>] [-BufferSize <int>] [-DontFragment] [-Quiet] [-TimeoutSeconds <int>] [<CommonParameters>] ``` ### RepeatPing ``` Test-Connection [-TargetName] <string[]> -Repeat [-Ping] [-IPv4] [-IPv6] [-ResolveDestination] [-Source <string>] [-MaxHops <int>] [-Delay <int>] [-BufferSize <int>] [-DontFragment] [-Quiet] [-TimeoutSeconds <int>] [<CommonParameters>] ``` ### TraceRoute ``` Test-Connection [-TargetName] <string[]> -Traceroute [-IPv4] [-IPv6] [-ResolveDestination] [-Source <string>] [-MaxHops <int>] [-Quiet] [-TimeoutSeconds <int>] [<CommonParameters>] ``` ### MtuSizeDetect ``` Test-Connection [-TargetName] <string[]> -MtuSize [-IPv4] [-IPv6] [-ResolveDestination] [-Quiet] [-TimeoutSeconds <int>] [<CommonParameters>] ``` ### TcpPort ``` Test-Connection [-TargetName] <string[]> -TcpPort <int> [-IPv4] [-IPv6] [-ResolveDestination] [-Source <string>] [-Count <int>] [-Delay <int>] [-Repeat] [-Quiet] [-TimeoutSeconds <int>] [-Detailed] [<CommonParameters>] ``` ## DESCRIPTION The `Test-Connection` cmdlet sends Internet Control Message Protocol (ICMP) echo request packets, or pings, to one or more remote computers and returns the echo response replies. You can use this cmdlet to determine whether a particular computer can be contacted across an IP network. You can use the parameters of `Test-Connection` to specify both the sending and receiving computers, to run the command as a background job, to set a time-out and number of pings, and to configure the connection and authentication. Unlike the familiar **ping** command, `Test-Connection` returns a **TestConnectionCommand+PingStatus** object that you can investigate in PowerShell. The **Quiet** parameter returns a **Boolean** value in a **System.Boolean** object for each tested connection. If multiple connections are tested, an array of **Boolean** values is returned. ## EXAMPLES ### Example 1: Send echo requests to a remote computer This example sends echo request packets from the local computer to the Server01 computer. ```powershell Test-Connection -TargetName Server01 -IPv4 ``` ```Output Destination: Server01 Ping Source Address Latency BufferSize Status (ms) (B) ---- ------ ------- ------- ---------- ------ 1 ADMIN1 10.59.137.44 24 32 Success 2 ADMIN1 10.59.137.44 39 32 Success 3 ADMIN1 * * * TimedOut 4 ADMIN1 10.59.137.44 28 32 Success ``` `Test-Connection` uses the **TargetName** parameter to specify the Server01 computer. The **IPv4** parameter specifies the protocol for the test. A series of **TestConnectionCommand+PingStatus** objects are sent to the output stream, one object per ping reply from the target machine. ### Example 2: Send echo requests to several computers This example sends pings from the local computer to several remote computers. ```powershell Test-Connection -TargetName Server01, Server02, Server12 ``` ### Example 3: Use parameters to customize the test command This example uses the parameters of `Test-Connection` to customize the command. The local computer sends a ping test to a remote computer. ```powershell Test-Connection -TargetName Server01 -Count 3 -Delay 2 -MaxHops 255 -BufferSize 256 ``` `Test-Connection` uses the **TargetName** parameter to specify Server01. The **Count** parameter specifies three pings are sent to the Server01 computer with a **Delay** of 2-second intervals. You might use these options when the ping response is expected to take longer than usual, either because of an extended number of hops or a high-traffic network condition. ### Example 4: Run a test as a background job This example shows how to run a `Test-Connection` command as a PowerShell background job. ```powershell $job = Start-Job -ScriptBlock { Test-Connection -TargetName (Get-Content -Path "Servers.txt") } $Results = Receive-Job $job -Wait ``` The `Start-Job` command uses the `Test-Connection` cmdlet to ping many computers in an enterprise. The value of the **TargetName** parameter is a `Get-Content` command that reads a list of computer names from the `Servers.txt` file. The command uses the `Start-Job` cmdlet to run the command as a background job and it saves the job in the `$job` variable. The `Receive-Job` command is instructed to `-Wait` until the job is completed, and then gets the results and stores them in the `$Results` variable. ### Example 5: Create a session only if a connection test succeeds This example creates a session on the Server01 computer only if at least one of the pings sent to the computer succeeds. ```powershell if (Test-Connection -TargetName Server01 -Quiet) { New-PSSession -ComputerName Server01 } ``` The `Test-Connection` cmdlet pings the `Server01` computer, with the **Quiet** parameter provided. The resulting value is `$true` if any of the four pings succeed. If none of the pings succeed, the value is `$false`. If the `Test-Connection` command returns a value of `$true`, the command uses the `New-PSSession` cmdlet to create the **PSSession**. ### Example 6: Use the Traceroute parameter Introduced in PowerShell 6.0, the **Traceroute** parameter maps a route between the local computer and the remote destination you specify with the **TargetName** parameter. ```powershell Test-Connection -TargetName www.google.com -Traceroute ``` ```Output Target: google.com Hop Hostname Ping Latency Status Source TargetAddress (ms) --- -------- ---- ------- ------ ------ ------------- 1 172.20.0.1 1 4 Success Lira 172.217.9.174 1 172.20.0.1 2 3 Success Lira 172.217.9.174 1 172.20.0.1 3 2 Success Lira 172.217.9.174 2 12.108.153.193 1 3 Success Lira 172.217.9.174 2 12.108.153.193 2 3 Success Lira 172.217.9.174 2 12.108.153.193 3 2 Success Lira 172.217.9.174 3 12.244.85.177 1 11 Success Lira 172.217.9.174 3 12.244.85.177 2 12 Success Lira 172.217.9.174 3 12.244.85.177 3 12 Success Lira 172.217.9.174 4 * 1 14 DestinationNetw… Lira 172.217.9.174 4 * 2 * TimedOut Lira 172.217.9.174 4 * 3 20 DestinationNetw… Lira 172.217.9.174 5 * 1 * TimedOut Lira 172.217.9.174 5 * 2 15 DestinationNetw… Lira 172.217.9.174 5 * 3 * TimedOut Lira 172.217.9.174 6 * 1 18 DestinationNetw… Lira 172.217.9.174 6 * 2 * TimedOut Lira 172.217.9.174 6 * 3 16 DestinationNetw… Lira 172.217.9.174 7 * 1 * TimedOut Lira 172.217.9.174 7 * 2 * TimedOut Lira 172.217.9.174 7 * 3 * TimedOut Lira 172.217.9.174 8 * 1 * TimedOut Lira 172.217.9.174 8 * 2 * TimedOut Lira 172.217.9.174 8 * 3 * TimedOut Lira 172.217.9.174 9 * 1 * TimedOut Lira 172.217.9.174 9 * 2 * TimedOut Lira 172.217.9.174 9 * 3 * TimedOut Lira 172.217.9.174 10 * 1 * TimedOut Lira 172.217.9.174 10 * 2 * TimedOut Lira 172.217.9.174 10 * 3 * TimedOut Lira 172.217.9.174 11 172.217.9.174 1 23 Success Lira 172.217.9.174 11 172.217.9.174 2 21 Success Lira 172.217.9.174 11 172.217.9.174 3 22 Success Lira 172.217.9.174 ``` The `Test-Connection` command is called with the **Traceroute** parameter. The results, which are `[Microsoft.PowerShell.Commands.TestConnectionCommand+TraceStatus]` objects, are output to the **Success** output stream. ### Example 7: Get detailed output for a TCP connection test When you use the **Detailed** parameter, this cmdlet returns a detailed information about the status of the TCP connection attempts. ```powershell Test-Connection bing.com -TCPPort 443 -Detailed -Count 4 ``` ```Output Target: bing.com Id Source Address Port Latency(ms) Connected Status -- ------ ------- ---- ----------- --------- ------ 1 circumflex 2620:1ec:c11::200 443 12 True Success 2 circumflex 2620:1ec:c11::200 443 14 True Success 3 circumflex 2620:1ec:c11::200 443 17 True Success 4 circumflex 2620:1ec:c11::200 443 17 True Success ``` ## PARAMETERS ### -BufferSize Specifies the size, in bytes, of the buffer sent with this command. The default value is 32. ```yaml Type: System.Int32 Parameter Sets: DefaultPing, RepeatPing Aliases: Size, Bytes, BS Required: False Position: Named Default value: 32 Accept pipeline input: False Accept wildcard characters: False ``` ### -Count Specifies the number of echo requests to send. The default value is 4. ```yaml Type: System.Int32 Parameter Sets: DefaultPing, TcpPort Aliases: Required: False Position: Named Default value: 4 Accept pipeline input: False Accept wildcard characters: False ``` ### -Delay Specifies the interval between pings, in seconds. ```yaml Type: System.Int32 Parameter Sets: DefaultPing, RepeatPing, TcpPort Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Detailed When you use the **Detailed** parameter, this cmdlet returns a detailed information about the status of the TCP connection attempts. This parameter was added in PowerShell 7.4. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: TcpPort Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -DontFragment This parameter sets the **Don't Fragment** flag in the IP header. You can use this parameter with the **BufferSize** parameter to test the Path MTU size. For more information about Path MTU, see the [Path MTU Discovery](https://wikipedia.org/wiki/Path_MTU_Discovery) article in wikipedia. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: DefaultPing, RepeatPing Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -IPv4 Forces the cmdlet to use the IPv4 protocol for the test. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -IPv6 Forces the cmdlet to use the IPv6 protocol for the test. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -MaxHops Sets the maximum number of hops that an ICMP request message can be sent. The default value is controlled by the operating system. The default value for Windows 10 and higher is 128 hops. ```yaml Type: System.Int32 Parameter Sets: DefaultPing, RepeatPing, TraceRoute Aliases: Ttl, TimeToLive, Hops Required: False Position: Named Default value: 128 Accept pipeline input: False Accept wildcard characters: False ``` ### -MtuSize This parameter is used to discover the Path MTU size. The cmdlet returns a **PingReply#MTUSize** object that contains the Path MTU size to the target. For more information about Path MTU, see the [Path MTU Discovery](https://wikipedia.org/wiki/Path_MTU_Discovery) article in wikipedia. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: MtuSizeDetect Aliases: MtuSizeDetect Required: True Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Ping Causes the cmdlet to do a ping test. This is the default mode for the `Test-Connection` cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: DefaultPing, RepeatPing Aliases: Required: False Position: Named Default value: True Accept pipeline input: False Accept wildcard characters: False ``` ### -Quiet The **Quiet** parameter returns a **Boolean** value. Using this parameter suppresses all errors. Each connection that's tested returns a **Boolean** value. If the **TargetName** parameter specifies multiple computers, an array of **Boolean** values is returned. If **any** ping to a given target succeeds, `$true` is returned. If **all** pings to a given target fail, `$false` is returned. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Repeat Causes the cmdlet to send ping requests continuously. When the value of **TargetName** is an array of targets, the cmdlet repeats the ping requests for the first target only. It ignores the remaining targets. This parameter can't be used with the **Count** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: RepeatPing, TcpPort Aliases: Continuous Required: True (RepeatPing), False (TcpPort) Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ResolveDestination Causes the cmdlet to attempt to resolve the DNS name of the target. When used in conjunction with the **Traceroute** parameter, the DNS names of all intermediate hosts will also be retrieved, if possible. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Source Specifies the names of the computers where the ping originates. Enter a comma-separated list of computer names. The default is the local computer. > [!NOTE] > This parameter is not supported in PowerShell versions 6 and up. Supplying this parameter > causes an error. ```yaml Type: System.String Parameter Sets: DefaultPing, RepeatPing, TraceRoute, TcpPort Aliases: Required: False Position: Named Default value: Local computer Accept pipeline input: False Accept wildcard characters: False ``` ### -TargetName Specifies the computer(s) to test. Type the computer names or type IP addresses in IPv4 or IPv6 format. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: ComputerName Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -TcpPort Specifies the TCP port number on the target to be used in the TCP connection test. The cmdlet attempts to make a TCP connection to the specified port on the target. - The cmdlet returns `$true` if a connection is made. - The cmdlet returns `$false` if a connection is not made. ```yaml Type: System.Int32 Parameter Sets: TcpPort Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TimeoutSeconds Sets the timeout value for the test. The test fails if a response isn't received before the timeout expires. The default is five seconds. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 5 seconds Accept pipeline input: False Accept wildcard characters: False ``` ### -Traceroute Causes the cmdlet to do a traceroute test. When this parameter is used, the cmdlet returns a `TestConnectionCommand+TraceStatus` object. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: TraceRoute Aliases: Required: True Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.TestConnectionCommand+PingStatus By default, this cmdlet returns a **TestConnectionCommand+PingStatus** object for each ping reply. ### Microsoft.PowerShell.Commands.TestConnectionCommand+TraceStatus When you use the **Traceroute** parameter, this cmdlet returns a **TestConnectionCommand+TraceStatus** object for each ping reply along the route. ### System.Boolean When you use the **Quiet** or **TcpPort** parameters, this cmdlet returns a **Boolean** value. If the cmdlet tests multiple connections, it returns an array of **Boolean** values. ### Microsoft.PowerShell.Commands.TestConnectionCommand+PingMtuStatus When you use the **MtuSize** parameter, this cmdlet returns a **TestConnectionCommand+PingMtuStatus** object for each ping reply. ### Microsoft.PowerShell.Commands.TestConnectionCommand+TcpPortStatus When you use the **Detailed** parameter, this cmdlet returns a **TestConnectionCommand+TcpPortStatus** object that shows the status of the TCP connection. ## NOTES On Linux, using the **BufferSize** parameter or any combination of parameters with the **MtuSize** parameter set that results in a non-default buffer size of 32 bytes may require `sudo`. In those cases, `Test-Command` raises an exception with a message indicating that `sudo` is required. ## RELATED LINKS [Restart-Computer](Restart-Computer.md) [Stop-Computer](Stop-Computer.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Test-Path.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 03/20/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/test-path?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Test-Path --- # Test-Path ## SYNOPSIS Determines whether all elements of a path exist. ## SYNTAX ### Path (Default) - FileSystem provider ``` Test-Path [-Path] <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-PathType <TestPathType>] [-IsValid] [-Credential <PSCredential>] [-OlderThan <DateTime>] [-NewerThan <DateTime>] [<CommonParameters>] ``` ### LiteralPath - FileSystem provider ``` Test-Path -LiteralPath <String[]> [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-PathType <TestPathType>] [-IsValid] [-Credential <PSCredential>] [-OlderThan <DateTime>] [-NewerThan <DateTime>] [<CommonParameters>] ``` ### Path (Default) - All providers ``` Test-Path [-Path] <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-PathType <TestPathType>] [-IsValid] [-Credential <pscredential>] [<CommonParameters>] ``` ### LiteralPath - All providers ``` Test-Path -LiteralPath <string[]> [-Filter <string>] [-Include <string[]>] [-Exclude <string[]>] [-PathType <TestPathType>] [-IsValid] [-Credential <pscredential>] [<CommonParameters>] ``` ## DESCRIPTION The `Test-Path` cmdlet determines whether all elements of the path exist. It returns `$true` if all elements exist and `$false` if any are missing. It can also tell whether the path syntax is valid and whether the path leads to a container or a terminal or leaf element. If the **Path** is a whitespace or empty string, then the cmdlet returns `$false`. If the **Path** is `$null`, an array of `$null` or an empty array, the cmdlet returns a non-terminating error. ## EXAMPLES ### Example 1: Test a path ```powershell Test-Path -Path "C:\Documents and Settings\DavidC" ``` ```Output True ``` This command checks whether all elements in the path exist, including the `C:` directory, the `Documents and Settings` directory, and the `DavidC` directory. If any are missing, the cmdlet returns `$false`. Otherwise, it returns `$true`. ### Example 2: Test the path of a profile ```powershell Test-Path -Path $PROFILE ``` ```Output False ``` ```powershell Test-Path -Path $PROFILE -IsValid ``` ```Output True ``` These commands test the path of the PowerShell profile. The first command determines whether all elements in the path exist. The second command determines whether the syntax of the path is correct. In this case, the path is `$false`, but the syntax is correct `$true`. These commands use `$PROFILE`, the automatic variable that points to the location for the profile, even if the profile doesn't exist. For more information about automatic variables, see [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md). ### Example 3: Check whether there are any files besides a specified type ```powershell Test-Path -Path "C:\CAD\Commercial Buildings\*" -Exclude *.dwg ``` ```Output False ``` This command checks whether there are any files in the Commercial Buildings directory other than .dwg files. The command uses the **Path** parameter to specify the path. Because the path includes a space, the path is enclosed in quotation marks. The asterisk at the end of the path indicates the contents of the Commercial Building directory. With long paths, such as this one, type the first few letters of the path, and then use the TAB key to complete the path. The command specifies the **Exclude** parameter to specify files to omit from the evaluation. In this case, because the directory contains only .dwg files, the result is `$false`. ### Example 4: Check for a file ```powershell Test-Path -Path $PROFILE -PathType Leaf ``` ```Output True ``` This command checks whether the path stored in the `$PROFILE` variable leads to a file. In this case, because the PowerShell profile is a `.ps1` file, the cmdlet returns `$true`. ### Example 5: Check paths in the Registry These commands use `Test-Path` with the PowerShell Registry provider. The first command tests whether the registry path of the **Microsoft.PowerShell** registry key is correct on the system. If PowerShell is installed correctly, the cmdlet returns `$true`. > [!IMPORTANT] > `Test-Path` doesn't work correctly with all PowerShell providers. For example, you can use > `Test-Path` to test the path of a registry key, but if you use it to test the path of a registry > entry, it always returns `$false`, even if the registry entry is present. ```powershell Test-Path -Path "HKLM:\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell" ``` ```Output True ``` ```powershell Test-Path -Path "HKLM:\Software\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell\ExecutionPolicy" ``` ```Output False ``` ### Example 6: Test if a file is in a date range This command uses the **NewerThan** and **OlderThan** dynamic parameters to determine whether the `pwsh.exe` file on the computer is newer than `July 13, 2009` and older than last week. The **NewerThan** and **OlderThan** parameters only work in file system drives. ```powershell Get-Command pwsh | Select-Object -ExpandProperty Path | Test-Path -NewerThan "July 13, 2009" -OlderThan (Get-Date).AddDays(-7) ``` ```Output True ``` ### Example 7: Test a path with null as the value The error returned for `null`, array of `null` or empty array is a non-terminating error. It can be suppress by using `-ErrorAction SilentlyContinue`. The following example shows all cases that return the `NullPathNotPermitted` error. ```powershell Test-Path $null Test-Path $null, $null Test-Path @() ``` ```Output Test-Path : Cannot bind argument to parameter 'Path' because it is null. At line:1 char:11 + Test-Path $null + ~~~~~ + CategoryInfo : InvalidData: (:) [Test-Path], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand ``` ### Example 8: Test a path with whitespace as the value When a whitespace string is provided for the **Path** parameter, it returns `$false`. This is a change from Windows PowerShell 5.1. When an empty string is provided, `Test-Path` returns an error. The following example shows whitespace and empty string. ```powershell Test-Path ' ' Test-Path '' ``` ```Output False False ``` ### Example 9: Test a path that may have an invalid drive When you test a path that includes a drive specification, testing the validity of the path fails if the drive doesn't exist. You can prefix the drive with the provider name to work around this problem. ```powershell Test-Path -IsValid Z:\abc.txt Test-Path -IsValid FileSystem::Z:\abc.txt ``` ```Output False True ``` ## PARAMETERS ### -Credential > [!NOTE] > This parameter isn't supported by any providers installed with PowerShell. To impersonate another > user, or elevate your credentials when running this cmdlet, use > [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Exclude Specifies items that this cmdlet omits. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter in the format or language of the provider. The value of this parameter qualifies the **Path** parameter. The syntax of the filter, including the use of wildcard characters, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when it retrieves the objects instead of having PowerShell filter the objects after they're retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Include Specifies paths that this cmdlet tests. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -IsValid Indicates that this cmdlet tests the syntax of the path, regardless of whether the elements of the path exist. This cmdlet returns `$true` if the path syntax is valid and `$false` if it's not. If the path being tested includes a drive specification, the cmdlet returns false when the drive does not exist. PowerShell returns false because it doesn't know which drive provider to test. > [!NOTE] > A breaking change in the Path APIs was introduced in .NET 2.1. Those methods no longer check for > invalid path characters. This change caused a regression in PowerShell where the **IsValid** check > no longer tests for invalid characters. The regression will be addressed in a future release. For > more information, > see [Breaking changes in .NET Core 2.1](/dotnet/core/compatibility/2.1#path-apis-dont-throw-an-exception-for-invalid-characters). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies a path to be tested. Unlike **Path**, the value of the **LiteralPath** parameter is used exactly as it's typed. No characters are interpreted as wildcard characters. If the path includes characters that could be interpreted by PowerShell as escape sequences, you must enclose the path in single quote so that they won't be interpreted. ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -NewerThan This is a dynamic parameter made available by the **FileSystem** provider. Specify a time as a **DateTime** object. Before PowerShell 7.5, the cmdlet ignores: - This parameter when you specify **PathType** as any value other than `Any`. - The **OlderThan** parameter when used with this parameter. - This parameter when **Path** points to a directory. Starting with PowerShell 7.5, you can use this parameter with any value for the **PathType** parameter, to test a date range with the **OlderThan** parameter, and to test the age of directories. For more information, see [about_FileSystem_Provider](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md). ```yaml Type: System.Nullable`1[[System.DateTime]] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OlderThan This is a dynamic parameter made available by the **FileSystem** provider. Specify a time as a **DateTime** object. Before PowerShell 7.5, the cmdlet ignores: - This parameter when you specify **PathType** as any value other than `Any`. - This parameter when used with the **NewerThan** parameter. - This parameter when **Path** points to a directory. Starting with PowerShell 7.5, you can use this parameter with any value for the **PathType** parameter, to test a date range with the **NewerThan** parameter, and to test the age of directories. For more information, see [about_FileSystem_Provider](../Microsoft.PowerShell.Core/About/about_FileSystem_Provider.md). ```yaml Type: System.Nullable`1[[System.DateTime]] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies a path to be tested. Wildcard characters are permitted. If the path includes spaces, enclose it in quotation marks. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -PathType Specifies the type of the final element in the path. This cmdlet returns `$true` if the element is of the specified type and `$false` if it's not. The acceptable values for this parameter are: - `Container` - An element that contains other elements, such as a directory or registry key. - `Leaf` - An element that doesn't contain other elements, such as a file. - `Any` - Either a container or a leaf. Tells whether the final element in the path is of a particular type. > [!CAUTION] > > Up to PowerShell version 6.1.2, when the **IsValid** and **PathType** switches are specified > together, the `Test-Path` cmdlet ignores the **PathType** switch and only validates the syntactic > path without validating the path type. > > According to [issue #8607](https://github.com/PowerShell/PowerShell/issues/8607), fixing this > behavior may be a breaking change in a future version, where the **IsValid** and **PathType** > switches belong to separate parameter sets, and thus, can't be used together avoiding this > confusion. ```yaml Type: Microsoft.PowerShell.Commands.TestPathType Parameter Sets: (All) Aliases: Type Accepted values: Any, Container, Leaf Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string that contains a path, but not a literal path, to this cmdlet. ## OUTPUTS ### System.Boolean The cmdlet returns a **Boolean** value. ## NOTES The cmdlets that contain the **Path** noun (the **Path** cmdlets) work with path and return the names in a concise format that all PowerShell providers can interpret. They're designed for use in programs and scripts where you want to display all or part of a path in a particular format. Use them as you would use **Dirname**, **Normpath**, **Realpath**, **Join**, or other path manipulators. The `Test-Path` is designed to work with the data exposed by any provider. To list the providers available in your session, type `Get-PSProvider`. For more information, see [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md). ## RELATED LINKS [Convert-Path](Convert-Path.md) [Join-Path](Join-Path.md) [Resolve-Path](Resolve-Path.md) [Split-Path](Split-Path.md)

#File: reference/7.6/Microsoft.PowerShell.Management/Wait-Process.md

--- external help file: Microsoft.PowerShell.Commands.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Management ms.date: 08/18/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.management/wait-process?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Wait-Process --- # Wait-Process ## SYNOPSIS Waits for the processes to be stopped before accepting more input. ## SYNTAX ### Name (Default) ``` Wait-Process [-Name] <String[]> [[-Timeout] <Int32>] [-Any] [-PassThru] [<CommonParameters>] ``` ### Id ``` Wait-Process [-Id] <Int32[]> [[-Timeout] <Int32>] [-Any] [-PassThru] [<CommonParameters>] ``` ### InputObject ``` Wait-Process [[-Timeout] <Int32>] [-Any] [-PassThru] -InputObject <Process[]> [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet doesn't work on Linux or macOS.** The `Wait-Process` cmdlet waits for one or more running processes to be stopped before accepting input. In the PowerShell console, this cmdlet suppresses the command prompt until the processes are stopped. You can specify a process by process name or process ID (PID), or pipe a process object to `Wait-Process`. `Wait-Process` works only on processes running on the local computer. ## EXAMPLES ### Example 1: Stop a process and wait This example stops the **Notepad** process and then waits for the process to be stopped before it continues with the next command. ```powershell $nid = (Get-Process notepad).Id Stop-Process -Id $nid Wait-Process -Id $nid ``` The `Get-Process` cmdlet gets the process ID of the **Notepad** process and stores it in the `$nid` variable. `Stop-Process` stops the process with the ID stored in `$nid`. `Wait-Process` waits until the **Notepad** process is stopped. ### Example 2: Specifying a process This example shows three different methods of specifying a process to `Wait-Process`. The first command gets the Notepad process and stores it in the `$p` variable. The second command uses the **Id** parameter, the third command uses the **Name** parameter, and the fourth command uses the **InputObject** parameter. ```powershell $p = Get-Process notepad Wait-Process -Id $p.Id Wait-Process -Name "notepad" Wait-Process -InputObject $p ``` These commands have the same results and can be used interchangeably. ### Example 3: Wait for processes for a specified time In this example, `Wait-Process` waits 30 seconds for the **Outlook** and **Winword** processes to stop. If both processes are not stopped, the cmdlet displays a non-terminating error and the command prompt. ```powershell Wait-Process -Name outlook, winword -Timeout 30 ``` ## PARAMETERS ### -Any When multiple processes are passed into `Wait-Process`, the cmdlet waits for all processes to exit before returning. With this parameter, the cmdlet returns when any of the processes exits. The remaining processes continue to run. This parameter was added in PowerShell 7.4. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies the process IDs of the processes. To specify multiple IDs, use commas to separate the IDs. To find the PID of a process, type `Get-Process`. ```yaml Type: System.Int32[] Parameter Sets: Id Aliases: PID, ProcessId Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -InputObject Specifies the processes by submitting process objects. Enter a variable that contains the process objects, or type a command or expression that gets the process objects, such as the `Get-Process` cmdlet. ```yaml Type: System.Diagnostics.Process[] Parameter Sets: InputObject Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies the process names of the processes. To specify multiple names, use commas to separate the names. Wildcard characters are not supported. ```yaml Type: System.String[] Parameter Sets: Name Aliases: ProcessName Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru By default, this cmdlet doesn't output anything. With this parameter, the cmdlet returns objects representing the processes that were waited on. This parameter was added in PowerShell 7.4. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Timeout Specifies the maximum time, in seconds, that this cmdlet waits for the specified processes to stop. When this interval expires, the command displays a non-terminating error that lists the processes that are still running, and ends the wait. By default, there is no time-out. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: TimeoutSec Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Diagnostics.Process You can pipe a process object to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Diagnostics.Process The cmdlet returns process objects when you use the **PassThru** parameter. ## NOTES - This cmdlet uses the **WaitForExit** method of the **System.Diagnostics.Process** class. - Unlike `Start-Process -Wait`, `Wait-Process` only waits for the processes identified. `Start-Process -Wait` waits for the process tree (the process and all its descendants) to exit before returning control. ## RELATED LINKS [Debug-Process](Debug-Process.md) [Get-Process](Get-Process.md) [Start-Process](Start-Process.md) [Stop-Process](Stop-Process.md) [Wait-Process](Wait-Process.md)

#File: reference/7.6/Microsoft.PowerShell.Security/ConvertFrom-SecureString.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/convertfrom-securestring?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: ConvertFrom-SecureString --- # ConvertFrom-SecureString ## SYNOPSIS Converts a secure string to an encrypted standard string. ## SYNTAX ### Secure (Default) ``` ConvertFrom-SecureString [-SecureString] <SecureString> [[-SecureKey] <SecureString>] [<CommonParameters>] ``` ### AsPlainText ``` ConvertFrom-SecureString [-SecureString] <SecureString> [-AsPlainText] [<CommonParameters>] ``` ### Open ``` ConvertFrom-SecureString [-SecureString] <SecureString> [-Key <Byte[]>] [<CommonParameters>] ``` ## DESCRIPTION The `ConvertFrom-SecureString` cmdlet converts a secure string (**System.Security.SecureString**) into an encrypted standard string (**System.String**). Unlike a secure string, an encrypted standard string can be saved in a file for later use. The encrypted standard string can be converted back to its secure string format by using the `ConvertTo-SecureString` cmdlet. If an encryption key is specified by using the **Key** or **SecureKey** parameters, the Advanced Encryption Standard (AES) encryption algorithm is used. The specified key must have a length of 128, 192, or 256 bits because those are the key lengths supported by the AES encryption algorithm. If no key is specified, the Windows Data Protection API (DPAPI) is used to encrypt the standard string representation. > [!NOTE] > Note that per [DotNet](/dotnet/api/system.security.securestring?view=netcore-2.1#remarks), the > contents of a SecureString are not encrypted on non-Windows systems. ## EXAMPLES ### Example 1: Create a secure string ```powershell $SecureString = Read-Host -AsSecureString ``` This command creates a secure string from characters that you type at the command prompt. After entering the command, type the string you want to store as a secure string. An asterisk (`*`) is displayed to represent each character that you type. ### Example 2: Convert a secure string to an encrypted standard string ```powershell $StandardString = ConvertFrom-SecureString $SecureString ``` This command converts the secure string in the `$SecureString` variable to an encrypted standard string. The resulting encrypted standard string is stored in the `$StandardString` variable. ### Example 3: Convert a secure string to an encrypted standard string with a 192-bit key ```powershell $Key = (3,4,2,3,56,34,254,222,1,1,2,23,42,54,33,233,1,34,2,7,6,5,35,43) $StandardString = ConvertFrom-SecureString $SecureString -Key $Key ``` These commands use the Advanced Encryption Standard (AES) algorithm to convert the secure string stored in the `$SecureString` variable to an encrypted standard string with a 192-bit key. The resulting encrypted standard string is stored in the `$StandardString` variable. The first command stores a key in the `$Key` variable. The key is an array of 24 decimal numerals, each of which must be less than 256 to fit within a single unsigned byte. Because each decimal numeral represents a single byte (8 bits), the key has 24 digits for a total of 192 bits (8 x 24). This is a valid key length for the AES algorithm. The second command uses the key in the `$Key` variable to convert the secure string to an encrypted standard string. ### Example 4: Convert a secure string directly to a plaintext string ```powershell $secureString = ConvertTo-SecureString -String 'Example' -AsPlainText $secureString # 'System.Security.SecureString' ConvertFrom-SecureString -SecureString $secureString -AsPlainText # 'Example' ``` ## PARAMETERS ### -AsPlainText When set, `ConvertFrom-SecureString` will convert secure strings to the decrypted plaintext string as output. This parameter was added in PowerShell 7.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: AsPlainText Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Key Specifies the encryption key as a byte array. ```yaml Type: System.Byte[] Parameter Sets: Open Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SecureKey Specifies the encryption key as a secure string. The secure string value is converted to a byte array before being used as the key. ```yaml Type: System.Security.SecureString Parameter Sets: Secure Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SecureString Specifies the secure string to convert to an encrypted standard string. ```yaml Type: System.Security.SecureString Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Security.SecureString You can pipe a **SecureString** object to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns the created plain text string. ## NOTES - To create a secure string from characters that are typed at the command prompt, use the **AsSecureString** parameter of the `Read-Host` cmdlet. - When you use the **Key** or **SecureKey** parameters to specify a key, the key length must be correct. For example, a key of 128 bits can be specified as a byte array of 16 decimal numerals. Similarly, 192-bit and 256-bit keys correspond to byte arrays of 24 and 32 decimal numerals, respectively. - Some characters, such as emoticons, correspond to several code points in the string that contains them. Avoid using these characters because they may cause problems and misunderstandings when used in a password. ## RELATED LINKS [ConvertTo-SecureString](ConvertTo-SecureString.md) [Read-Host](../Microsoft.PowerShell.Utility/Read-Host.md)

#File: reference/7.6/Microsoft.PowerShell.Security/ConvertTo-SecureString.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/convertto-securestring?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: ConvertTo-SecureString --- # ConvertTo-SecureString ## SYNOPSIS Converts plain text or encrypted strings to secure strings. ## SYNTAX ### Secure (Default) ``` ConvertTo-SecureString [-String] <String> [[-SecureKey] <SecureString>] [<CommonParameters>] ``` ### PlainText ``` ConvertTo-SecureString [-String] <String> [-AsPlainText] [-Force] [<CommonParameters>] ``` ### Open ``` ConvertTo-SecureString [-String] <String> [-Key <Byte[]>] [<CommonParameters>] ``` ## DESCRIPTION The `ConvertTo-SecureString` cmdlet converts encrypted standard strings into secure strings. It can also convert plain text to secure strings. It is used with `ConvertFrom-SecureString` and `Read-Host`. The secure string created by the cmdlet can be used with cmdlets or functions that require a parameter of type **SecureString**. The secure string can be converted back to an encrypted, standard string using the `ConvertFrom-SecureString` cmdlet. This enables it to be stored in a file for later use. If the standard string being converted was encrypted with `ConvertFrom-SecureString` using a specified key, that same key must be provided as the value of the **Key** or **SecureKey** parameter of the `ConvertTo-SecureString` cmdlet. > [!NOTE] > Note that per [DotNet](/dotnet/api/system.security.securestring#remarks), the > contents of a SecureString are not encrypted on non-Windows systems. ## EXAMPLES ### Example 1: Convert a secure string to an encrypted string This example shows how to create a secure string from user input, convert the secure string to an encrypted standard string, and then convert the encrypted standard string back to a secure string. ```powershell PS C:\> $Secure = Read-Host -AsSecureString PS C:\> $Secure System.Security.SecureString PS C:\> $Encrypted = ConvertFrom-SecureString -SecureString $Secure PS C:\> $Encrypted 01000000d08c9ddf0115d1118c7a00c04fc297eb010000001a114d45b8dd3f4aa11ad7c0abdae98000000000 02000000000003660000a8000000100000005df63cea84bfb7d70bd6842e7efa79820000000004800000a000 000010000000f10cd0f4a99a8d5814d94e0687d7430b100000008bf11f1960158405b2779613e9352c6d1400 0000e6b7bf46a9d485ff211b9b2a2df3bd6eb67aae41 PS C:\> $Secure2 = ConvertTo-SecureString -String $Encrypted PS C:\> $Secure2 System.Security.SecureString ``` The first command uses the **AsSecureString** parameter of the `Read-Host` cmdlet to create a secure string. After you enter the command, any characters that you type are converted into a secure string and then saved in the `$Secure` variable. The second command displays the contents of the `$Secure` variable. Because the `$Secure` variable contains a secure string, PowerShell displays only the **System.Security.SecureString** type. The third command uses the `ConvertFrom-SecureString` cmdlet to convert the secure string in the `$Secure` variable into an encrypted standard string. It saves the result in the `$Encrypted` variable. The fourth command displays the encrypted string in the value of the `$Encrypted` variable. The fifth command uses the `ConvertTo-SecureString` cmdlet to convert the encrypted standard string in the `$Encrypted` variable back into a secure string. It saves the result in the `$Secure2` variable. The sixth command displays the value of the `$Secure2` variable. The SecureString type indicates that the command was successful. ### Example 2: Create a secure string from an encrypted string in a file This example shows how to create a secure string from an encrypted standard string that is saved in a file. ```powershell $Secure = Read-Host -AsSecureString $Encrypted = ConvertFrom-SecureString -SecureString $Secure -Key (1..16) $Encrypted | Set-Content Encrypted.txt $Secure2 = Get-Content Encrypted.txt | ConvertTo-SecureString -Key (1..16) ``` The first command uses the **AsSecureString** parameter of the `Read-Host` cmdlet to create a secure string. After you enter the command, any characters that you type are converted into a secure string and then saved in the `$Secure` variable. The second command uses the `ConvertFrom-SecureString` cmdlet to convert the secure string in the `$Secure` variable into an encrypted standard string by using the specified key. The contents are saved in the `$Encrypted` variable. The third command uses a pipeline operator (`|`) to send the value of the `$Encrypted` variable to the `Set-Content` cmdlet, which saves the value in the Encrypted.txt file. The fourth command uses the `Get-Content` cmdlet to get the encrypted standard string in the Encrypted.txt file. The command uses a pipeline operator to send the encrypted string to the `ConvertTo-SecureString` cmdlet, which converts it to a secure string by using the specified key. The results are saved in the `$Secure2` variable. ### Example 3: Convert a plain text string to a secure string This command converts the plain text string `P@ssW0rD!` into a secure string and stores the result in the `$Secure_String_Pwd` variable. Starting in PowerShell 7, the **Force** parameter is not required when using the **AsPlainText** parameter. However, including the **Force** parameter ensures the statement is compatible with earlier versions. ```powershell $Secure_String_Pwd = ConvertTo-SecureString "P@ssW0rD!" -AsPlainText -Force ``` > [!CAUTION] > You should avoid using plain text strings in script or from the command line. The plain text can > show up in event logs and command history logs. ## PARAMETERS ### -AsPlainText Specifies a plain text string to convert to a secure string. The secure string cmdlets help protect confidential text. The text is encrypted for privacy and is deleted from computer memory after it is used. If you use this parameter to provide plain text as input, the system cannot protect that input in this manner. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: PlainText Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Beginning in PowerShell 7, The **Force** parameter is no longer required when using the **AsPlainText** parameter. While the parameter is not used, it was not removed to provide compatibility with earlier versions of PowerShell. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: PlainText Aliases: Required: False Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Key Specifies the encryption key used to convert the original secure string into the encrypted standard string. Valid key lengths are 16, 24 and 32 bytes. ```yaml Type: System.Byte[] Parameter Sets: Open Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SecureKey Specifies the encryption key used to convert the original secure string into the encrypted standard string. The key must be provided in the format of a secure string. The secure string will be converted to a byte array to be used as the key. Valid secure key lengths are 8, 12 and 16 code points. ```yaml Type: System.Security.SecureString Parameter Sets: Secure Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -String Specifies the string to convert to a secure string. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a standard encrypted string to this cmdlet. ## OUTPUTS ### System.Security.SecureString This cmdlet returns the created **SecureString** object. ## NOTES Some characters, such as emoticons, correspond to several code points in the string that contains them. Avoid using these characters because they may cause problems and misunderstandings when used in a password. ## RELATED LINKS [ConvertFrom-SecureString](ConvertFrom-SecureString.md) [Read-Host](../Microsoft.PowerShell.Utility/Read-Host.md)

#File: reference/7.6/Microsoft.PowerShell.Security/Get-Acl.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 01/18/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/get-acl?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Acl --- # Get-Acl ## SYNOPSIS Gets the security descriptor for a resource, such as a file or registry key. ## SYNTAX ### ByPath (Default) ``` Get-Acl [[-Path] <String[]>] [-Audit] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [<CommonParameters>] ``` ### ByInputObject ``` Get-Acl -InputObject <PSObject> [-Audit] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [<CommonParameters>] ``` ### ByLiteralPath ``` Get-Acl [-LiteralPath <String[]>] [-Audit] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Get-Acl` cmdlet gets objects that represent the security descriptor of a file or resource. The security descriptor contains the access control lists (ACLs) of the resource. The ACL specifies the permissions that users and user groups have to access the resource. Beginning in Windows PowerShell 3.0, you can use the **InputObject** parameter of `Get-Acl` to get the security descriptor of objects that do not have a path. ## EXAMPLES ### Example 1- Get an ACL for a folder This example gets the security descriptor of the `C:\Windows` directory. ```powershell Get-Acl C:\Windows ``` ### Example 2 - Get an ACL for a folder using wildcards This example gets the PowerShell path and SDDL for all of the `.log` files in the `C:\Windows` directory whose names begin with `s`. ```powershell Get-Acl C:\Windows\s*.log | Format-List -Property PSPath, Sddl ``` The command uses the `Get-Acl` cmdlet to get objects representing the security descriptors of each log file. It uses a pipeline operator (`|`) to send the results to the `Format-List` cmdlet. The command uses the **Property** parameter of `Format-List` to display only the **PSPath** and **SDDL** properties of each security descriptor object. Lists are often used in PowerShell, because long values appear truncated in tables. The **SDDL** values are valuable to system administrators, because they are simple text strings that contain all of the information in the security descriptor. As such, they are easy to pass and store, and they can be parsed when needed. ### Example 3 - Get count of Audit entries for an ACL This example gets the security descriptors of the `.log` files in the `C:\Windows` directory whose names begin with `s`. ```powershell Get-Acl C:\Windows\s*.log -Audit | ForEach-Object { $_.Audit.Count } ``` It uses the **Audit** parameter to get the audit records from the SACL in the security descriptor. Then it uses the `ForEach-Object` cmdlet to count the number of audit records associated with each file. The result is a list of numbers representing the number of audit records for each log file. ### Example 4 - Get an ACL for a registry key This example uses the `Get-Acl` cmdlet to get the security descriptor of the Control subkey (`HKLM:\SYSTEM\CurrentControlSet\Control`) of the registry. ```powershell Get-Acl -Path HKLM:\System\CurrentControlSet\Control | Format-List ``` The **Path** parameter specifies the Control subkey. The pipeline operator (`|`) passes the security descriptor that `Get-Acl` gets to the `Format-List` command, which formats the properties of the security descriptor as a list so that they are easy to read. ### Example 5 - Get an ACL using **InputObject** This example uses the **InputObject** parameter of `Get-Acl` to get the security descriptor of a storage subsystem object. ```powershell Get-Acl -InputObject (Get-StorageSubSystem -Name S087) ``` ## PARAMETERS ### -Audit Gets the audit data for the security descriptor from the system access control list (SACL). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Exclude Omits the specified items. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter in the provider's format or language. The value of this parameter qualifies the **Path** parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when getting the objects, rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Include Gets only the specified items. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -InputObject Gets the security descriptor for the specified object. Enter a variable that contains the object or a command that gets the object. You cannot pipe an object, other than a path, to `Get-Acl`. Instead, use the **InputObject** parameter explicitly in the command. This parameter is introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: ByInputObject Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to a resource. Unlike **Path**, the value of the **LiteralPath** parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. This parameter is introduced in Windows PowerShell 3.0. ```yaml Type: System.String[] Parameter Sets: ByLiteralPath Aliases: PSPath, LP Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Path Specifies the path to a resource. `Get-Acl` gets the security descriptor of the resource indicated by the path. Wildcards are permitted. If you omit the **Path** parameter, `Get-Acl` gets the security descriptor of the current directory. The parameter name ("Path") is optional. ```yaml Type: System.String[] Parameter Sets: ByPath Aliases: Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### System.Security.AccessControl.FileSecurity ### System.Security.AccessControl.DirectorySecurity ### System.Security.AccessControl.RegistrySecurity This cmdlet returns an object that represents the ACLs that it gets. The object type depends upon the ACL type. ## NOTES This cmdlet is only available on Windows platforms. By default, `Get-Acl` displays the PowerShell path to the resource (`<provider>::<resource-path>`), the owner of the resource, and "Access", a list (array) of the access control entries in the discretionary access control list (DACL) for the resource. The DACL list is controlled by the resource owner. When you format the result as a list, (`Get-Acl | Format-List`), in addition to the path, owner, and access list, PowerShell displays the following properties and property values: - **Group**: The security group of the owner. - **Audit**: A list (array) of entries in the system access control list (SACL). The SACL specifies the types of access attempts for which Windows generates audit records. - **Sddl**: The security descriptor of the resource displayed in a single text string in Security Descriptor Definition Language format. PowerShell uses the **GetSddlForm** method of security descriptors to get this data. Because `Get-Acl` is supported by the FileSystem and Registry providers, you can use `Get-Acl` to view the ACL of file system objects, such as files and directories, and registry objects, such as registry keys and entries. ## RELATED LINKS [Set-Acl](Set-Acl.md)

#File: reference/7.6/Microsoft.PowerShell.Security/Get-AuthenticodeSignature.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 01/18/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/get-authenticodesignature?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-AuthenticodeSignature --- # Get-AuthenticodeSignature ## SYNOPSIS Gets information about the Authenticode signature for a file. ## SYNTAX ### ByPath (Default) ``` Get-AuthenticodeSignature [-FilePath] <String[]> [<CommonParameters>] ``` ### ByLiteralPath ``` Get-AuthenticodeSignature -LiteralPath <String[]> [<CommonParameters>] ``` ### ByContent ``` Get-AuthenticodeSignature -SourcePathOrExtension <String[]> -Content <Byte[]> [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Get-AuthenticodeSignature` cmdlet gets information about the Authenticode signature for a file or file content as a byte array. If the file is both embedded signed and Windows catalog signed, the Windows catalog signature is used. If the file is not signed, the information is retrieved, but the fields are blank. ## EXAMPLES ### Example 1: Get the Authenticode signature for a file ```powershell Get-AuthenticodeSignature -FilePath "C:\Test\NewScript.ps1" ``` This command gets information about the Authenticode signature in the NewScript.ps1 file. It uses the **FilePath** parameter to specify the file. ### Example 2: Get the Authenticode signature for multiple files ```powershell Get-AuthenticodeSignature test.ps1, test1.ps1, sign-file.ps1, makexml.ps1 ``` This command gets information about the Authenticode signature for the four files listed at the command line. In this example, the name of the **FilePath** parameter, which is optional, is omitted. ### Example 3: Get only valid Authenticode signatures for multiple files ```powershell Get-ChildItem $PSHOME\*.* | ForEach-Object {Get-AuthenticodeSignature $_} | Where-Object {$_.Status -eq "Valid"} ``` This command lists all of the files in the `$PSHOME` directory that have a valid Authenticode signature. The `$PSHOME` automatic variable contains the path to the PowerShell installation directory. The command uses the `Get-ChildItem` cmdlet to get the files in the `$PSHOME` directory. It uses a pattern of *.* to exclude directories (although it also excludes files without a dot in the filename). The command uses a pipeline operator (`|`) to send the files in `$PSHOME` to the `ForEach-Object` cmdlet, where `Get-AuthenticodeSignature` is called for each file. The results of the `Get-AuthenticodeSignature` command are sent to a `Where-Object` command that selects only the signature objects with a status of Valid. ### Example 4: Get the Authenticode signature for a file content specified as byte array ```powershell Get-AuthenticodeSignature -Content (Get-Content foo.ps1 -AsByteStream) -SourcePathorExtension ps1 ``` This command gets information about the Authenticode signature for the content of a file. In this example, the file extension is specified along with the content of the file. ## PARAMETERS ### -Content Contents of a file as a byte array for which the Authenticode signature is retrieved. This parameter must be used with **SourcePathOrExtension** parameter. Prior to PowerShell 7.4, the contents of the file must be in Unicode (UTF-16LE) format. ```yaml Type: System.Byte[] Parameter Sets: ByContent Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -FilePath Specifies the path to the file to examine. Wildcards are permitted, but they must lead to a single file. It is not necessary to type **FilePath** at the command line when you specify a value for this parameter. ```yaml Type: System.String[] Parameter Sets: ByPath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -LiteralPath Specifies the path to the file being examined. Unlike **FilePath**, the value of the **LiteralPath** parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes an escape character, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape characters. ```yaml Type: System.String[] Parameter Sets: ByLiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -SourcePathOrExtension Path to the file or file type of the content for which the Authenticode signature is retrieved. This parameter is used with **Content** where file content is passed as a byte array. ```yaml Type: System.String[] Parameter Sets: ByContent Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string that contains a file path to this cmdlet. ## OUTPUTS ### System.Management.Automation.Signature This cmdlet returns a signature object for each signature that it gets. ## NOTES This cmdlet is only available on Windows platforms. For information about Authenticode signatures in PowerShell, see [about_Signing](../Microsoft.PowerShell.Core/About/about_Signing.md). ## RELATED LINKS [Get-ExecutionPolicy](Get-ExecutionPolicy.md) [Set-AuthenticodeSignature](Set-AuthenticodeSignature.md) [Set-ExecutionPolicy](Set-ExecutionPolicy.md) [about_Execution_Policies](../Microsoft.PowerShell.Core/About/about_Execution_Policies.md) [about_Signing](../Microsoft.PowerShell.Core/About/about_Signing.md)

#File: reference/7.6/Microsoft.PowerShell.Security/Get-CmsMessage.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 02/03/2020 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/get-cmsmessage?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-CmsMessage --- # Get-CmsMessage ## SYNOPSIS Gets content that has been encrypted by using the Cryptographic Message Syntax format. ## SYNTAX ### ByContent ``` Get-CmsMessage [-Content] <String> [<CommonParameters>] ``` ### ByPath ``` Get-CmsMessage [-Path] <String> [<CommonParameters>] ``` ### ByLiteralPath ``` Get-CmsMessage [-LiteralPath] <String> [<CommonParameters>] ``` ## DESCRIPTION The `Get-CmsMessage` cmdlet gets content that has been encrypted using the Cryptographic Message Syntax (CMS) format. The CMS cmdlets support encryption and decryption of content using the IETF format for cryptographically protecting messages, as documented by [RFC5652](https://tools.ietf.org/html/rfc5652). The CMS encryption standard uses public key cryptography, where the keys used to encrypt content (the public key) and the keys used to decrypt content (the private key) are separate. Your public key can be shared widely, and is not sensitive data. If any content is encrypted with this public key, only your private key can decrypt it. For more information, see [Public-key cryptography](https://en.wikipedia.org/wiki/Public-key_cryptography). `Get-CmsMessage` gets content that has been encrypted in CMS format. It does not decrypt or unprotect content. You can run this cmdlet to get content that you have encrypted by running the `Protect-CmsMessage` cmdlet. You can specify content that you want to decrypt as a string, or by path to the encrypted content. You can pipe the results of `Get-CmsMessage` to `Unprotect-CmsMessage` to decrypt the content, provided that you have information about the document encryption certificate that was used to encrypt the content. Support for Linux and macOS was added in PowerShell 7.1. ## EXAMPLES ### Example 1: Get encrypted content ```powershell $Msg = Get-CmsMessage -Path "C:\Users\Test\Documents\PowerShell\Future_Plans.txt" $Msg.Content ``` ```Output -----BEGIN CMS----- MIIBqAYJKoZIhvcNAQcDoIIBmTCCAZUCAQAxggFQMIIBTAIBADA0MCAxHjAcBgNVBAMBFWxlZWhv bG1AbGljcm9zb2Z0LmNvbQIQQYHsbcXnjIJCtH+OhGmc1DANBgkqhkiG9w0BAQcwAASCAQAnkFHM proJnFy4geFGfyNmxH3yeoPvwEYzdnsoVqqDPAd8D3wao77z7OhJEXwz9GeFLnxD6djKV/tF4PxR E27aduKSLbnxfpf/sepZ4fUkuGibnwWFrxGE3B1G26MCenHWjYQiqv+Nq32Gc97qEAERrhLv6S4R G+2dJEnesW8A+z9QPo+DwYP5FzD0Td0ExrkswVckpLNR6j17Yaags3ltNXmbdEXekhi6Psf2MLMP TSO79lv2L0KeXFGuPOrdzPRwCkV0vNEqTEBeDnZGrjv/5766bM3GW34FXApod9u+VSFpBnqVOCBA DVDraA6k+xwBt66cV84AHLkh0kT02SIHMDwGCSqGSIb3DQEHATAdBglghkgBZQMEASoEEJbJaiRl KMnBoD1dkb/FzSWAEBaL8xkFwCu0e1AtDj7nSJc= -----END CMS----- ``` This command gets encrypted content located at C:\Users\Test\Documents\PowerShell\Future_Plans.txt. ### Example 2: Pipe encrypted content to Unprotect-CmsMessage ```powershell $Msg = Get-CmsMessage -Path "C:\Users\Test\Documents\PowerShell\Future_Plans.txt" $Msg | Unprotect-CmsMessage -To "cn=youralias@emailaddress.com" ``` ```Output Try the new Break All command ``` This command pipes the results of the `Get-CmsMessage` cmdlet from Example 1 to `Unprotect-CmsMessage`, to decrypt the message and read it in plain text. In this case, the value of the **To** parameter is the value of the encrypting certificate's Subject line. The decrypted message, "Try the new Break All command," is the result. ## PARAMETERS ### -Content Specifies an encrypted string, or a variable containing an encrypted string. ```yaml Type: System.String Parameter Sets: ByContent Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to encrypted content that you want to get. Unlike **Path**, the value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcard characters. If the path includes escape characters, enclose each one in single quotation marks. Single quotation marks tell PowerShell not to interpret enclosed characters as escape characters. ```yaml Type: System.String Parameter Sets: ByLiteralPath Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to encrypted content that you want to decrypt. ```yaml Type: System.String Parameter Sets: ByPath Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ## NOTES ## RELATED LINKS [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md) [Protect-CmsMessage](Protect-CmsMessage.md) [Unprotect-CmsMessage](Unprotect-CmsMessage.md)

#File: reference/7.6/Microsoft.PowerShell.Security/Get-Credential.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 05/15/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/get-credential?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Credential --- # Get-Credential ## SYNOPSIS Gets a credential object based on a user name and password. ## SYNTAX ### CredentialSet (Default) ``` Get-Credential [[-Credential] <PSCredential>] [<CommonParameters>] ``` ### MessageSet ``` Get-Credential [-Message <String>] [[-UserName] <String>] [-Title <String>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Credential` cmdlet creates a credential object for a specified user name and password. You can use the credential object in security operations. The `Get-Credential` cmdlet prompts the user for a password or a user name and password. You can use the **Message** parameter to specify a customized message for the prompt. In Windows PowerShell 5.1 and earlier, Windows presents a dialog box to prompt for a user name and password. In PowerShell 6.0 and later, the prompt is presented in the console for all platforms. ## EXAMPLES ### Example 1 ```powershell $c = Get-Credential ``` This command gets a credential object and saves it in the `$c` variable. When you enter the command, you are prompted for a user name and password. When you enter the requested information, the cmdlet creates a **PSCredential** object representing the credentials of the user and saves it in the `$c` variable. You can use the object as input to cmdlets that request user authentication, such as those with a **Credential** parameter. However, some providers that are installed with PowerShell do not support the **Credential** parameter. ### Example 2 ```powershell $c = Get-Credential -Credential User01 $c.Username User01 ``` This example creates a credential that includes a user name without a domain name. The first command gets a credential with the user name User01 and stores it in the `$c` variable. The second command displays the value of the **Username** property of the resulting credential object. ### Example 3 ```powershell $Credential = $Host.UI.PromptForCredential("Need credentials", "Please enter your user name and password.", "", "NetBiosUserName") ``` This command uses the **PromptForCredential** method to prompt the user for their user name and password. The command saves the resulting credentials in the `$Credential` variable. The **PromptForCredential** method is an alternative to using the `Get-Credential` cmdlet. When you use **PromptForCredential**, you can specify the caption, messages, and user name that appear in the prompt. For more information, see the [PromptForCredential](/dotnet/api/system.management.automation.host.pshostuserinterface.promptforcredential) documentation in the SDK. ### Example 4 This example demonstrates how to create a credential object identical to the one returned by `Get-Credential`. ```powershell $User = "Domain01\User01" $PWord = Read-Host -Prompt 'Enter a Password' -AsSecureString $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord ``` The first command assigns the username to the `$User` variable. Ensure the value follows the "Domain\User" or "ComputerName\User" format. The second command uses the `Read-Host` cmdlet to create a secure string from user input. The **Prompt** parameter requests user input, and the **AsSecureString** parameter masks the input and converts it to a secure string. The third command uses the `New-Object` cmdlet to create a **PSCredential** object from the values stored in the `$User` and `$PWord` variables. ### Example 5 ```powershell Get-Credential -Message "Credential are required for access to the \\Server1\Scripts file share." -User Server01\PowerUser ``` ```Output PowerShell Credential Request Credential are required for access to the \\Server1\Scripts file share. Password for user Server01\PowerUser: ``` This command uses the **Message** and **UserName** parameters of the `Get-Credential` cmdlet. This command format is designed for shared scripts and functions. In this case, the message tells the user why credentials are needed and gives them confidence that the request is legitimate. ### Example 6 ```powershell Invoke-Command -ComputerName Server01 {Get-Credential Domain01\User02} ``` ```Output PowerShell Credential Request : PowerShell Credential Request Warning: This credential is being requested by a script or application on the SERVER01 remote computer. Enter your credentials only if you trust the remote computer and the application or script requesting it. Enter your credentials. Password for user Domain01\User02: *************** PSComputerName : Server01 RunspaceId : 422bdf52-9886-4ada-ab2f-130497c6777f PSShowComputerName : True UserName : Domain01\User01 Password : System.Security.SecureString ``` This command gets a credential from the Server01 remote computer. The command uses the `Invoke-Command` cmdlet to run a `Get-Credential` command on the remote computer. The output shows the remote security message that `Get-Credential` includes in the authentication prompt. ## PARAMETERS ### -Credential Specifies a user name for the credential, such as **User01** or **Domain01\User01**. The parameter name, `-Credential`, is optional. When you submit the command and specify a user name, you're prompted for a password. If you omit this parameter, you're prompted for a user name and a password. Starting in PowerShell 3.0, if you enter a user name without a domain, `Get-Credential` no longer inserts a backslash before the name. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: CredentialSet Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Message Specifies a message that appears in the authentication prompt. This parameter is designed for use in a function or script. You can use the message to explain to the user why you are requesting credentials and how they will be used. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.String Parameter Sets: MessageSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Title Sets the text of the title line for the authentication prompt in the console. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.String Parameter Sets: MessageSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UserName Specifies a user name. The authentication prompt requests a password for the user name. By default, the user name is blank and the authentication prompt requests both a user name and password. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.String Parameter Sets: MessageSet Aliases: Required: False Position: 1 Default value: None (blank) Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSCredential This cmdlet returns a credential object. ## NOTES You can use the **PSCredential** object that `Get-Credential` creates in cmdlets that request user authentication, such as those with a **Credential** parameter. The **Credential** parameter is not supported by all providers that are installed with PowerShell. Beginning in PowerShell 3.0, it is supported on select cmdlets, such as the `Get-Content` and `New-PSDrive` cmdlets. ## RELATED LINKS [PromptForCredential](/dotnet/api/system.management.automation.host.pshostuserinterface.promptforcredential)

#File: reference/7.6/Microsoft.PowerShell.Security/Get-ExecutionPolicy.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 03/04/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/get-executionpolicy?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-ExecutionPolicy --- # Get-ExecutionPolicy ## SYNOPSIS Gets the execution policies for the current session. ## SYNTAX ### All ``` Get-ExecutionPolicy [[-Scope] <ExecutionPolicyScope>] [-List] [<CommonParameters>] ``` ## DESCRIPTION To display the execution policies for each scope in the order of precedence, use `Get-ExecutionPolicy -List`. To see the effective execution policy for your PowerShell session use `Get-ExecutionPolicy` with no parameters. The effective execution policy is determined by execution policies that are set by `Set-ExecutionPolicy` and Group Policy settings. For more information, see [about_Execution_Policies](../Microsoft.PowerShell.Core/about/about_Execution_Policies.md). ## EXAMPLES ### Example 1: Get all execution policies This command displays the execution policies for each scope in the order of precedence. ```powershell Get-ExecutionPolicy -List ``` ```Output Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser AllSigned LocalMachine Undefined ``` The `Get-ExecutionPolicy` cmdlet uses the **List** parameter to display each scope's execution policy. ### Example 2: Set an execution policy This example shows how to set an execution policy for the local computer. ```powershell Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine Get-ExecutionPolicy -List ``` ```Output Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser AllSigned LocalMachine RemoteSigned ``` The `Set-ExecutionPolicy` cmdlet uses the **ExecutionPolicy** parameter to specify the `RemoteSigned` policy. The **Scope** parameter specifies the default scope value, `LocalMachine`. To view the execution policy settings, use the `Get-ExecutionPolicy` cmdlet with the **List** parameter. ### Example 3: Get the effective execution policy This example shows how to display the effective execution policy for a PowerShell session. ``` PS> Get-ExecutionPolicy -List Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser AllSigned LocalMachine RemoteSigned PS> Get-ExecutionPolicy AllSigned ``` The `Get-ExecutionPolicy` cmdlet uses the **List** parameter to display each scope's execution policy. The `Get-ExecutionPolicy` cmdlet is run without a parameter to display the effective execution policy, `AllSigned`. ### Example 4: Unblock a script to run it without changing the execution policy This example shows how the `RemoteSigned` execution policy prevents you from running unsigned scripts. A best practice is to read the script's code and verify it's safe _before_ using the `Unblock-File` cmdlet. The `Unblock-File` cmdlet unblocks scripts so they can run, but doesn't change the execution policy. ```powershell PS> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine PS> Get-ExecutionPolicy RemoteSigned PS> .\Start-ActivityTracker.ps1 .\Start-ActivityTracker.ps1 : File .\Start-ActivityTracker.ps1 cannot be loaded. The file .\Start-ActivityTracker.ps1 is not digitally signed. The script will not execute on the system. For more information, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1 + .\Start-ActivityTracker.ps1 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess PS> Unblock-File -Path .\Start-ActivityTracker.ps1 PS> Get-ExecutionPolicy RemoteSigned PS> .\Start-ActivityTracker.ps1 Task 1: ``` The `Set-ExecutionPolicy` uses the **ExecutionPolicy** parameter to specify the `RemoteSigned` policy. The policy is set for the default scope, `LocalMachine`. The `Get-ExecutionPolicy` cmdlet shows that `RemoteSigned` is the effective execution policy for the current PowerShell session. The `Start-ActivityTracker.ps1` script is executed from the current directory. The script is blocked by `RemoteSigned` because the script isn't digitally signed. For this example, the script's code was reviewed and verified as safe to run. The `Unblock-File` cmdlet uses the **Path** parameter to unblock the script. To verify that `Unblock-File` didn't change the execution policy, `Get-ExecutionPolicy` displays the effective execution policy, `RemoteSigned`. The script, `Start-ActivityTracker.ps1` is executed from the current directory. The script begins to run because it was unblocked by the `Unblock-File` cmdlet. ## PARAMETERS ### -List Gets all execution policy values for the session. By default, `Get-ExecutionPolicy` gets only the effective execution policy. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Scope Specifies the scope that is affected by an execution policy. The effective execution policy is determined by the order of precedence as follows: - `MachinePolicy`. Set by a Group Policy for all users of the computer. - `UserPolicy`. Set by a Group Policy for the current user of the computer. - `Process`. Affects only the current PowerShell session. - `LocalMachine`. Default scope that affects all users of the computer. - `CurrentUser`. Affects only the current user. ```yaml Type: Microsoft.PowerShell.ExecutionPolicyScope Parameter Sets: (All) Aliases: Accepted values: CurrentUser, LocalMachine, MachinePolicy, Process, UserPolicy Required: False Position: 0 Default value: Effective execution policy Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.ExecutionPolicy The cmdlet always returns **Unrestricted** on Linux and macOS platforms. On Windows platforms it returns the current execution policy. ## NOTES An execution policy is part of the PowerShell security strategy. Execution policies determine whether you can load configuration files, such as your PowerShell profile, or run scripts. And, whether scripts must be digitally signed before they are run. ## RELATED LINKS [about_Execution_Policies](../Microsoft.PowerShell.Core/about/about_Execution_Policies.md) [about_Group_Policy_Settings](../Microsoft.PowerShell.Core/About/about_Group_Policy_Settings.md) [Get-AuthenticodeSignature](Get-AuthenticodeSignature.md) [Set-AuthenticodeSignature](Set-AuthenticodeSignature.md) [Set-ExecutionPolicy](Set-ExecutionPolicy.md)

#File: reference/7.6/Microsoft.PowerShell.Security/Get-PfxCertificate.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 01/18/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/get-pfxcertificate?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-PfxCertificate --- # Get-PfxCertificate ## SYNOPSIS Gets information about PFX certificate files on the computer. ## SYNTAX ### ByPath (Default) ``` Get-PfxCertificate [-FilePath] <String[]> [-Password <SecureString>] [-NoPromptForPassword] [<CommonParameters>] ``` ### ByLiteralPath ``` Get-PfxCertificate -LiteralPath <String[]> [-Password <SecureString>] [-NoPromptForPassword] [<CommonParameters>] ``` ## DESCRIPTION The `Get-PfxCertificate` cmdlet gets an object representing each specified PFX certificate file. A PFX file includes both the certificate and a private key. ## EXAMPLES ### Example 1: Get a PFX certificate ```powershell Get-PfxCertificate -FilePath "C:\windows\system32\Test.pfx" ``` ```output Password: ****** Signer Certificate: David Chew (Self Certificate) Time Certificate: Time Stamp: Path: C:\windows\system32\zap.pfx ``` This command gets information about the Test.pfx certificate file on the system. ### Example 2: Get a PFX certificate from a remote computer ```powershell Invoke-Command -ComputerName "Server01" -ScriptBlock {Get-PfxCertificate -FilePath "C:\Text\TestNoPassword.pfx"} -Authentication CredSSP ``` This command gets a PFX certificate file from the Server01 remote computer. It uses `Invoke-Command` to run a `Get-PfxCertificate` command remotely. When the PFX certificate file is not password-protected, the value of the **Authentication** parameter of `Invoke-Command` must be CredSSP. ## PARAMETERS ### -FilePath Specifies the full path to the PFX file of the secured file. If you specify a value for this parameter, it is not necessary to type `-FilePath` at the command line. ```yaml Type: System.String[] Parameter Sets: ByPath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -LiteralPath The full path to the PFX file of the secured file. Unlike **FilePath**, the value of the **LiteralPath** parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: ByLiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -NoPromptForPassword Suppresses prompting for a password. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Password Specifies a password required to access a `.pfx` certificate file. This parameter was introduced in PowerShell 6.1. > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Security.SecureString Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a file path to `Get-PfxCertificate`. ## OUTPUTS ### System.Security.Cryptography.X509Certificates.X509Certificate2 `Get-PfxCertificate` returns an object for each certificate that it gets. ## NOTES When using the `Invoke-Command` cmdlet to run a `Get-PfxCertificate` command remotely, and the PFX certificate file is not password protected, the value of the **Authentication** parameter of `Invoke-Command` must be CredSSP. ## RELATED LINKS [Get-AuthenticodeSignature](Get-AuthenticodeSignature.md) [Set-AuthenticodeSignature](Set-AuthenticodeSignature.md)

#File: reference/7.6/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.md

--- Download Help Link: https://aka.ms/powershell75-help Help Version: 7.6.0.0 Locale: en-US Module Guid: a94c8c7e-9810-47c0-b8af-65089c13a35a Module Name: Microsoft.PowerShell.Security ms.date: 06/09/2017 schema: 2.0.0 title: Microsoft.PowerShell.Security --- # Microsoft.PowerShell.Security Module ## Description This section contains the help topics for the cmdlets that are installed with PowerShell Microsoft.PowerShell.Security module. The Security module contains cmdlets and providers that manage the basic security features of Windows. ## Microsoft.PowerShell.Security Cmdlets ### [ConvertFrom-SecureString](ConvertFrom-SecureString.md) Converts a secure string to an encrypted standard string. ### [ConvertTo-SecureString](ConvertTo-SecureString.md) Converts encrypted standard strings to secure strings. ### [Get-Acl](Get-Acl.md) Gets the security descriptor for a resource, such as a file or registry key. ### [Get-AuthenticodeSignature](Get-AuthenticodeSignature.md) Gets information about the Authenticode signature for a file. ### [Get-CmsMessage](Get-CmsMessage.md) Gets content that has been encrypted by using the Cryptographic Message Syntax format. ### [Get-Credential](Get-Credential.md) Gets a credential object based on a user name and password. ### [Get-ExecutionPolicy](Get-ExecutionPolicy.md) Gets the execution policies for the current session. ### [Get-PfxCertificate](Get-PfxCertificate.md) Gets information about PFX certificate files on the computer. ### [New-FileCatalog](New-FileCatalog.md) Creates a Windows catalog file containing cryptographic hashes for files and folders in specified paths. ### [Protect-CmsMessage](Protect-CmsMessage.md) Encrypts content by using the Cryptographic Message Syntax format. ### [Set-Acl](Set-Acl.md) Changes the security descriptor of a specified item, such as a file or a registry key. ### [Set-AuthenticodeSignature](Set-AuthenticodeSignature.md) Adds an Authenticode signature to a PowerShell script or other file. ### [Set-ExecutionPolicy](Set-ExecutionPolicy.md) Sets the PowerShell execution policies for Windows computers. ### [Test-FileCatalog](Test-FileCatalog.md) Validates whether the hashes contained in a catalog file (.cat) matches the hashes of the actual files in order to validate their authenticity. ### [Unprotect-CmsMessage](Unprotect-CmsMessage.md) Decrypts content that has been encrypted by using the Cryptographic Message Syntax format.

#File: reference/7.6/Microsoft.PowerShell.Security/New-FileCatalog.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 05/29/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/new-filecatalog?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-FileCatalog --- # New-FileCatalog ## SYNOPSIS Creates a Windows catalog file containing cryptographic hashes for files and folders in the specified paths. ## SYNTAX ``` New-FileCatalog [-CatalogVersion <Int32>] [-CatalogFilePath] <String> [[-Path] <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** `New-FileCatalog` creates a [Windows catalog file](/windows-hardware/drivers/install/catalog-files) for a set of folders and files. This catalog file contains hashes for all files in the provided paths. Users can then distribute the catalog with their files so that users can validate whether any changes have been made to the folders since catalog creation time. Catalog versions 1 and 2 are supported. Version 1 uses the (deprecated) SHA1 hashing algorithm to create file hashes, and version 2 uses SHA256. ## EXAMPLES ### Example 1: Create a file catalog for `Microsoft.PowerShell.Utility` ```powershell $newFileCatalogSplat = @{ Path = "$PSHOME\Modules\Microsoft.PowerShell.Utility" CatalogFilePath = '\temp\Microsoft.PowerShell.Utility.cat' CatalogVersion = 2.0 } New-FileCatalog @newFileCatalogSplat ``` ```Output Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 11/2/2018 11:58 AM 950 Microsoft.PowerShell.Utility.cat ``` ## PARAMETERS ### -CatalogFilePath The location and name of the catalog file (`.cat`) you are creating. If you specify only a folder path, the command creates a file named `catalog.cat` in that location. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -CatalogVersion Accepts `1.0` or `2.0` as possible values for specifying the catalog version. `1.0` should be avoided whenever possible because it uses the insecure SHA-1 hash algorithm. Version `2.0` uses the secure SHA-256 algorithm. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Accepts a path or array of paths to files or folders that should be included in the catalog file. If a folder is specified, the command includes all files in the folder. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that's used as the catalog filename to this cmdlet. ## OUTPUTS ### System.IO.FileInfo This cmdlet returns a **FileInfo** object representing the created catalog. ## NOTES This cmdlet is only available on Windows platforms. ## RELATED LINKS [Test-FileCatalog](Test-FileCatalog.md) [PowerShellGet](/powerShell/module/powershellget)

#File: reference/7.6/Microsoft.PowerShell.Security/Protect-CmsMessage.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 02/03/2020 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/protect-cmsmessage?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Protect-CmsMessage --- # Protect-CmsMessage ## SYNOPSIS Encrypts content by using the Cryptographic Message Syntax format. ## SYNTAX ### ByContent (Default) ``` Protect-CmsMessage [-To] <CmsMessageRecipient[]> [-Content] <PSObject> [[-OutFile] <String>] [<CommonParameters>] ``` ### ByPath ``` Protect-CmsMessage [-To] <CmsMessageRecipient[]> [-Path] <String> [[-OutFile] <String>] [<CommonParameters>] ``` ### ByLiteralPath ``` Protect-CmsMessage [-To] <CmsMessageRecipient[]> [-LiteralPath] <String> [[-OutFile] <String>] [<CommonParameters>] ``` ## DESCRIPTION The `Protect-CmsMessage` cmdlet encrypts content by using the Cryptographic Message Syntax (CMS) format. The CMS cmdlets support encryption and decryption of content using the IETF format as documented by [RFC5652](https://tools.ietf.org/html/rfc5652.html). The CMS encryption standard uses public key cryptography, where the keys used to encrypt content (the public key) and the keys used to decrypt content (the private key) are separate. Your public key can be shared widely, and is not sensitive data. If any content is encrypted with this public key, only your private key can decrypt it. For more information, see [Public-key cryptography](https://en.wikipedia.org/wiki/Public-key_cryptography). Before you can run the `Protect-CmsMessage` cmdlet, you must have an encryption certificate set up. To be recognized in PowerShell, encryption certificates require a unique extended key usage ([EKU](/windows/desktop/SecCrypto/eku)) ID to identify them as data encryption certificates (such as the IDs for Code Signing and Encrypted Mail). For an example of a certificate that would work for document encryption, see Example 1 in this topic. Support for Linux and macOS was added in PowerShell 7.1. ## EXAMPLES ### Example 1: Create a certificate for encrypting content Before you can run the `Protect-CmsMessage` cmdlet, you must create an encryption certificate. Using the following text, change the name in the Subject line to your name, email, or other identifier, and save the certificate in a file (such as `DocumentEncryption.inf`, as shown in this example). ```powershell # Create .INF file for certreq {[Version] Signature = "$Windows NT$" [Strings] szOID_ENHANCED_KEY_USAGE = "2.5.29.37" szOID_DOCUMENT_ENCRYPTION = "1.3.6.1.4.1.311.80.1" [NewRequest] Subject = "cn=youralias@emailaddress.com" MachineKeySet = false KeyLength = 2048 KeySpec = AT_KEYEXCHANGE HashAlgorithm = Sha1 Exportable = true RequestType = Cert KeyUsage = "CERT_KEY_ENCIPHERMENT_KEY_USAGE | CERT_DATA_ENCIPHERMENT_KEY_USAGE" ValidityPeriod = "Years" ValidityPeriodUnits = "1000" [Extensions] %szOID_ENHANCED_KEY_USAGE% = "{text}%szOID_DOCUMENT_ENCRYPTION%" } | Out-File -FilePath DocumentEncryption.inf # After you have created your certificate file, run the following command to add # the certificate file to the certificate store. Now you are ready to encrypt and # decrypt content with the next two examples. certreq.exe -new DocumentEncryption.inf DocumentEncryption.cer ``` ### Example 2: Encrypt a message sent by email ```powershell $Protected = "Hello World" | Protect-CmsMessage -To "*youralias@emailaddress.com*" ``` In the following example, you encrypt a message, "Hello World", by piping it to the `Protect-CmsMessage` cmdlet, and then save the encrypted message in a variable. The **To** parameter uses the value of the Subject line in the certificate. ### Example 3: View document encryption certificates ``` PS C:\> cd Cert:\CurrentUser\My PS Cert:\CurrentUser\My> Get-ChildItem -DocumentEncryptionCert ``` To view document encryption certificates in the Certificate provider, you can add the **DocumentEncryptionCert** dynamic parameter of [Get-ChildItem](../Microsoft.PowerShell.Management/Get-ChildItem.md), available only when the Certificate provider is loaded. ## PARAMETERS ### -Content Specifies a **PSObject** that contains content that you want to encrypt. For example, you can encrypt the content of an event message, and then use the variable containing the message (`$Event`, in this example) as the value of the **Content** parameter: `$event = Get-WinEvent -ProviderName "PowerShell" -MaxEvents 1`. You can also use the `Get-Content` cmdlet to get the contents of a file, such as a Microsoft Word document, and save the content in a variable that you use as the value of the **Content** parameter. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: ByContent Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to content that you want to encrypt. Unlike **Path**, the value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String Parameter Sets: ByLiteralPath Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OutFile Specifies the path and file name of a file to which you want to send the encrypted content. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to content that you want to encrypt. ```yaml Type: System.String Parameter Sets: ByPath Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -To Specifies one or more CMS message recipients, identified in any of the following formats: - An actual certificate (as retrieved from the Certificate provider). - Path to the file containing the certificate. - Path to a directory containing the certificate. - Thumbprint of the certificate (used to look in the certificate store). - Subject name of the certificate (used to look in the certificate store). ```yaml Type: System.Management.Automation.CmsMessageRecipient[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: `-Debug`, `-ErrorAction`, `-ErrorVariable`, `-InformationAction`, `-InformationVariable`, `-OutVariable`, `-OutBuffer`, `-PipelineVariable`, `-Verbose`, `-WarningAction`, and `-WarningVariable`. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ## OUTPUTS ## NOTES ## RELATED LINKS [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md) [Get-CmsMessage](Get-CmsMessage.md) [Unprotect-CmsMessage](Unprotect-CmsMessage.md)

#File: reference/7.6/Microsoft.PowerShell.Security/Set-Acl.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 01/18/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/set-acl?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-Acl --- # Set-Acl ## SYNOPSIS Changes the security descriptor of a specified item, such as a file or a registry key. ## SYNTAX ### ByPath (Default) ``` Set-Acl [-Path] <String[]> [-AclObject] <Object> [-ClearCentralAccessPolicy] [-PassThru] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ByInputObject ``` Set-Acl [-InputObject] <PSObject> [-AclObject] <Object> [-PassThru] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ByLiteralPath ``` Set-Acl -LiteralPath <String[]> [-AclObject] <Object> [-ClearCentralAccessPolicy] [-PassThru] [-Filter <String>] [-Include <String[]>] [-Exclude <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Set-Acl` cmdlet changes the security descriptor of a specified item, such as a file or a registry key, to match the values in a security descriptor that you supply. To use `Set-Acl`, use the **Path** or **InputObject** parameter to identify the item whose security descriptor you want to change. Then, use the **AclObject** or **SecurityDescriptor** parameters to supply a security descriptor that has the values you want to apply. `Set-Acl` applies the security descriptor that is supplied. It uses the value of the **AclObject** parameter as a model and changes the values in the item's security descriptor to match the values in the **AclObject** parameter. ## EXAMPLES ### Example 1: Copy a security descriptor from one file to another ```powershell $DogACL = Get-Acl -Path "C:\Dog.txt" Set-Acl -Path "C:\Cat.txt" -AclObject $DogACL ``` These commands copy the values from the security descriptor of the Dog.txt file to the security descriptor of the Cat.txt file. When the commands complete, the security descriptors of the Dog.txt and Cat.txt files are identical. The first command uses the `Get-Acl` cmdlet to get the security descriptor of the Dog.txt file. The assignment operator (`=`) stores the security descriptor in the value of the $DogACL variable. The second command uses `Set-Acl` to change the values in the ACL of Cat.txt to the values in `$DogACL`. The value of the **Path** parameter is the path to the Cat.txt file. The value of the **AclObject** parameter is the model ACL, in this case, the ACL of Dog.txt as saved in the `$DogACL` variable. ### Example 2: Use the pipeline operator to pass a descriptor ```powershell Get-Acl -Path "C:\Dog.txt" | Set-Acl -Path "C:\Cat.txt" ``` This command is almost the same as the command in the previous example, except that it uses a pipeline operator (`|`) to send the security descriptor from a `Get-Acl` command to a `Set-Acl` command. The first command uses the `Get-Acl` cmdlet to get the security descriptor of the Dog.txt file. The pipeline operator (`|`) passes an object that represents the Dog.txt security descriptor to the `Set-Acl` cmdlet. The second command uses `Set-Acl` to apply the security descriptor of Dog.txt to Cat.txt. When the command completes, the ACLs of the Dog.txt and Cat.txt files are identical. ### Example 3: Apply a security descriptor to multiple files ```powershell $NewAcl = Get-Acl File0.txt Get-ChildItem -Path "C:\temp" -Recurse -Include "*.txt" -Force | Set-Acl -AclObject $NewAcl ``` These commands apply the security descriptors in the File0.txt file to all text files in the `C:\Temp` directory and all of its subdirectories. The first command gets the security descriptor of the File0.txt file in the current directory and uses the assignment operator (`=`) to store it in the `$NewACL` variable. The first command in the pipeline uses the Get-ChildItem cmdlet to get all of the text files in the `C:\Temp` directory. The **Recurse** parameter extends the command to all subdirectories of `C:\temp`. The **Include** parameter limits the files retrieved to those with the `.txt` file name extension. The **Force** parameter gets hidden files, which would otherwise be excluded. (You cannot use `C:\temp\*.txt`, because the **Recurse** parameter works on directories, not on files.) The pipeline operator (`|`) sends the objects representing the retrieved files to the `Set-Acl` cmdlet, which applies the security descriptor in the **AclObject** parameter to all of the files in the pipeline. In practice, it is best to use the **WhatIf** parameter with all `Set-Acl` commands that can affect more than one item. In this case, the second command in the pipeline would be `Set-Acl -AclObject $NewAcl -WhatIf`. This command lists the files that would be affected by the command. After reviewing the result, you can run the command again without the **WhatIf** parameter. ### Example 4: Disable inheritance and preserve inherited access rules ```powershell $NewAcl = Get-Acl -Path "C:\Pets\Dog.txt" $isProtected = $true $preserveInheritance = $true $NewAcl.SetAccessRuleProtection($isProtected, $preserveInheritance) Set-Acl -Path "C:\Pets\Dog.txt" -AclObject $NewAcl ``` These commands disable access inheritance from parent folders, while still preserving the existing inherited access rules. The first command uses the `Get-Acl` cmdlet to get the security descriptor of the Dog.txt file. Next, variables are created to convert the inherited access rules to explicit access rules. To protect the access rules associated with this from inheritance, set the `$isProtected` variable to `$true`. To allow inheritance, set `$isProtected` to `$false`. For more information, see [set access rule protection](/dotnet/api/system.security.accesscontrol.objectsecurity.setaccessruleprotection). Set the `$preserveInheritance` variable to `$true` to preserve inherited access rules or `$false` to remove inherited access rules. Then the access rule protection is updated using the **SetAccessRuleProtection()** method. The last command uses `Set-Acl` to apply the security descriptor of to Dog.txt. When the command completes, the ACLs of the Dog.txt that were inherited from the Pets folder will be applied directly to Dog.txt, and new access policies added to Pets will not change the access to Dog.txt. ### Example 5: Grant Administrators Full Control of the file ```powershell $NewAcl = Get-Acl -Path "C:\Pets\Dog.txt" # Set properties $identity = "BUILTIN\Administrators" $fileSystemRights = "FullControl" $type = "Allow" # Create new rule $fileSystemAccessRuleArgumentList = $identity, $fileSystemRights, $type $fileSystemAccessRule = New-Object -TypeName System.Security.AccessControl.FileSystemAccessRule -ArgumentList $fileSystemAccessRuleArgumentList # Apply new rule $NewAcl.SetAccessRule($fileSystemAccessRule) Set-Acl -Path "C:\Pets\Dog.txt" -AclObject $NewAcl ``` This command will grant the **BUILTIN\Administrators** group Full control of the Dog.txt file. The first command uses the `Get-Acl` cmdlet to get the security descriptor of the Dog.txt file. Next variables are created to grant the **BUILTIN\Administrators** group full control of the Dog.txt file. The `$identity` variable set to the name of a [user account](/dotnet/api/system.security.accesscontrol.filesystemaccessrule.-ctor). The `$fileSystemRights` variable set to FullControl, and can be any one of the [FileSystemRights](/dotnet/api/system.security.accesscontrol.filesystemrights) values that specifies the type of operation associated with the access rule. The `$type` variable set to "Allow" to specifies whether to allow or deny the operation. The `$fileSystemAccessRuleArgumentList` variable is an argument list is to be passed when making the new **FileSystemAccessRule** object. Then a new **FileSystemAccessRule** object is created, and the **FileSystemAccessRule** object is passed to the **SetAccessRule()** method, adds the new access rule. The last command uses `Set-Acl` to apply the security descriptor of to Dog.txt. When the command completes, the **BUILTIN\Administrators** group will have full control of the Dog.txt. ## PARAMETERS ### -AclObject Specifies an ACL with the desired property values. `Set-Acl` changes the ACL of item specified by the **Path** or **InputObject** parameter to match the values in the specified security object. You can save the output of a `Get-Acl` command in a variable and then use the **AclObject** parameter to pass the variable, or type a `Get-Acl` command. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -ClearCentralAccessPolicy Removes the central access policy from the specified item. Beginning in Windows Server 2012, administrators can use Active Directory and Group Policy to set central access policies for users and groups. For more information, see [Dynamic Access Control: Scenario Overview](/windows-server/identity/solution-guides/dynamic-access-control--scenario-overview). This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ByPath, ByLiteralPath Aliases: PSPath, LP Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Exclude Omits the specified items. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Filter Specifies a filter in the provider's format or language. The value of this parameter qualifies the **Path** parameter. The syntax of the filter, including the use of wildcards, depends on the provider. Filters are more efficient than other parameters, because the provider applies them when retrieving the objects, rather than having PowerShell filter the objects after they are retrieved. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Include Changes only the specified items. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -InputObject Changes the security descriptor of the specified object. Enter a variable that contains the object or a command that gets the object. You cannot pipe the object to be changed to `Set-Acl`. Instead, use the **InputObject** parameter explicitly in the command. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: ByInputObject Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -LiteralPath Changes the security descriptor of the specified item. Unlike **Path**, the value of the **LiteralPath** parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks (`'`). Single quotation marks tell PowerShell not to interpret any characters as escape sequences. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String[] Parameter Sets: ByLiteralPath Aliases: PSPath Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Returns an object that represents the security descriptor that was changed. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Changes the security descriptor of the specified item. Enter the path to an item, such as a path to a file or registry key. Wildcards are permitted. If you pass a security object to `Set-Acl` (either by using the **AclObject** or **SecurityDescriptor** parameters or by passing a security object from Get-Acl to `Set-Acl`), and you omit the **Path** parameter (name and value), `Set-Acl` uses the path that is included in the security object. ```yaml Type: System.String[] Parameter Sets: ByPath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Security.AccessControl.ObjectSecurity You can pipe an ACL object to this cmdlet. ### System.Security.AccessControl.CommonSecurityDescriptor You can pipe a security descriptor to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Security.AccessControl.FileSecurity When you use the **PassThru** parameter, this cmdlet returns a security object. The type of the security object depends on the type of the item. ## NOTES This cmdlet is only available on Windows platforms. The `Set-Acl` cmdlet is supported by the PowerShell FileSystem and Registry providers. As such, you can use it to change the security descriptors of files, directories, and registry keys. ## RELATED LINKS [Get-Acl](Get-Acl.md) [FileSystemAccessRule](/dotnet/api/system.security.accesscontrol.filesystemaccessrule.-ctor) [ObjectSecurity.SetAccessRuleProtection](/dotnet/api/system.security.accesscontrol.objectsecurity.setaccessruleprotection) [FileSystemRights](/dotnet/api/system.security.accesscontrol.filesystemrights)

#File: reference/7.6/Microsoft.PowerShell.Security/Set-AuthenticodeSignature.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 03/07/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/set-authenticodesignature?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-AuthenticodeSignature --- # Set-AuthenticodeSignature ## SYNOPSIS Adds an Authenticode signature to a PowerShell script or other file. ## SYNTAX ### ByPath (Default) ``` Set-AuthenticodeSignature [-Certificate] <X509Certificate2> [-IncludeChain <String>] [-TimestampServer <String>] [-HashAlgorithm <String>] [-Force] [-FilePath] <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ByLiteralPath ``` Set-AuthenticodeSignature [-Certificate] <X509Certificate2> [-IncludeChain <String>] [-TimestampServer <String>] [-HashAlgorithm <String>] [-Force] -LiteralPath <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ByContent ``` Set-AuthenticodeSignature [-Certificate] <X509Certificate2> [-IncludeChain <String>] [-TimestampServer <String>] [-HashAlgorithm <String>] [-Force] -SourcePathOrExtension <String[]> -Content <Byte[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Set-AuthenticodeSignature` cmdlet adds an Authenticode signature to any file that supports Subject Interface Package (SIP). In a PowerShell script file, the signature takes the form of a block of text that indicates the end of the instructions that are executed in the script. If there is a signature in the file when this cmdlet runs, that signature is removed. ## EXAMPLES ### Example 1 - Sign a script using a certificate from the local certificate store These commands retrieve a code-signing certificate from the PowerShell Certificate provider and use it to sign a PowerShell script. ```powershell $cert = Get-ChildItem -Path Cert:\CurrentUser\My -CodeSigningCert Set-AuthenticodeSignature -FilePath PsTestInternet2.ps1 -Certificate $cert ``` The first command uses the `Get-ChildItem` cmdlet and the PowerShell Certificate provider to get the certificates in the `Cert:\CurrentUser\My` subdirectory of the certificate store. The `Cert:` drive is the drive exposed by the Certificate provider. The **CodeSigningCert** parameter, which is supported only by the Certificate provider, limits the certificates retrieved to those with code-signing authority. The command stores the result in the `$cert` variable. The second command uses the `Set-AuthenticodeSignature` cmdlet to sign the `PSTestInternet2.ps1` script. It uses the **FilePath** parameter to specify the name of the script and the **Certificate** parameter to specify that the certificate is stored in the `$cert` variable. > [!NOTE] > Using the **CodeSigningCert** parameter with `Get-ChildItem` only returns certificates that have > code-signing authority and contain a private key. If there is no private key, the certificates > can't be used for signing. ### Example 2 - Sign a script using a certificate from a PFX file These commands use the `Get-PfxCertificate` cmdlet to load a code signing certificate. Then, use it to sign a PowerShell script. ```powershell $cert = Get-PfxCertificate -FilePath C:\Test\Mysign.pfx Set-AuthenticodeSignature -FilePath ServerProps.ps1 -Certificate $cert ``` The first command uses the `Get-PfxCertificate` cmdlet to load the `C:\Test\MySign.pfx` certificate into the `$cert` variable. The second command uses `Set-AuthenticodeSignature` to sign the script. The **FilePath** parameter of `Set-AuthenticodeSignature` specifies the path to the script file being signed and the **Cert** parameter passes the `$cert` variable containing the certificate to `Set-AuthenticodeSignature`. If the certificate file is password protected, PowerShell prompts you for the password. ### Example 3 - Add a signature that includes the root authority This command adds a digital signature that includes the root authority in the trust chain, and it's signed by a third-party timestamp server. ```powershell $signingParameters = @{ FilePath = 'C:\scripts\Remodel.ps1' Certificate = $cert HashAlgorithm = 'SHA256' IncludeChain = 'All' TimestampServer = 'http://timestamp.fabrikam.com/scripts/timstamper.dll' } Set-AuthenticodeSignature @signingParameters ``` The command uses the **FilePath** parameter to specify the script being signed and the **Certificate** parameter to specify the certificate that's saved in the `$cert` variable. It uses the **IncludeChain** parameter to include all of the signatures in the trust chain, including the root authority. It also uses the **TimeStampServer** parameter to add a timestamp to the signature. This prevents the script from failing when the certificate expires. ## PARAMETERS ### -Certificate Specifies the certificate that will be used to sign the script or file. Enter a variable that stores an object representing the certificate or an expression that gets the certificate. To find a certificate, use `Get-PfxCertificate` or use the `Get-ChildItem` cmdlet in the Certificate `Cert:` drive. If the certificate isn't valid or doesn't have `code-signing` authority, the command fails. ```yaml Type: System.Security.Cryptography.X509Certificates.X509Certificate2 Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Content This parameter appears in the syntax listing because it's defined in the base class that `Set-AuthenticodeSignature` is derived from. However, support for this parameter isn't implemented in `Set-AuthenticodeSignature`. ```yaml Type: System.Byte[] Parameter Sets: ByContent Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -FilePath Specifies the path to a file that's being signed. ```yaml Type: System.String[] Parameter Sets: ByPath Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Force Allows the cmdlet to append a signature to a read-only file. Even using the **Force** parameter, the cmdlet can't override security restrictions. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -HashAlgorithm Specifies the hashing algorithm that Windows uses to compute the digital signature for the file. For PowerShell 7.3, the default is SHA256, which is the Windows default hashing algorithm. For earlier versions, the default is SHA1. Files that are signed with a different hashing algorithm might not be recognized on other systems. Which algorithms are supported depends on the version of the operating system. For a list of possible values, see [HashAlgorithmName](xref:System.Security.Cryptography.HashAlgorithmName#properties) struct. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: SHA256 Accept pipeline input: False Accept wildcard characters: False ``` ### -IncludeChain Determines which certificates in the certificate trust chain are included in the digital signature. **NotRoot** is the default. Valid values are: - `Signer`: Includes only the signer's certificate. - `NotRoot`: Includes all of the certificates in the certificate chain, except for the root authority. - `All`: Includes all the certificates in the certificate chain. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: NotRoot Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to a file that's being signed. Unlike **FilePath**, the value of the **LiteralPath** parameter is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: ByLiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -SourcePathOrExtension This parameter appears in the syntax listing because it's defined in the base class that `Set-AuthenticodeSignature` is derived from. However, support for this parameter isn't implemented in `Set-AuthenticodeSignature`. ```yaml Type: System.String[] Parameter Sets: ByContent Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -TimestampServer Uses the specified time stamp server to add a time stamp to the signature. Type the URL of the time stamp server as a string. The URL must start with `http://`. The time stamp represents the exact time that the certificate was added to the file. A time stamp prevents the script from failing if the certificate expires because users and programs can verify that the certificate was valid at the time of signing. > [!NOTE] > PowerShell 7.3 added support for `https://` URLs with this parameter. However, the underlying API > doesn't support HTTPS. If you use HTTPS, the command returns an error, but the file is signed > without a time stamp. For more information, see > [Issue #25130](https://github.com/PowerShell/PowerShell/issues/25130). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains the file path to this cmdlet. ## OUTPUTS ### System.Management.Automation.Signature This cmdlet returns a **Signature** object representing the value it set. ## NOTES This cmdlet is only available on Windows platforms. ## RELATED LINKS [Authenticode](/windows-hardware/drivers/install/authenticode) [Get-AuthenticodeSignature](Get-AuthenticodeSignature.md) [Get-ExecutionPolicy](Get-ExecutionPolicy.md) [Get-PfxCertificate](Get-PfxCertificate.md) [Set-ExecutionPolicy](Set-ExecutionPolicy.md) [about_Execution_Policies](../Microsoft.PowerShell.Core/About/about_Execution_Policies.md) [about_Signing](../Microsoft.PowerShell.Core/About/about_Signing.md)

#File: reference/7.6/Microsoft.PowerShell.Security/Set-ExecutionPolicy.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 04/15/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/set-executionpolicy?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-ExecutionPolicy --- # Set-ExecutionPolicy ## SYNOPSIS Sets the PowerShell execution policies for Windows computers. ## SYNTAX ### All ``` Set-ExecutionPolicy [-ExecutionPolicy] <ExecutionPolicy> [[-Scope] <ExecutionPolicyScope>] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Set-ExecutionPolicy` cmdlet changes PowerShell execution policies for Windows computers. For more information, see [about_Execution_Policies](../Microsoft.PowerShell.Core/about/about_Execution_Policies.md). Beginning in PowerShell 6.0 for non-Windows computers, the default execution policy is `Unrestricted` and can't be changed. The `Set-ExecutionPolicy` cmdlet is available, but PowerShell displays a console message that it's not supported. An execution policy is part of the PowerShell security strategy. Execution policies determine whether you can load configuration files, such as your PowerShell profile, or run scripts. And, whether scripts must be digitally signed before they are run. The `Set-ExecutionPolicy` cmdlet's default scope is `LocalMachine`, which affects everyone who uses the computer. To change the execution policy for `LocalMachine`, start PowerShell with **Run as Administrator**. To display the execution policies for each scope, use `Get-ExecutionPolicy -List`. To see the effective execution policy for your PowerShell session use `Get-ExecutionPolicy` with no parameters. ## EXAMPLES ### Example 1: Set an execution policy This example shows how to set the execution policy for the local computer. ```powershell Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine Get-ExecutionPolicy -List ``` ```Output Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser RemoteSigned LocalMachine RemoteSigned ``` The `Set-ExecutionPolicy` cmdlet uses the **ExecutionPolicy** parameter to specify the `RemoteSigned` policy. The **Scope** parameter specifies the default scope value, `LocalMachine`. To view the execution policy settings, use the `Get-ExecutionPolicy` cmdlet with the **List** parameter. ### Example 2: Set an execution policy that conflicts with a Group Policy This command attempts to set the `LocalMachine` scope's execution policy to `Restricted`. `LocalMachine` is more restrictive, but isn't the effective policy because it conflicts with a Group Policy. The `Restricted` policy is written to the registry hive `HKEY_LOCAL_MACHINE`. ```powershell PS> Set-ExecutionPolicy -ExecutionPolicy Restricted -Scope LocalMachine Set-ExecutionPolicy : PowerShell updated your local preference successfully, but the setting is overridden by the Group Policy applied to your system. Due to the override, your shell will retain its current effective execution policy of "AllSigned". Contact your Group Policy administrator for more information. At line:1 char:20 + Set-ExecutionPolicy <<<< restricted PS> Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds Hive: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds Name Property ---- -------- Microsoft.PowerShell Path : C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe ExecutionPolicy : Restricted ScriptedDiagnostics ExecutionPolicy : Unrestricted ``` The `Set-ExecutionPolicy` cmdlet uses the **ExecutionPolicy** parameter to specify the `Restricted` policy. The **Scope** parameter specifies the default scope value, `LocalMachine`. The `Get-ChildItem` cmdlet uses the **Path** parameter with the `HKLM:` drive to specify registry location. ### Example 3: Apply the execution policy from a remote computer to a local computer This command gets the execution policy object from a remote computer and sets the policy on the local computer. `Get-ExecutionPolicy` sends a **Microsoft.PowerShell.ExecutionPolicy** object down the pipeline. `Set-ExecutionPolicy` accepts pipeline input and doesn't require the **ExecutionPolicy** parameter. ```powershell Invoke-Command -ComputerName Server01 -ScriptBlock { Get-ExecutionPolicy } | Set-ExecutionPolicy ``` The `Invoke-Command` cmdlet is executed at the local computer and sends the **ScriptBlock** to the remote computer. The **ComputerName** parameter specifies the remote computer, **Server01**. The **ScriptBlock** parameter runs `Get-ExecutionPolicy` on the remote computer. The `Get-ExecutionPolicy` object is sent down the pipeline to the `Set-ExecutionPolicy`. `Set-ExecutionPolicy` applies the execution policy to the local computer's default scope, `LocalMachine`. ### Example 4: Set the scope for an execution policy This example shows how to set an execution policy for a specified scope, `CurrentUser`. The `CurrentUser` scope only affects the user who sets this scope. ```powershell Set-ExecutionPolicy -ExecutionPolicy AllSigned -Scope CurrentUser Get-ExecutionPolicy -List ``` ```Output Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser AllSigned LocalMachine RemoteSigned ``` `Set-ExecutionPolicy` uses the **ExecutionPolicy** parameter to specify the `AllSigned` policy. The **Scope** parameter specifies the `CurrentUser`. To view the execution policy settings, use the `Get-ExecutionPolicy` cmdlet with the **List** parameter. The effective execution policy for the user becomes `AllSigned`. ### Example 5: Remove the execution policy for the current user This example shows how to use the `Undefined` execution policy to remove an execution policy for a specified scope. ```powershell Set-ExecutionPolicy -ExecutionPolicy Undefined -Scope CurrentUser Get-ExecutionPolicy -List ``` ```Output Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process Undefined CurrentUser Undefined LocalMachine RemoteSigned ``` `Set-ExecutionPolicy` uses the **ExecutionPolicy** parameter to specify the `Undefined` policy. The **Scope** parameter specifies the `CurrentUser`. To view the execution policy settings, use the `Get-ExecutionPolicy` cmdlet with the **List** parameter. ### Example 6: Set the execution policy for the current PowerShell session The `Process` scope only affects the current PowerShell session. The execution policy is saved in the environment variable `$Env:PSExecutionPolicyPreference` and is deleted when the session is closed. ```powershell Set-ExecutionPolicy -ExecutionPolicy AllSigned -Scope Process ``` ```Output Scope ExecutionPolicy ----- --------------- MachinePolicy Undefined UserPolicy Undefined Process AllSigned CurrentUser RemoteSigned LocalMachine RemoteSigned ``` The `Set-ExecutionPolicy` uses the **ExecutionPolicy** parameter to specify the `AllSigned` policy. The **Scope** parameter specifies the value `Process`. To view the execution policy settings, use the `Get-ExecutionPolicy` cmdlet with the **List** parameter. ### Example 7: Unblock a script to run it without changing the execution policy This example shows how the `RemoteSigned` execution policy prevents you from running unsigned scripts. A best practice is to read the script's code and verify it's safe _before_ using the `Unblock-File` cmdlet. The `Unblock-File` cmdlet unblocks scripts so they can run, but doesn't change the execution policy. ```powershell PS> Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope LocalMachine PS> Get-ExecutionPolicy RemoteSigned PS> .\Start-ActivityTracker.ps1 .\Start-ActivityTracker.ps1 : File .\Start-ActivityTracker.ps1 cannot be loaded. The file .\Start-ActivityTracker.ps1 is not digitally signed. The script will not execute on the system. For more information, see about_Execution_Policies at https://go.microsoft.com/fwlink/?LinkID=135170. At line:1 char:1 + .\Start-ActivityTracker.ps1 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : NotSpecified: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess PS> Unblock-File -Path .\Start-ActivityTracker.ps1 PS> Get-ExecutionPolicy RemoteSigned PS> .\Start-ActivityTracker.ps1 Task 1: ``` The `Set-ExecutionPolicy` uses the **ExecutionPolicy** parameter to specify the `RemoteSigned` policy. The policy is set for the default scope, `LocalMachine`. The `Get-ExecutionPolicy` cmdlet shows that `RemoteSigned` is the effective execution policy for the current PowerShell session. The `Start-ActivityTracker.ps1` script is executed from the current directory. The script is blocked by `RemoteSigned` because the script isn't digitally signed. For this example, the script's code was reviewed and verified as safe to run. The `Unblock-File` cmdlet uses the **Path** parameter to unblock the script. To verify that `Unblock-File` didn't change the execution policy, `Get-ExecutionPolicy` displays the effective execution policy, `RemoteSigned`. The script, `Start-ActivityTracker.ps1` is executed from the current directory. The script begins to run because it was unblocked by the `Unblock-File` cmdlet. ## PARAMETERS ### -ExecutionPolicy Specifies the execution policy. If there are no Group Policies and each scope's execution policy is set to `Undefined`, then `Restricted` becomes the effective policy for all users. The acceptable execution policy values are as follows: - `AllSigned`. Requires that all scripts and configuration files are signed by a trusted publisher, including scripts written on the local computer. - `Bypass`. Nothing is blocked and there are no warnings or prompts. - `Default`. Sets the default execution policy. `Restricted` for Windows clients or `RemoteSigned` for Windows servers. - `RemoteSigned`. Requires that all scripts and configuration files downloaded from the Internet are signed by a trusted publisher. The default execution policy for Windows server computers. - `Restricted`. Doesn't load configuration files or run scripts. The default execution policy for Windows client computers. - `Undefined`. No execution policy is set for the scope. Removes an assigned execution policy from a scope that is not set by a Group Policy. If the execution policy in all scopes is `Undefined`, the effective execution policy is `Restricted`. - `Unrestricted`. Beginning in PowerShell 6.0, this is the default execution policy for non-Windows computers and can't be changed. Loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the internet, you're prompted for permission before it runs. ```yaml Type: Microsoft.PowerShell.ExecutionPolicy Parameter Sets: (All) Aliases: Accepted values: AllSigned, Bypass, Default, RemoteSigned, Restricted, Undefined, Unrestricted Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Force Suppresses all the confirmation prompts. Use caution with this parameter to avoid unexpected results. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Scope Specifies the scope that is affected by an execution policy. The default scope is `LocalMachine`. The effective execution policy is determined by the order of precedence as follows: - `MachinePolicy` - Set by a Group Policy for all users of the computer - `UserPolicy` - Set by a Group Policy for the current user of the computer - `Process` - Affects only the current PowerShell session - `LocalMachine` - Default scope that affects all users of the computer - `CurrentUser` - Affects only the current user The `Process` scope only affects the current PowerShell session. The execution policy is saved in the environment variable `$Env:PSExecutionPolicyPreference`, rather than the registry. When the PowerShell session is closed, the variable and value are deleted. Execution policies for the `CurrentUser` scope are written to the registry hive `HKEY_LOCAL_USER`. Execution policies for the `LocalMachine` scope are written to the registry hive `HKEY_LOCAL_MACHINE`. ```yaml Type: Microsoft.PowerShell.ExecutionPolicyScope Parameter Sets: (All) Aliases: Accepted values: CurrentUser, LocalMachine, MachinePolicy, Process, UserPolicy Required: False Position: 1 Default value: LocalMachine Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### Microsoft.PowerShell.ExecutionPolicy You can pipe an execution policy object to this cmdlet. ### System.String You can pipe a string that contains the name of an execution policy to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES `Set-ExecutionPolicy` doesn't change the `MachinePolicy` and `UserPolicy` scopes because they are set by Group Policies. `Set-ExecutionPolicy` doesn't override a Group Policy, even if the user preference is more restrictive than the policy. If the Group Policy **Turn on Script Execution** is enabled for the computer or user, the user preference is saved, but it's not effective. PowerShell displays a message that explains the conflict. ## RELATED LINKS [about_Execution_Policies](../Microsoft.PowerShell.Core/About/about_Execution_Policies.md) [about_Group_Policy_Settings](../Microsoft.PowerShell.Core/About/about_Group_Policy_Settings.md) [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md) [Get-AuthenticodeSignature](Get-AuthenticodeSignature.md) [Get-ChildItem](../Microsoft.PowerShell.Management/Get-ChildItem.md) [Get-ExecutionPolicy](Get-ExecutionPolicy.md) [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md) [Set-AuthenticodeSignature](Set-AuthenticodeSignature.md) [Unblock-File](../Microsoft.PowerShell.Utility/Unblock-File.md)

#File: reference/7.6/Microsoft.PowerShell.Security/Test-FileCatalog.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/test-filecatalog?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Test-FileCatalog --- # Test-FileCatalog ## SYNOPSIS `Test-FileCatalog` validates whether the hashes contained in a catalog file (.cat) matches the hashes of the actual files in order to validate their authenticity. This cmdlet is only supported on Windows. ## SYNTAX ``` Test-FileCatalog [-Detailed] [-FilesToSkip <String[]>] [-CatalogFilePath] <String> [[-Path] <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** `Test-FileCatalog` validates the authenticity of files by comparing the file hashes of a catalog file (.cat) with the hashes of actual files on disk. If it detects any mismatches, it returns the status as ValidationFailed. Users can retrieve all this information by using the -Detailed parameter. It also displays signing status of catalog in Signature property which is equivalent to calling `Get-AuthenticodeSignature` cmdlet on the catalog file. Users can also skip any file during validation by using the -FilesToSkip parameter. This cmdlet is only supported on Windows. ## EXAMPLES ### Example 1: Create and validate a file catalog ```powershell New-FileCatalog -Path $PSHOME\Modules\Microsoft.PowerShell.Utility -CatalogFilePath \temp\Microsoft.PowerShell.Utility.cat -CatalogVersion 2.0 Test-FileCatalog -CatalogFilePath \temp\Microsoft.PowerShell.Utility.cat -Path "$PSHOME\Modules\Microsoft.PowerShell.Utility\" ``` ```Output Valid ``` ### Example 2: Validate a file catalog with detailed output ```powershell Test-FileCatalog -Detailed -CatalogFilePath \temp\Microsoft.PowerShell.Utility.cat -Path "$PSHOME\Modules\Microsoft.PowerShell.Utility\" ``` ```Output Status : Valid HashAlgorithm : SHA256 CatalogItems : {[Microsoft.PowerShell.Utility.psd1, A7028BD54018AE519381CDF5BF91F3B0417BD9345478086089ACBFAD05C899FC], [Microsoft.PowerShell.Utility.psm1, 1127E8151FB86BCB683F932E8F6538552F7195816ED351A28AE07A753B8F20DE]} PathItems : {[Microsoft.PowerShell.Utility.psd1, A7028BD54018AE519381CDF5BF91F3B0417BD9345478086089ACBFAD05C899FC], [Microsoft.PowerShell.Utility.psm1, 1127E8151FB86BCB683F932E8F6538552F7195816ED351A28AE07A753B8F20DE]} Signature : System.Management.Automation.Signature ``` ## PARAMETERS ### -CatalogFilePath A path to a catalog file (.cat) that contains the hashes to be used for validation. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Detailed Returns more information a more detailed `CatalogInformation` object that contains the files tested, their expected/actual hashes, and an Authenticode signature of the catalog file if it's signed. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FilesToSkip An array of paths that should not be tested as part of the validation. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path A folder or array of files that should be validated against the catalog file. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.IO.DirectoryInfo You can pipe a `DirectoryInfo` object representing the path to the files that need to be validated. ### System.String You can pipe a string representing the path to the files that need to be validated. ## OUTPUTS ### System.Management.Automation.CatalogValidationStatus By default, this cmdlet returns a **CatalogValidationStatus** object with a value of either `Valid` or `ValidationFailed`. ### System.Management.Automation.CatalogInformation When you use the **Detailed** parameter, the cmdlet returns a **CatalogInformation** object for each file, which can be used to analyze specific files that may or may not have passed validation, which hashes were expected vs. found, and the algorithm used in the catalog. ## NOTES This cmdlet is only available on Windows platforms. ## RELATED LINKS [New-FileCatalog](New-FileCatalog.md) [PowerShellGet](/powershell/module/PowerShellGet)

#File: reference/7.6/Microsoft.PowerShell.Security/Unprotect-CmsMessage.md

--- external help file: Microsoft.PowerShell.Security.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Security ms.date: 10/18/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.security/unprotect-cmsmessage?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Unprotect-CmsMessage --- # Unprotect-CmsMessage ## SYNOPSIS Decrypts content that has been encrypted by using the Cryptographic Message Syntax format. ## SYNTAX ### ByWinEvent (Default) ``` Unprotect-CmsMessage [-EventLogRecord] <EventLogRecord> [[-To] <CmsMessageRecipient[]>] [-IncludeContext] [<CommonParameters>] ``` ### ByContent ``` Unprotect-CmsMessage [-Content] <string> [[-To] <CmsMessageRecipient[]>] [-IncludeContext] [<CommonParameters>] ``` ### ByPath ``` Unprotect-CmsMessage [-Path] <string> [[-To] <CmsMessageRecipient[]>] [-IncludeContext] [<CommonParameters>] ``` ### ByLiteralPath ``` Unprotect-CmsMessage [-LiteralPath] <string> [[-To] <CmsMessageRecipient[]>] [-IncludeContext] [<CommonParameters>] ``` ## DESCRIPTION The `Unprotect-CmsMessage` cmdlet decrypts content that has been encrypted using the Cryptographic Message Syntax (CMS) format. The CMS cmdlets support encryption and decryption of content using the IETF standard format for cryptographically protecting messages, as documented by [RFC5652](https://tools.ietf.org/html/rfc5652). The CMS encryption standard uses public key cryptography, where the keys used to encrypt content (the public key) and the keys used to decrypt content (the private key) are separate. Your public key can be shared widely, and isn't sensitive data. If any content is encrypted with this public key, only your private key can decrypt it. For more information, see [Public-key cryptography](https://en.wikipedia.org/wiki/Public-key_cryptography). `Unprotect-CmsMessage` decrypts content that has been encrypted in CMS format. You can run this cmdlet to decrypt content that you have encrypted by running the `Protect-CmsMessage` cmdlet. You can specify content that you want to decrypt as a string, by the encryption event log record ID number, or by path to the encrypted content. The `Unprotect-CmsMessage` cmdlet returns the decrypted content. Support for Linux and macOS was added in PowerShell 7.1. ## EXAMPLES ### Example 1: Decrypt a message In the following example, you decrypt content that's located at the literal path `C:\Users\Test\Documents\PowerShell`. For the value of the required **To** parameter, this example uses the thumbprint of the certificate that was used to perform the encryption. The decrypted message, "Try the new Break All command," is the result. ```powershell $parameters = @{ LiteralPath = "C:\Users\Test\Documents\PowerShell\Future_Plans.txt" To = '0f 8j b1 ab e0 ce 35 1d 67 d2 f2 6f a2 d2 00 cl 22 z9 m9 85' } Unprotect-CmsMessage -LiteralPath @parameters ``` ```Output Try the new Break All command ``` ### Example 2: Decrypt an encrypted event log message The following example gets an encrypted event from the PowerShell event log and decrypts it using `Unprotect-CmsMessage`. ```powershell $event = Get-WinEvent Microsoft-Windows-PowerShell/Operational -MaxEvents 1 | Where-Object Id -EQ 4104 Unprotect-CmsMessage -EventLogRecord $event ``` ### Example 3: Decrypt encrypted event log messages using the pipeline The following example gets all encrypted events from the PowerShell event log and decrypts them using `Unprotect-CmsMessage`. ```powershell Get-WinEvent Microsoft-Windows-PowerShell/Operational | Where-Object Id -EQ 4104 | Unprotect-CmsMessage ``` ## PARAMETERS ### -Content Specifies an encrypted string, or a variable containing an encrypted string. ```yaml Type: System.String Parameter Sets: ByContent Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -EventLogRecord Specifies an event log record that contains a CMS encrypted message. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: ByWinEvent Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -IncludeContext ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to encrypted content that you want to decrypt. Unlike **Path**, the value of **LiteralPath** is used exactly as it's typed. No characters are interpreted as wildcard characters. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String Parameter Sets: ByLiteralPath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to encrypted content that you want to decrypt. ```yaml Type: System.String Parameter Sets: ByPath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -To Specifies one or more CMS message recipients, identified in any of the following formats: - An actual certificate (as retrieved from the Certificate provider). - Path to the a file containing the certificate. - Path to a directory containing the certificate. - Thumbprint of the certificate (used to look in the certificate store). - Subject name of the certificate (used to look in the certificate store). ```yaml Type: System.Management.Automation.CmsMessageRecipient[] Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Diagnostics.Eventing.Reader.EventLogRecord ### System.String You can pipe an object containing encrypted content to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns the unencrypted message. ## NOTES ## RELATED LINKS [about_Providers](../Microsoft.PowerShell.Core/About/about_Providers.md) [Get-CmsMessage](Get-CmsMessage.md) [Protect-CmsMessage](Protect-CmsMessage.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Add-Member.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 03/06/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/add-member?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Add-Member --- # Add-Member ## SYNOPSIS Adds custom properties and methods to an instance of a PowerShell object. ## SYNTAX ### TypeNameSet (Default) ``` Add-Member -InputObject <PSObject> -TypeName <String> [-PassThru] [<CommonParameters>] ``` ### NotePropertyMultiMemberSet ``` Add-Member -InputObject <PSObject> [-TypeName <String>] [-Force] [-PassThru] [-NotePropertyMembers] <IDictionary> [<CommonParameters>] ``` ### NotePropertySingleMemberSet ``` Add-Member -InputObject <PSObject> [-TypeName <String>] [-Force] [-PassThru] [-NotePropertyName] <String> [-NotePropertyValue] <Object> [<CommonParameters>] ``` ### MemberSet ``` Add-Member -InputObject <PSObject> [-MemberType] <PSMemberTypes> [-Name] <String> [[-Value] <Object>] [[-SecondValue] <Object>] [-TypeName <String>] [-Force] [-PassThru] [<CommonParameters>] ``` ## DESCRIPTION The `Add-Member` cmdlet lets you add members (properties and methods) to an instance of a PowerShell object. For instance, you can add a **NoteProperty** member that contains a description of the object or a **ScriptMethod** member that runs a script to change the object. To use `Add-Member`, pipe the object to `Add-Member`, or use the **InputObject** parameter to specify the object. The **MemberType** parameter indicates the type of member that you want to add. The **Name** parameter assigns a name to the new member, and the **Value** parameter sets the value of the member. The properties and methods that you add are added only to the particular instance of the object that you specify. `Add-Member` doesn't change the object type. To create a new object type, use the `Add-Type` cmdlet. You can also use the `Export-Clixml` cmdlet to save the instance of the object, including the additional members, in a file. Then you can use the `Import-Clixml` cmdlet to re-create the instance of the object from the information that's stored in the exported file. Beginning in Windows PowerShell 3.0, `Add-Member` has new features that make it easier to add note properties to objects. You can use the **NotePropertyName** and **NotePropertyValue** parameters to define a note property or use the **NotePropertyMembers** parameter, which takes a hash table of note property names and values. Also, beginning in Windows PowerShell 3.0, the **PassThru** parameter, which generates an output object, is needed less frequently. `Add-Member` now adds the new members directly to the input object of more types. For more information, see the **PassThru** parameter description. ## EXAMPLES ### Example 1: Add a note property to a PSObject The following example adds a **Status** note property with a value of "Done" to the **FileInfo** object that represents the `Test.txt` file. The first command uses the `Get-ChildItem` cmdlet to get a **FileInfo** object representing the `Test.txt` file. It saves it in the `$a` variable. The second command adds the note property to the object in `$a`. The third command uses dot notation to get the value of the **Status** property of the object in `$a`. As the output shows, the value is `Done`. ```powershell $A = Get-ChildItem C:\ps-test\test.txt $A | Add-Member -NotePropertyName Status -NotePropertyValue Done $A.Status ``` ```Output Done ``` ### Example 2: Add an alias property to a PSObject The following example adds a **Size** alias property to the object that represents the `Test.txt` file. The new property is an alias for the **Length** property. The first command uses the `Get-ChildItem` cmdlet to get the `Test.txt` **FileInfo** object. The second command adds the **Size** alias property. The third command uses dot notation to get the value of the new **Size** property. ```powershell $A = Get-ChildItem C:\Temp\test.txt $A | Add-Member -MemberType AliasProperty -Name Size -Value Length $A.Size ``` ```Output 2394 ``` ### Example 3: Add a StringUse note property to a string This example adds the **StringUse** note property to a string. Because `Add-Member` can't add types to **String** input objects, you can specify the **PassThru** parameter to generate an output object. The last command in the example displays the new property. This example uses the **NotePropertyMembers** parameter. The value of the **NotePropertyMembers** parameter is a hash table. The key is the note property name, **StringUse**, and the value is the note property value, **Display**. ```powershell $A = "A string" $A = $A | Add-Member -NotePropertyMembers @{StringUse="Display"} -PassThru $A.StringUse ``` ```Output Display ``` ### Example 4: Add a script method to a FileInfo object This example adds the **SizeInMB** script method to a **FileInfo** object that calculates the file size to the nearest MegaByte. The second command creates a **ScriptBlock** that uses the **Round** static method from the `[Math]` type to round the file size to the second decimal place. The **Value** parameter also uses the `$this` automatic variable, which represents the current object. The `$this` variable is valid only in script blocks that define new properties and methods. The last command uses dot notation to call the new **SizeInMB** script method on the object in the `$A` variable. ```powershell $A = Get-ChildItem C:\Temp\test.txt $S = {[Math]::Round(($this.Length / 1MB), 2)} $A | Add-Member -MemberType ScriptMethod -Name "SizeInMB" -Value $S $A.SizeInMB() ``` ```Output 0.43 ``` ### Example 5: Create a custom object This example creates an **Asset** custom object. The `New-Object` cmdlet creates a **PSObject** that's saved in the `$Asset` variable. The `[ordered]` type accelerator creates an ordered dictionary that's stored in the `$d` variable. Piping `$Asset` to `Add-Member` adds the key-value pairs in the dictionary to the object as **NoteProperty** members. **TypeName** parameter assigns the type `Asset` to the **PSObject**. The `Get-Member` cmdlet shows the type and properties of the object. However, the properties are listed in alphabetical order, not in the order that they were added. ```powershell $Asset = New-Object -TypeName psobject $d = [ordered]@{Name="Server30"; System="Server Core"; PSVersion="4.0"} $Asset | Add-Member -NotePropertyMembers $d -TypeName Asset $Asset | Get-Member -MemberType Properties ``` ```Output TypeName: Asset Name MemberType Definition ---- ---------- ---------- Name NoteProperty string Name=Server30 PSVersion NoteProperty string PSVersion=4.0 System NoteProperty string System=Server Core ``` ```powershell $Asset.psobject.Properties | Format-Table Name, MemberType, TypeNameOfValue, Value ``` ```Output Name MemberType TypeNameOfValue Value ---- ---------- --------------- ----- Name NoteProperty System.String Server30 System NoteProperty System.String Server Core PSVersion NoteProperty System.String 4.0 ``` Inspecting the raw list of properties shows the properties in the order that they were added to the object. `Format-Table` is used in this example to create output similar to `Get-Member`. ### Example 6: Add an AliasProperty to an object In this example we create a custom object that contains two **NoteProperty** members. The type for a **NoteProperty** reflects the type of the value stored in the property. In this case, the **Age** property is a string. ```powershell PS> $obj = [pscustomobject]@{ Name = 'Doris' Age = '20' } PS> $obj | Add-Member -MemberType AliasProperty -Name 'IntAge' -Value Age -SecondValue uint32 PS> $obj | Get-Member TypeName: System.Management.Automation.PSCustomObject Name MemberType Definition ---- ---------- ---------- IntAge AliasProperty IntAge = (System.UInt32)Age Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() ToString Method string ToString() Age NoteProperty string Age=20 Name NoteProperty string Name=Doris PS> $obj Name Age IntAge ---- --- ------ Doris 20 20 PS> $obj.Age + 1 201 PS> $obj.IntAge + 1 21 ``` The **IntAge** property is an **AliasProperty** for the **Age** property, but the type is guaranteed to be **uint32**. ### Example 7: Add get and set methods to a custom object This examples shows how to define **Get** and **Set** methods that access a deeply nested property. ```powershell $user = [pscustomobject]@{ Name = 'User1' Age = 29 StartDate = [datetime]'2019-05-05' Position = [pscustomobject]@{ DepartmentName = 'IT' Role = 'Manager' } } $addMemberSplat = @{ MemberType = 'ScriptProperty' Name = 'Title' Value = { $this.Position.Role } # getter SecondValue = { $this.Position.Role = $args[0] } # setter } $user | Add-Member @addMemberSplat $user | Get-Member ``` ```Output 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() Age NoteProperty int Age=29 Name NoteProperty string Name=User1 Position NoteProperty System.Management.Automation.PSCustomObject Position=@{DepartmentName=IT; Role=Manager} StartDate NoteProperty datetime StartDate=5/5/2019 12:00:00 AM Title ScriptProperty System.Object Title {get= $this.Position.Role ;set= $this.Position.Role = $args[0] ;} ``` ```powershell $user.Title = 'Dev Manager' ``` ```Output Name : User1 Age : 29 StartDate : 5/5/2019 12:00:00 AM Position : @{DepartmentName=IT; Role=Dev Manager} Title : Dev Manager ``` Notice that the **Title** property is a **ScriptProperty** that has a **Get** and **Set** method. When we assign a new value to the **Title** property, the **Set** method is called and changes the value of the **Role** property in the **Position** property. ## PARAMETERS ### -Force By default, `Add-Member` can't add a new member if the object already has a member with the same. When you use the **Force** parameter, `Add-Member` replaces the existing member with the new member. You can't use the **Force** parameter to replace a standard member of a type. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: MemberSet, NotePropertySingleMemberSet, NotePropertyMultiMemberSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the object to which the new member is added. Enter a variable that contains the objects, or type a command or expression that gets the objects. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -MemberType Specifies the type of the member to add. This parameter is required. The acceptable values for this parameter are: - AliasProperty - CodeMethod - CodeProperty - NoteProperty - ScriptMethod - ScriptProperty For information about these values, see [PSMemberTypes Enumeration](xref:System.Management.Automation.PSMemberTypes) in the PowerShell SDK. Not all objects have every type of member. If you specify a member type that the object doesn't have, PowerShell returns an error. ```yaml Type: System.Management.Automation.PSMemberTypes Parameter Sets: MemberSet Aliases: Type Accepted values: AliasProperty, CodeMethod, CodeProperty, NoteProperty, ScriptMethod, ScriptProperty Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies the name of the member that this cmdlet adds. ```yaml Type: System.String Parameter Sets: MemberSet Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NotePropertyMembers Specifies a hashtable or ordered dictionary that contains key-value pair representing **NoteProperty** names and their values. For more information about hash tables and ordered dictionaries in PowerShell, see [about_Hash_Tables](../Microsoft.PowerShell.Core/About/about_Hash_Tables.md). This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Collections.IDictionary Parameter Sets: NotePropertyMultiMemberSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NotePropertyName Specifies the note property name. Use this parameter with the **NotePropertyValue** parameter. This parameter is optional. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String Parameter Sets: NotePropertySingleMemberSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NotePropertyValue Specifies the note property value. Use this parameter with the **NotePropertyName** parameter. This parameter is optional. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Object Parameter Sets: NotePropertySingleMemberSet Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet doesn't generate any output. For most objects, `Add-Member` adds the new members to the input object. However, when the input object is a string, `Add-Member` can't add the member to the input object. For these objects, use the **PassThru** parameter to create an output object. In Windows PowerShell 2.0, `Add-Member` added members only to the **PSObject** wrapper of objects, not to the object. Use the **PassThru** parameter to create an output object for any object that has a **PSObject** wrapper. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SecondValue Specifies optional additional information about **AliasProperty**, **ScriptProperty**, or **CodeProperty** members. If used when adding an **AliasProperty**, this parameter must be a data type. A conversion to the specified data type is added to the value of the **AliasProperty**. For example, if you add an **AliasProperty** that provides an alternate name for a string property, you can also specify a **SecondValue** parameter of **System.Int32** to indicate that the value of that string property should be converted to an integer when accessed using the corresponding **AliasProperty**. For a **CodeProperty**, the value must be a reference to a method that implements a **Set** accessor. Use the `GetMethod()` method of a type reference to get a reference to a method. The method must take a single parameter that's a **PSObject**. The **Get** accessor is assigned using the **Value** parameter. For a **ScriptProperty**, the value must be a script block that implements a **Set** accessor. The **Get** accessor is assigned using the **Value** parameter. ```yaml Type: System.Object Parameter Sets: MemberSet Aliases: Required: False Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TypeName Specifies a name for the type. When the type is a class in the **System** namespace or a type that has a type accelerator, you can enter the short name of the type. Otherwise, the full type name is required. This parameter is effective only when the **InputObject** is a **PSObject**. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String Parameter Sets: TypeNameSet, NotePropertyMultiMemberSet, NotePropertySingleMemberSet, MemberSet Aliases: Required: True (TypeNameSet), False (NotePropertyMultiMemberSet, NotePropertySingleMemberSet, MemberSet) Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Value Specifies the initial value of the added member. If you add an **AliasProperty**, **CodeProperty**, or **ScriptProperty** member, you can supply additional information using the **SecondValue** parameter. - For an **AliasProperty**, the value must be the name of the property being aliased. - For a **CodeMethod**, the value must be a reference to a method. Use the `GetMethod()` method of a type reference to get a reference to a method. - For a **CodeProperty**, the value must be a reference to a method that implements a **Get** accessor. Use the `GetMethod()` method of a type reference to get a reference to a method. reference. The method must take a single parameter that's a **PSObject**. The **Set** accessor is assigned using the **SecondValue** parameter. - For a **ScriptMethod**, the value must be a script block. - For a **ScriptProperty**, the value must be a script block that implements a **Get** accessor. The **Set** accessor is assigned using the **SecondValue** parameter. ```yaml Type: System.Object Parameter Sets: MemberSet Aliases: Required: False Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Object When you use the **PassThru** parameter, this cmdlet returns the newly extended object. ## NOTES You can add members only to **PSObject** type objects. To determine whether an object is a **PSObject** object, use the `-is` operator. For instance, to test an object stored in the `$obj` variable, type `$obj -is [psobject]`. **PSObject** type objects maintain their list of members in the order that the members were added to the object. The names of the **MemberType**, **Name**, **Value**, and **SecondValue** parameters are optional. If you omit the parameter names, the unnamed parameter values must appear in this order: **MemberType**, **Name**, **Value**, and **SecondValue**. If you include the parameter names, the parameters can appear in any order. You can use the `$this` automatic variable in script blocks that define the values of new properties and methods. The `$this` variable refers to the instance of the object to which the properties and methods are being added. For more information about the `$this` variable, see [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md). ## RELATED LINKS [Export-Clixml](Export-Clixml.md) [Get-Member](Get-Member.md) [Import-Clixml](Import-Clixml.md) [New-Object](New-Object.md) [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md) [System.Type.GetMethod()](/dotnet/api/system.type.getmethod)

#File: reference/7.6/Microsoft.PowerShell.Utility/Add-Type.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 11/25/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/add-type?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Add-Type --- # Add-Type ## SYNOPSIS Adds a Microsoft .NET class to a PowerShell session. ## SYNTAX ### FromSource (Default) ``` Add-Type [-TypeDefinition] <String> [-Language <Language>] [-ReferencedAssemblies <String[]>] [-OutputAssembly <String>] [-OutputType <OutputAssemblyType>] [-PassThru] [-IgnoreWarnings] [-CompilerOptions <String[]>] [<CommonParameters>] ``` ### FromMember ``` Add-Type [-Name] <String> [-MemberDefinition] <String[]> [-Namespace <String>] [-UsingNamespace <String[]>] [-Language <Language>] [-ReferencedAssemblies <String[]>] [-OutputAssembly <String>] [-OutputType <OutputAssemblyType>] [-PassThru] [-IgnoreWarnings] [-CompilerOptions <String[]>] [<CommonParameters>] ``` ### FromPath ``` Add-Type [-Path] <String[]> [-ReferencedAssemblies <String[]>] [-OutputAssembly <String>] [-OutputType <OutputAssemblyType>] [-PassThru] [-IgnoreWarnings] [-CompilerOptions <String[]>] [<CommonParameters>] ``` ### FromLiteralPath ``` Add-Type -LiteralPath <String[]> [-ReferencedAssemblies <String[]>] [-OutputAssembly <String>] [-OutputType <OutputAssemblyType>] [-PassThru] [-IgnoreWarnings] [-CompilerOptions <String[]>] [<CommonParameters>] ``` ### FromAssemblyName ``` Add-Type -AssemblyName <String[]> [-PassThru] [<CommonParameters>] ``` ## DESCRIPTION The `Add-Type` cmdlet lets you define a Microsoft .NET Core class in your PowerShell session. You can then instantiate objects, by using the `New-Object` cmdlet, and use the objects just as you would use any .NET Core object. If you add an `Add-Type` command to your PowerShell profile, the class is available in all PowerShell sessions. You can specify the type by specifying an existing assembly or source code files, or you can specify the source code inline or saved in a variable. You can even specify only a method and `Add-Type` defines and generates the class. On Windows, you can use this feature to make Platform Invoke (P/Invoke) calls to unmanaged functions in PowerShell. If you specify source code, `Add-Type` compiles the specified source code and generates an in-memory assembly that contains the new .NET Core types. You can use the parameters of `Add-Type` to specify an alternate language and compiler, C# is the default, compiler options, assembly dependencies, the class namespace, the names of the type, and the resulting assembly. Beginning in PowerShell 7, `Add-Type` doesn't compile a type if a type with the same name already exists. Also, `Add-Type` looks for assemblies in a `ref` folder under the folder that contains `pwsh.dll`. ## EXAMPLES ### Example 1: Add a .NET type to a session This example adds the **BasicTest** class to the session by specifying source code that's stored in a variable. The **BasicTest** class is used to add integers, create an object, and multiply integers. ```powershell $Source = @" public class BasicTest { public static int Add(int a, int b) { return (a + b); } public int Multiply(int a, int b) { return (a * b); } } "@ Add-Type -TypeDefinition $Source [BasicTest]::Add(4, 3) $BasicTestObject = New-Object BasicTest $BasicTestObject.Multiply(5, 2) ``` The `$Source` variable stores the source code for the class. The type has a static method called `Add` and a non-static method called `Multiply`. The `Add-Type` cmdlet adds the class to the session. Because it's using inline source code, the command uses the **TypeDefinition** parameter to specify the code in the `$Source` variable. The `Add` static method of the **BasicTest** class uses the double-colon characters (`::`) to specify a static member of the class. The integers are added and the sum is displayed. The `New-Object` cmdlet instantiates an instance of the **BasicTest** class. It saves the new object in the `$BasicTestObject` variable. `$BasicTestObject` uses the `Multiply` method. The integers are multiplied and the product is displayed. ### Example 2: Examine an added type This example uses the `Get-Member` cmdlet to examine the objects that the `Add-Type` and `New-Object` cmdlets created in **Example 1**. ```powershell [BasicTest] | Get-Member ``` ```Output TypeName: System.RuntimeType Name MemberType Definition ---- ---------- ---------- AsType Method type AsType() Clone Method System.Object Clone(), System.Object ICloneable.Clone() Equals Method bool Equals(System.Object obj), bool Equals(type o) FindInterfaces Method type[] FindInterfaces(System.Reflection.TypeFilter filter... ... ``` ```powershell [BasicTest] | Get-Member -Static ``` ```Output TypeName: BasicTest Name MemberType Definition ---- ---------- ---------- Add Method static int Add(int a, int b) Equals Method static bool Equals(System.Object objA, System.Object objB) new Method BasicTest new() ReferenceEquals Method static bool ReferenceEquals(System.Object objA, System.Object objB) ``` ```powershell $BasicTestObject | Get-Member ``` ```Output TypeName: BasicTest Name MemberType Definition ---- ---------- ---------- Equals Method bool Equals(System.Object obj) GetHashCode Method int GetHashCode() GetType Method type GetType() Multiply Method int Multiply(int a, int b) ToString Method string ToString() ``` The `Get-Member` cmdlet gets the type and members of the **BasicTest** class that `Add-Type` added to the session. The `Get-Member` command reveals that it's a **System.RuntimeType** object, which is derived from the **System.Object** class. The `Get-Member` **Static** parameter gets the static properties and methods of the **BasicTest** class. The output shows that the `Add` method is included. The `Get-Member` cmdlet gets the members of the object stored in the `$BasicTestObject` variable. `$BasicTestObject` was created by using the `New-Object` cmdlet with the **BasicTest** class. The output reveals that the value of the `$BasicTestObject` variable is an instance of the **BasicTest** class and that it includes a member called `Multiply`. ### Example 3: Add types from an assembly This example adds the classes from the `JsonSchema.NET.dll` assembly to the current session. ```powershell Set-Location -Path $PSHOME $AccType = Add-Type -AssemblyName *jsonschema* -PassThru ``` `Set-Location` uses the **Path** parameter to specify the `$PSHOME` variable. The variable references the PowerShell installation directory where the DLL file is located. The `$AccType` variable stores an object created with the `Add-Type` cmdlet. `Add-Type` uses the **AssemblyName** parameter to specify the name of the assembly. The asterisk (`*`) wildcard character allows you to get the correct assembly even when you aren't sure of the name or its spelling. The **PassThru** parameter generates objects that represent the classes that are added to the session. ### Example 4: Call native Windows APIs This example demonstrates how to call native Windows APIs in PowerShell. `Add-Type` uses the Platform Invoke (P/Invoke) mechanism to call a function in `User32.dll` from PowerShell. This example only works on computers running the Windows operating system. ```powershell $Signature = @" [DllImport("user32.dll")]public static extern bool ShowWindowAsync(IntPtr hWnd, int nCmdShow); "@ $addTypeSplat = @{ MemberDefinition = $Signature Name = "Win32ShowWindowAsync" Namespace = 'Win32Functions' PassThru = $true } $ShowWindowAsync = Add-Type @addTypeSplat # Minimize the PowerShell console $ShowWindowAsync::ShowWindowAsync((Get-Process -Id $PID).MainWindowHandle, 2) # Restore the PowerShell console $ShowWindowAsync::ShowWindowAsync((Get-Process -Id $PID).MainWindowHandle, 4) ``` The `$Signature` variable stores the C# signature of the `ShowWindowAsync` function. To ensure that the resulting method is visible in a PowerShell session, the `public` keyword was added to the standard signature. For more information, see [ShowWindowAsync](/windows/win32/api/winuser/nf-winuser-showwindowasync) function. The `$ShowWindowAsync` variable stores the object created by the `Add-Type` **PassThru** parameter. The `Add-Type` cmdlet adds the `ShowWindowAsync` function to the PowerShell session as a static method. The command uses the **MemberDefinition** parameter to specify the method definition saved in the `$Signature` variable. The command uses the **Name** and **Namespace** parameters to specify a name and namespace for the class. The **PassThru** parameter generates an object that represents the types. The new `ShowWindowAsync` static method is used in the commands to minimize and restore the PowerShell console. The method takes two parameters: the window handle, and an integer that specifies how the window is displayed. To minimize the PowerShell console, `ShowWindowAsync` uses the `Get-Process` cmdlet with the `$PID` automatic variable to get the process that's hosting the current PowerShell session. Then it uses the **MainWindowHandle** property of the current process and a value of `2`, which represents the `SW_MINIMIZE` value. To restore the window, `ShowWindowAsync` uses a value of `4` for the window position, which represents the `SW_RESTORE` value. To maximize the window, use the value of `3` that represents `SW_MAXIMIZE`. ## PARAMETERS ### -AssemblyName Specifies the name of an assembly that includes the types. `Add-Type` takes the types from the specified assembly. This parameter is required when you're creating types based on an assembly name. Enter the full or simple name, also known as the partial name, of an assembly. Wildcard characters are permitted in the assembly name. If you enter a simple or partial name, `Add-Type` resolves it to the full name, and then uses the full name to load the assembly. Using the **Path** or **LiteralPath** parameters guarantees that you are loading the assembly that you intended to load. When you use the **AssemblyName** parameter, PowerShell asks .NET to resolve the assembly name using the standard .NET assembly resolution process. Since .NET searches the application folder first, `Add-Type` might load an assembly from `$PSHOME` instead of the version in the current folder. For more information, see [Assembly location](/dotnet/standard/assembly/location). If .NET fails to resolve the name, PowerShell then looks in the current location to find the assembly. When you use wildcards in the **AssemblyName** parameter, the .NET assembly resolution process fails causing PowerShell to look in the current location. ```yaml Type: System.String[] Parameter Sets: FromAssemblyName Aliases: AN Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -CompilerOptions Specifies the options for the source code compiler. These options are sent to the compiler without revision. This parameter allows you to direct the compiler to generate an executable file, embed resources, or set command-line options, such as the `/unsafe` option. ```yaml Type: System.String[] Parameter Sets: FromSource, FromMember, FromPath, FromLiteralPath Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -IgnoreWarnings Ignores compiler warnings. Use this parameter to prevent `Add-Type` from handling compiler warnings as errors. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: FromSource, FromMember, FromPath, FromLiteralPath Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Language Specifies the language that's used in the source code. The acceptable value for this parameter is `CSharp`. ```yaml Type: Microsoft.PowerShell.Commands.Language Parameter Sets: FromSource, FromMember Aliases: Accepted values: CSharp Required: False Position: Named Default value: CSharp Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to source code files or assembly DLL files that contain the types. Unlike **Path**, the value of the **LiteralPath** parameter is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. Using the **Path** or **LiteralPath** parameters guarantees that you are loading the assembly that you intended to load. ```yaml Type: System.String[] Parameter Sets: FromLiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MemberDefinition Specifies new properties or methods for the class. `Add-Type` generates the template code that's required to support the properties or methods. On Windows, you can use this feature to make Platform Invoke (P/Invoke) calls to unmanaged functions in PowerShell. ```yaml Type: System.String[] Parameter Sets: FromMember Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies the name of the class to create. This parameter is required when generating a type from a member definition. The type name and namespace must be unique within a session. You can't unload a type or change it. To change the code for a type, you must change the name or start a new PowerShell session. Otherwise, the command fails. ```yaml Type: System.String Parameter Sets: FromMember Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Namespace By default, this command creates the type in the **Microsoft.PowerShell.Commands.AddType.AutoGeneratedTypes** namespace. When you use this parameter, the type is created in the specified namespace. If the value an empty string, the type is created in the global namespace. ```yaml Type: System.String Parameter Sets: FromMember Aliases: NS Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OutputAssembly Generates a DLL file for the assembly with the specified name in the location. Enter an optional path and filename. Wildcard characters are permitted. By default, `Add-Type` generates the assembly only in memory. If you output the assembly to a file you should include the **PassThru** parameter to return the type from the newly created assembly. ```yaml Type: System.String Parameter Sets: FromSource, FromMember, FromPath, FromLiteralPath Aliases: OA Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -OutputType Specifies the output type of the output assembly. By default, no output type is specified. This parameter is valid only when an output assembly is specified in the command. For more information about the values, see [OutputAssemblyType Enumeration](/dotnet/api/microsoft.powershell.commands.outputassemblytype). The acceptable values for this parameter are as follows: - `ConsoleApplication` - `Library` - `WindowsApplication` > [!IMPORTANT] > As of PowerShell 7.1, `ConsoleApplication` and `WindowsApplication` aren't supported and > PowerShell throws a terminating error if either are specified as values for the **OutputType** > parameter. ```yaml Type: Microsoft.PowerShell.Commands.OutputAssemblyType Parameter Sets: FromSource, FromMember, FromPath, FromLiteralPath Aliases: OT Accepted values: ConsoleApplication, Library, WindowsApplication Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns a **System.Runtime** object that represents the types that were added. By default, this cmdlet doesn't generate any output. Use this parameter if you used **OutputAssembly** to create a DLL file and you want to return the type from the newly created assembly. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to source code files or assembly DLL files that contain the types. If you submit source code files, `Add-Type` compiles the code in the files and creates an in-memory assembly of the types. The file extension specified in the value of **Path** determines the compiler that `Add-Type` uses. Using the **Path** or **LiteralPath** parameters guarantees that you are loading the assembly that you intended to load. ```yaml Type: System.String[] Parameter Sets: FromPath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ReferencedAssemblies Specifies the assemblies upon which the type depends. By default, `Add-Type` references `System.dll` and `System.Management.Automation.dll`. Beginning in PowerShell 6, **ReferencedAssemblies** doesn't include the default .NET assemblies. You must include a specific reference to them in the value passed to this parameter. ```yaml Type: System.String[] Parameter Sets: FromSource, FromMember, FromPath, FromLiteralPath Aliases: RA Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TypeDefinition Specifies the source code that contains the type definitions. Enter the source code in a string or here-string, or enter a variable that contains the source code. For more information about here-strings, see [about_Quoting_Rules](../Microsoft.PowerShell.Core/about/about_Quoting_Rules.md). Include a namespace declaration in your type definition. If you omit the namespace declaration, your type might have the same name as another type or the shortcut for another type, causing an unintentional overwrite. For example, if you define a type called **Exception**, scripts that use **Exception** as the shortcut for **System.Exception** will fail. ```yaml Type: System.String Parameter Sets: FromSource Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UsingNamespace Specifies other namespaces that are required for the class. This is much like the C# keyword, `Using`. By default, `Add-Type` references the **System** namespace. When the **MemberDefinition** parameter is used, `Add-Type` also references the **System.Runtime.InteropServices** namespace by default. The namespaces that you add by using the **UsingNamespace** parameter are referenced in addition to the default namespaces. ```yaml Type: System.String[] Parameter Sets: FromMember Aliases: Using Required: False Position: Named Default value: System namespace Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Type When you use the **PassThru** parameter, this cmdlet returns a **System.Type** object representing the new type. ## NOTES The types that you add exist only in the current session. To use the types in all sessions, add them to your PowerShell profile. For more information about the profile, see [about_Profiles](../Microsoft.PowerShell.Core/About/about_Profiles.md). Type names and namespaces must be unique within a session. You can't unload a type or change it. If you need to change the code for a type, you must change the name or start a new PowerShell session. Otherwise, the command fails. In Windows PowerShell (version 5.1 and below), you need to use `Add-Type` for anything that isn't already loaded. Most commonly, this applies to assemblies found in the Global Assembly Cache (GAC). In PowerShell 6 and higher, there is no GAC, so PowerShell installs its own assemblies in `$PSHOME`. These assemblies are automatically loaded on request, so there's no need to use `Add-Type` to load them. However, using `Add-Type` is still permitted to allow scripts to be implicitly compatible with any version of PowerShell. Assemblies in the GAC can be loaded by type name, rather than by path. Loading assemblies from an arbitrary path requires `Add-Type`, since those assemblies can't not be loaded automatically. ## RELATED LINKS [about_Profiles](../Microsoft.PowerShell.Core/About/about_profiles.md) [about_Quoting_Rules](../Microsoft.PowerShell.Core/About/about_Quoting_Rules.md) [Add-Member](Add-Member.md) [New-Object](New-Object.md) [OutputAssemblyType](/dotnet/api/microsoft.powershell.commands.outputassemblytype) [Platform Invoke (P/Invoke)](/dotnet/standard/native-interop/pinvoke) [Where-Object](../Microsoft.PowerShell.Core/Where-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Clear-Variable.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/clear-variable?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Clear-Variable --- # Clear-Variable ## SYNOPSIS Deletes the value of a variable. ## SYNTAX ``` Clear-Variable [-Name] <String[]> [-Include <String[]>] [-Exclude <String[]>] [-Force] [-PassThru] [-Scope <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Clear-Variable` cmdlet deletes the data stored in a variable, but it does not delete the variable. As a result, the value of the variable is NULL (empty). If the variable has a specified data or object type, this cmdlet preserves the type of the object stored in the variable. ## EXAMPLES ### Example 1: Remove the value of global variables that begin with a search string ```powershell Clear-Variable my* -Scope Global ``` This command removes the value of global variables that have names that begin with my. ### Example 2: Clear a variable in a child scope but not the parent scope ```powershell $a=3 &{ Clear-Variable a } $a ``` ```Output 3 ``` These commands demonstrate that clearing a variable in a child scope does not clear the value in the parent scope. The first command sets the value of the variable `$a` to 3. The second command uses the invoke operator (`&`) to run the `Clear-Variable` command in a new scope. The variable is cleared in the child scope (although it did not exist), but it is not cleared in the local scope. The third command, which gets the value of `$a`, shows that the value 3 is unaffected. ### Example 3: Delete the value of the specified variable ```powershell Clear-Variable -Name "Processes" ``` This command deletes the value of the variable named Processes. After the cmdlet completes the operation, the variable named Processes still exists, but the value is null. ## PARAMETERS ### -Exclude Specifies an array of items that this cmdlet omits in the operation. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Allows the cmdlet to clear a variable even if it is read-only. Even using the Force parameter, the cmdlet cannot clear constants. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies an array of items that this cmdlet includes in the operation. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Name Specifies the name of the variable to be cleared. Wildcards are permitted. This parameter is required, but the parameter name **Name** is optional. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Scope Specifies the scope in which this alias is valid. The acceptable values for this parameter are: - `Global` - `Local` - `Script` You can also use a number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). Local is the default. For more information, see [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSVariable When you use the **PassThru** parameter, this cmdlet returns a **PSVariable** object representing the cleared variable. ## NOTES PowerShell includes the following aliases for `Clear-Variable`: - All platforms: - `clv` - To delete a variable, along with its value, use `Remove-Variable` or `Remove-Item`. This cmdlet does not delete the values of variables that are set as constants or owned by the system, even if you use the **Force** parameter. If the variable that you are clearing does not exist, the cmdlet has no effect. It does not create a variable with a null value. ## RELATED LINKS [Get-Variable](Get-Variable.md) [New-Variable](New-Variable.md) [Remove-Variable](Remove-Variable.md) [Set-Variable](Set-Variable.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Compare-Object.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 06/11/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/compare-object?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Compare-Object --- # Compare-Object ## SYNOPSIS Compares two sets of objects. ## SYNTAX ``` Compare-Object [-ReferenceObject] <PSObject[]> [-DifferenceObject] <PSObject[]> [-SyncWindow <Int32>] [-Property <Object[]>] [-ExcludeDifferent] [-IncludeEqual] [-PassThru] [-Culture <String>] [-CaseSensitive] [<CommonParameters>] ``` ## DESCRIPTION The `Compare-Object` cmdlet compares two sets of objects. One set of objects is the **reference**, and the other set of objects is the **difference**. `Compare-Object` checks for available methods of comparing a whole object. If it can't find a suitable method, it calls the **ToString()** methods of the input objects and compares the string results. You can provide one or more properties to be used for comparison. When properties are provided, the cmdlet compares the values of those properties only. The result of the comparison indicates whether a property value appeared only in the **reference** object (`<=`) or only in the **difference** object (`=>`). If the **IncludeEqual** parameter is used, (`==`) indicates the value is in both objects. If the **reference** or the **difference** objects are null (`$null`), `Compare-Object` generates a terminating error. Some examples use splatting to reduce the line length of the code samples. For more information, see [about_Splatting](../Microsoft.PowerShell.Core/About/about_Splatting.md). ## EXAMPLES ### Example 1 - Compare the content of two text files This example compares the contents of two text files. The example uses the following two text files, with each value on a separate line. - `Testfile1.txt` contains the values: dog, squirrel, and bird. - `Testfile2.txt` contains the values: cat, bird, and racoon. The output displays only the lines that are different between the files. `Testfile1.txt` is the **reference** object (`<=`) and `Testfile2.txt`is the **difference** object (`=>`). Lines with content that appear in both files aren't displayed. ```powershell Compare-Object -ReferenceObject (Get-Content -Path C:\Test\Testfile1.txt) -DifferenceObject (Get-Content -Path C:\Test\Testfile2.txt) ``` ```Output InputObject SideIndicator ----------- ------------- cat => racoon => dog <= squirrel <= ``` ### Example 2 - Compare each line of content and exclude the differences This example uses the **ExcludeDifferent** parameter to compare each line of content in two text files. As of PowerShell 7.1, when using the **ExcludeDifferent** parameter, **IncludeEqual** is inferred and the output only contains lines contained in both files, as shown by the **SideIndicator** (`==`). ```powershell $objects = @{ ReferenceObject = (Get-Content -Path C:\Test\Testfile1.txt) DifferenceObject = (Get-Content -Path C:\Test\Testfile2.txt) } Compare-Object @objects -ExcludeDifferent ``` ```Output InputObject SideIndicator ----------- ------------- bird == ``` ### Example 3 - Show the difference when using the PassThru parameter <a id="ex3" ></a> Normally, `Compare-Object` returns a **PSCustomObject** type with the following properties: - The **InputObject** being compared - The **SideIndicator** property showing which input object the output belongs to When you use the **PassThru** parameter, the **Type** of the object is not changed but the instance of the object returned has an added **NoteProperty** named **SideIndicator**. **SideIndicator** shows which input object the output belongs to. The following examples shows the different output types. ```powershell $a = $true Compare-Object -IncludeEqual $a $a (Compare-Object -IncludeEqual $a $a) | Get-Member ``` ```Output InputObject SideIndicator ----------- ------------- True == 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() InputObject NoteProperty System.Boolean InputObject=True SideIndicator NoteProperty string SideIndicator=== ``` ```powershell Compare-Object -IncludeEqual $a $a -PassThru (Compare-Object -IncludeEqual $a $a -PassThru) | Get-Member ``` ```Output True TypeName: System.Boolean Name MemberType Definition ---- ---------- ---------- CompareTo Method int CompareTo(System.Object obj), int CompareTo(bool value), int IComparable.CompareTo(Syst Equals Method bool Equals(System.Object obj), bool Equals(bool obj), bool IEquatable[bool].Equals(bool ot GetHashCode Method int GetHashCode() GetType Method type GetType() GetTypeCode Method System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode() ToBoolean Method bool IConvertible.ToBoolean(System.IFormatProvider provider) ToByte Method byte IConvertible.ToByte(System.IFormatProvider provider) ToChar Method char IConvertible.ToChar(System.IFormatProvider provider) ToDateTime Method datetime IConvertible.ToDateTime(System.IFormatProvider provider) ToDecimal Method decimal IConvertible.ToDecimal(System.IFormatProvider provider) ToDouble Method double IConvertible.ToDouble(System.IFormatProvider provider) ToInt16 Method short IConvertible.ToInt16(System.IFormatProvider provider) ToInt32 Method int IConvertible.ToInt32(System.IFormatProvider provider) ToInt64 Method long IConvertible.ToInt64(System.IFormatProvider provider) ToSByte Method sbyte IConvertible.ToSByte(System.IFormatProvider provider) ToSingle Method float IConvertible.ToSingle(System.IFormatProvider provider) ToString Method string ToString(), string ToString(System.IFormatProvider provider), string IConvertible.To ToType Method System.Object IConvertible.ToType(type conversionType, System.IFormatProvider provider) ToUInt16 Method ushort IConvertible.ToUInt16(System.IFormatProvider provider) ToUInt32 Method uint IConvertible.ToUInt32(System.IFormatProvider provider) ToUInt64 Method ulong IConvertible.ToUInt64(System.IFormatProvider provider) TryFormat Method bool TryFormat(System.Span[char] destination, [ref] int charsWritten) SideIndicator NoteProperty string SideIndicator=== ``` When using **PassThru**, the original object type (**System.Boolean**) is returned. Note how the output displayed by the default format for **System.Boolean** objects didn't display the **SideIndicator** property. However, the returned **System.Boolean** object has the added **NoteProperty**. ### Example 4 - Compare two simple objects using properties In this example, we compare two different string that have the same length. ```powershell Compare-Object -ReferenceObject 'abc' -DifferenceObject 'xyz' -Property Length -IncludeEqual ``` ```Output Length SideIndicator ------ ------------- 3 == ``` ### Example 5 - Comparing complex objects using properties This example shows the behavior when comparing complex objects. In this example we store two different process objects for different instances of PowerShell. Both variables contain process objects with the same name. When the objects are compared without specifying the **Property** parameter, the cmdlet considers the objects to be equal. Notice that the value of the **InputObject** is the same as the result of the **ToString()** method. Since the **System.Diagnostics.Process** class does not have the **IComparable** interface, the cmdlet converts the objects to strings then compares the results. ```powershell PS> Get-Process pwsh NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 101 123.32 139.10 35.81 11168 1 pwsh 89 107.55 66.97 11.44 17600 1 pwsh PS> $a = Get-Process -Id 11168 PS> $b = Get-Process -Id 17600 PS> $a.ToString() System.Diagnostics.Process (pwsh) PS> $b.ToString() System.Diagnostics.Process (pwsh) PS> Compare-Object $a $b -IncludeEqual InputObject SideIndicator ----------- ------------- System.Diagnostics.Process (pwsh) == PS> Compare-Object $a $b -Property ProcessName, Id, CPU ProcessName Id CPU SideIndicator ----------- -- --- ------------- pwsh 17600 11.4375 => pwsh 11168 36.203125 <= ``` When you specify properties to be compared, the cmdlet shows the differences. ### Example 6 - Comparing complex objects that implement IComparable If the object implements **IComparable**, the cmdlet searches for ways to compare the objects.If the objects are different types, the **Difference** object is converted to the type of the **ReferenceObject** then compared. In this example, we are comparing a string to a **TimeSpan** object. In the first case, the string is converted to a **TimeSpan** so the objects are equal. ```powershell Compare-Object ([timespan]"0:0:1") "0:0:1" -IncludeEqual ``` ```Output InputObject SideIndicator ----------- ------------- 00:00:01 == ``` ```powershell Compare-Object "0:0:1" ([timespan]"0:0:1") ``` ```Output InputObject SideIndicator ----------- ------------- 00:00:01 => 0:0:1 <= ``` In the second case, the **TimeSpan** is converted to a string so the object are different. ## PARAMETERS ### -CaseSensitive Indicates that comparisons should be case-sensitive. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Culture Specifies the culture to use for comparisons. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DifferenceObject Specifies the objects that are compared to the **reference** objects. ```yaml Type: System.Management.Automation.PSObject[] Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -ExcludeDifferent Indicates that this cmdlet displays only the characteristics of compared objects that are equal. The differences between the objects are discarded. Use **ExcludeDifferent** with **IncludeEqual** to display only the lines that match between the **reference** and **difference** objects. If **ExcludeDifferent** is specified without **IncludeEqual**, there's no output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -IncludeEqual **IncludeEqual** displays the matches between the **reference** and **difference** objects. By default, the output also includes the differences between the **reference** and **difference** objects. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru When you use the **PassThru** parameter, `Compare-Object` omits the **PSCustomObject** wrapper around the compared objects and returns the differing objects, unchanged. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Property Specifies an array of properties of the **reference** and **difference** objects to compare. The value of the **Property** parameter can be a new calculated property. The calculated property can be a script block or a hash table. Valid key-value pairs are: - Expression - `<string>` or `<script block>` For more information, see [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ReferenceObject Specifies an array of objects used as a reference for comparison. ```yaml Type: System.Management.Automation.PSObject[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SyncWindow Specifies the number of adjacent objects that `Compare-Object` inspects while looking for a match in a collection of objects. `Compare-Object` examines adjacent objects when it doesn't find the object in the same position in a collection. The default value is `[int32]::MaxValue`, which means that `Compare-Object` examines the entire object collection. When working with large collections, the default value might not be efficient but is accurate. Specifying a smaller value for **SyncWindow** can increase performance but could have lower accuracy. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: [int32]::MaxValue Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can send an object down the pipeline to the **DifferenceObject** parameter. ## OUTPUTS ### None By default, this cmdlet returns no output when the **ReferenceObject** and the **DifferenceObject** are the same. ### System.Management.Automation.PSCustomObject When the objects are different, this cmdlet wraps the differing objects in a **PSCustomObject** wrapper with a **SideIndicator** property to reference the differences. When you use the **IncludeEqual** parameter and the objects are the same, the cmdlet returns the objects wrapped in a **PSCustomObject** with the **SideIndicator** property set to `==`. When you use the **PassThru** parameter, the **Type** of the object is not changed but the instance of the object returned has an added **NoteProperty** named **SideIndicator**. **SideIndicator** shows which input object the output belongs to. ## NOTES PowerShell includes the following aliases for `Compare-Object`: - Windows: - `compare` - `diff` When using the **PassThru** parameter, the output displayed in the console may not include the **SideIndicator** property. The default format view for the object type output by `Compare-Object` does not include the **SideIndicator** property. For more information see [Example 3](#ex3) in this article. ## RELATED LINKS [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md) [ForEach-Object](../Microsoft.PowerShell.Core/ForEach-Object.md) [Group-Object](Group-Object.md) [Measure-Object](Measure-Object.md) [New-Object](New-Object.md) [Select-Object](Select-Object.md) [Sort-Object](Sort-Object.md) [Tee-Object](Tee-Object.md) [Where-Object](../Microsoft.PowerShell.Core/Where-Object.md) [Get-Process](../Microsoft.PowerShell.Management/Get-Process.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/ConvertFrom-CliXml.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 08/19/2024 online version: https://go.microsoft.com/fwlink/?LinkID=2280770 schema: 2.0.0 title: ConvertFrom-CliXml --- # ConvertFrom-CliXml ## SYNOPSIS Converts a CliXml-formatted string to a custom **PSObject**. ## SYNTAX ``` ConvertFrom-CliXml [-InputObject] <String> [<CommonParameters>] ``` ## DESCRIPTION The `ConvertFrom-CliXml` cmdlet converts strings that are formatted as Common Language Infrastructure (CLI) XML to a custom **PSObject**. This command is similar to `Import-Clixml`, but it doesn't read from a file. Instead, it takes a string as input. The newly deserialized objects aren't live objects. They're a snapshot of the objects at the time of serialization. The deserialized objects include properties but no methods. The **pstypenames** property contains the original type name prefixed with `Deserialized`. This cmdlet was introduced in PowerShell 7.5-preview.4. ## EXAMPLES ### Example 1 - Convert a process object to CliXml and back This example shows the result of converting a process object to CliXml and back. First, the current process is stored in the variable `$process`. The **pstypenames** property of the process object shows that the object is of type **System.Diagnostics.Process**. The next command displays the count for each type of member in the process object. ```powershell $process = Get-Process -Id $PID $process.pstypenames ``` ```Output System.Diagnostics.Process System.ComponentModel.Component System.MarshalByRefObject System.Object ``` ```powershell $process | Get-Member | Group-Object MemberType | Select-Object Name, Count ``` ```Output Name Count ---- ----- AliasProperty 7 CodeProperty 1 Property 52 NoteProperty 1 ScriptProperty 8 PropertySet 2 Method 19 Event 4 ``` ```powershell $xml = $process | ConvertTo-CliXml $fromXML = ConvertFrom-CliXml $xml $fromXML.pstypenames ``` ```Output Deserialized.System.Diagnostics.Process Deserialized.System.ComponentModel.Component Deserialized.System.MarshalByRefObject Deserialized.System.Object ``` ```powershell $fromXML | Get-Member | Group-Object MemberType | Select-Object Name, Count ``` ```Output Name Count ---- ----- Property 46 NoteProperty 17 PropertySet 2 Method 2 ``` Next, the process object is converted to CliXml and back. The type of the new object is prefixed with `Deserialized`. The count of members in the new object is different from the original object. ## PARAMETERS ### -InputObject The object containing a CliXml-formatted string to be converted. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String ## OUTPUTS ### System.Object ## NOTES ## RELATED LINKS [ConvertTo-CliXml](ConvertTo-CliXml.md) [ConvertTo-Xml](ConvertTo-Xml.md) [Export-Clixml](Export-Clixml.md) [Import-Clixml](Import-Clixml.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/ConvertFrom-Csv.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 11/29/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertfrom-csv?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: ConvertFrom-Csv --- # ConvertFrom-Csv ## SYNOPSIS Converts object properties in character-separated value (CSV) format into CSV versions of the original objects. ## SYNTAX ### Delimiter (Default) ``` ConvertFrom-Csv [[-Delimiter] <Char>] [-InputObject] <PSObject[]> [-Header <String[]>] [<CommonParameters>] ``` ### UseCulture ``` ConvertFrom-Csv -UseCulture [-InputObject] <PSObject[]> [-Header <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `ConvertFrom-Csv` cmdlet converts character-separated value (CSV) data to **PSObject** type objects for each line of CSV data. The new objects are written to the pipeline in the order they are read from the CSV data. The values in column header row of the CSV become the names of the properties added to each new **PSObject**. The objects that `ConvertFrom-Csv` creates are **PSObject** type object for each row in the CSV file. The property values of the CSV objects are string versions of the property values of the original objects. The CSV versions of the objects don't have any methods. You can also use the `Export-Csv` and `Import-Csv` cmdlets to convert objects to CSV strings in a file and back. These cmdlets are the same as the `ConvertTo-Csv` and `ConvertFrom-Csv` cmdlets, except that they save the CSV strings in a file. The **PSObject** type maintains the order of the properties in column header order. This means that you get the same column order when you convert the objects back into CSV format. ## EXAMPLES ### Example 1: Convert processes on the local computer to CSV format This example shows how to convert the processes on the local computer into CSV format and then restore them to object form. ```powershell $P = Get-Process | ConvertTo-Csv $P | ConvertFrom-Csv ``` The `Get-Process` cmdlet sends the processes down the pipeline to `ConvertTo-Csv`. The `ConvertTo-Csv` cmdlet converts the process objects to a series of CSV strings. The `ConvertFrom-Csv` cmdlet converts the CSV strings into CSV versions of the original process objects. The CSV strings are saved in the `$P` variable. ### Example 2: Convert a data object to CSV format and then to CSV object format This example shows how to convert a data object to CSV format and then to CSV object format. ```powershell $Date = Get-Date | ConvertTo-Csv -Delimiter ';' ConvertFrom-Csv -InputObject $Date -Delimiter ';' ``` The first command uses `Get-Date` to send the current date and time down the pipeline to `ConvertTo-Csv`. The `ConvertTo-Csv` cmdlet converts the date object to a series of CSV strings. The **Delimiter** parameter is used to specify a semicolon delimiter. The strings are saved in the `$Date` variable. ### Example 3: Use the header parameter to change the names of properties This example shows how to use the **Header** parameter of `ConvertFrom-Csv` to change the names of properties in the resulting imported object. ```powershell $J = Start-Job -ScriptBlock { Get-Process } | ConvertTo-Csv -NoTypeInformation $Header = 'State', 'MoreData', 'StatusMessage', 'Location', 'Command', 'StateInfo', 'Finished', 'InstanceId', 'Id', 'Name', 'ChildJobs', 'BeginTime', 'EndTime', 'JobType', 'Output', 'Error', 'Progress', 'Verbose', 'Debug', 'Warning', 'Information' # Delete the default header from $J $J = $J[1..($J.Count - 1)] $J | ConvertFrom-Csv -Header $Header ``` ```Output State : Running MoreData : True StatusMessage : Location : localhost Command : Get-Process StateInfo : Running Finished : System.Threading.ManualResetEvent InstanceId : a259eb63-6824-4b97-a033-305108ae1c2e Id : 1 Name : Job1 ChildJobs : System.Collections.Generic.List`1[System.Management.Automation.Job] BeginTime : 12/20/2018 18:59:57 EndTime : JobType : BackgroundJob Output : System.Management.Automation.PSDataCollection`1[System.Management.Automation.PSObject] Error : System.Management.Automation.PSDataCollection`1[System.Management.Automation.ErrorRecord] Progress : System.Management.Automation.PSDataCollection`1[System.Management.Automation.ProgressRecord] Verbose : System.Management.Automation.PSDataCollection`1[System.Management.Automation.VerboseRecord] Debug : System.Management.Automation.PSDataCollection`1[System.Management.Automation.DebugRecord] Warning : System.Management.Automation.PSDataCollection`1[System.Management.Automation.WarningRecord] Information : System.Management.Automation.PSDataCollection`1[System.Management.Automation.InformationRecord] ``` The `Start-Job` cmdlet starts a background job that runs `Get-Process`. A job object is sent down the pipeline to `ConvertTo-Csv` and converted to a CSV string. The **NoTypeInformation** parameter removes the type information header from CSV output and is optional in PowerShell v6 and higher. The `$Header` variable contains a custom header that replaces the following default values: **HasMoreData**, **JobStateInfo**, **PSBeginTime**, **PSEndTime**, and **PSJobTypeName**. The `$J` variable contains the CSV string and is used to remove the default header. The `ConvertFrom-Csv` cmdlet converts the CSV string into a **PSCustomObject** and uses the **Header** parameter to apply the `$Header` variable. ### Example 4: Convert CSV strings of service objects This example shows how to use the `ConvertFrom-Csv` cmdlet with the **UseCulture** parameter. ```powershell (Get-Culture).TextInfo.ListSeparator $Services = (Get-Service | ConvertTo-Csv) ConvertFrom-Csv -InputObject $Services -UseCulture ``` The `Get-Culture` cmdlet uses the nested properties **TextInfo** and **ListSeparator** to get the current culture's default list separator. The `Get-Service` cmdlet sends service objects down the pipeline to `ConvertTo-Csv`. The `ConvertTo-Csv` converts the service objects to a series of CSV strings. The CSV strings are stored in the `$Services` variable. The `ConvertFrom-Csv` cmdlet uses the **InputObject** parameter and converts the CSV strings from the `$Services` variable. The **UseCulture** parameter uses the current culture's default list separator. When the **UseCulture** parameter is used, be sure that the current culture's default list separator matches the delimiter used in the CSV strings. Otherwise, `ConvertFrom-Csv` can't generate objects from the CSV strings. ## PARAMETERS ### -Delimiter Specifies the delimiter that separates the property values in the CSV strings. The default is a comma (`,`). Enter a character, such as a colon (`:`). To specify a semicolon (`;`) enclose it in single quotation marks. If you specify a character other than the actual string delimiter in the file, `ConvertFrom-Csv` can't create the objects from the CSV strings and returns the CSV strings. ```yaml Type: System.Char Parameter Sets: Delimiter Aliases: Required: False Position: 1 Default value: comma (,) Accept pipeline input: False Accept wildcard characters: False ``` ### -Header Specifies an alternate column header row for the imported string. The column header determines the property names of the objects created by `ConvertFrom-Csv`. Enter column headers as a character-separated list. don't enclose the header string in quotation marks. Enclose each column header in single quotation marks. If you enter fewer column headers than there are data columns, the remaining data columns are discarded. If you enter more column headers than there are data columns, the additional column headers are created with empty data columns. When using the **Header** parameter, omit the column header string from the CSV strings. Otherwise, this cmdlet creates an extra object from the items in the header row. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the CSV strings to be converted to objects. Enter a variable that contains the CSV strings or type a command or expression that gets the CSV strings. You can also pipe the CSV strings to `ConvertFrom-Csv`. ```yaml Type: System.Management.Automation.PSObject[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -UseCulture Uses the list separator for the current culture as the item delimiter. To find the list separator for a culture, use the following command: `(Get-Culture).TextInfo.ListSeparator`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: UseCulture Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe CSV strings to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSObject This cmdlet returns the objects described by the properties in the CSV strings. ## NOTES In CSV format, each object is represented by a character-separated list of the property values of the object. The property values are converted to strings, using the `ToString()` method of the object. There is no way to export the methods of the object. ## RELATED LINKS [ConvertTo-Csv](ConvertTo-Csv.md) [Export-Csv](Export-Csv.md) [Import-Csv](Import-Csv.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/ConvertFrom-Json.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/30/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertfrom-json?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: ConvertFrom-Json --- # ConvertFrom-Json ## SYNOPSIS Converts a JSON-formatted string to a custom object or a hash table. ## SYNTAX ``` ConvertFrom-Json [-InputObject] <String> [-AsHashtable] [-DateKind <JsonDateKind>] [-Depth <Int32>] [-NoEnumerate] [<CommonParameters>] ``` ## DESCRIPTION The `ConvertFrom-Json` cmdlet converts a JavaScript Object Notation (JSON) formatted string to a custom **PSObject** or **Hashtable** object that has a property for each field in the JSON string. JSON is commonly used by web sites to provide a textual representation of objects. The cmdlet adds the properties to the new object as it processes each line of the JSON string. The JSON standard allows duplicate key names, which are prohibited in **PSObject** and **Hashtable** types. For example, if the JSON string contains duplicate keys, only the last key is used by this cmdlet. See other examples below. To generate a JSON string from any object, use the `ConvertTo-Json` cmdlet. This cmdlet was introduced in PowerShell 3.0. > [!NOTE] > In Windows PowerShell 5.1, `ConvertFrom-Json` returned an error when it encountered a JSON > comment. In PowerShell 6 and higher, the cmdlet supports JSON with comments. JSON comments aren't > captured in the objects output by the cmdlet. For more information, see the _JSON comments_ > section of the > [about_Comments](/powershell/module/microsoft.powershell.core/about/about_comments) article. ## EXAMPLES ### Example 1: Convert a DateTime object to a JSON object This command uses the `ConvertTo-Json` and `ConvertFrom-Json` cmdlets to convert a **DateTime** object from the `Get-Date` cmdlet to a JSON object then to a **PSCustomObject**. ```powershell Get-Date | Select-Object -Property * | ConvertTo-Json | ConvertFrom-Json ``` ```Output DisplayHint : 2 DateTime : Monday, January 29, 2024 3:10:26 PM Date : 1/29/2024 12:00:00 AM Day : 29 DayOfWeek : 1 DayOfYear : 29 Hour : 15 Kind : 2 Millisecond : 931 Microsecond : 47 Nanosecond : 600 Minute : 10 Month : 1 Second : 26 Ticks : 638421378269310476 TimeOfDay : @{Ticks=546269310476; Days=0; Hours=15; Milliseconds=931; Microseconds=47; Nanoseconds=600; Minutes=10; Seconds=26; TotalDays=0.632256146384259; TotalHours=15.1741475132222; TotalMilliseconds=54626931.0476; TotalMicroseconds=54626931047.6; TotalNanoseconds=54626931047600; TotalMinutes=910.448850793333; TotalSeconds=54626.9310476} Year : 2024 ``` The example uses the `Select-Object` cmdlet to get all of the properties of the **DateTime** object. It uses the `ConvertTo-Json` cmdlet to convert the **DateTime** object to a string formatted as a JSON object and the `ConvertFrom-Json` cmdlet to convert the JSON-formatted string to a **PSCustomObject** object. ### Example 2: Get JSON strings from a web service and convert them to PowerShell objects This command uses the `Invoke-WebRequest` cmdlet to get JSON strings from a web service and then it uses the `ConvertFrom-Json` cmdlet to convert JSON content to objects that can be managed in PowerShell. ```powershell # Ensures that Invoke-WebRequest uses TLS 1.2 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 $j = Invoke-WebRequest 'https://api.github.com/repos/PowerShell/PowerShell/issues' | ConvertFrom-Json ``` You can also use the `Invoke-RestMethod` cmdlet, which automatically converts JSON content to objects. ### Example 3: Convert a JSON string to a custom object This example shows how to use the `ConvertFrom-Json` cmdlet to convert a JSON file to a PowerShell custom object. ```powershell Get-Content -Raw JsonFile.json | ConvertFrom-Json ``` The command uses Get-Content cmdlet to get the strings in a JSON file. The **Raw** parameter returns the whole file as a single JSON object. Then it uses the pipeline operator to send the delimited string to the `ConvertFrom-Json` cmdlet, which converts it to a custom object. ### Example 4: Convert a JSON string to a hash table This command shows an example where the `-AsHashtable` switch can overcome limitations of the command. ```powershell '{ "key":"value1", "Key":"value2" }' | ConvertFrom-Json -AsHashtable ``` The JSON string contains two key value pairs with keys that differ only in casing. Without the switch, the command would have thrown an error. ### Example 5: Round-trip a single element array This command shows an example where the `-NoEnumerate` switch is used to round-trip a single element JSON array. ```powershell Write-Output "With -NoEnumerate: $('[1]' | ConvertFrom-Json -NoEnumerate | ConvertTo-Json -Compress)" Write-Output "Without -NoEnumerate: $('[1]' | ConvertFrom-Json | ConvertTo-Json -Compress)" ``` ```Output With -NoEnumerate: [1] Without -NoEnumerate: 1 ``` The JSON string contains an array with a single element. Without the switch, converting the JSON to a PSObject and then converting it back with the `ConvertTo-Json` command results in a single integer. ## PARAMETERS ### -AsHashtable Converts the JSON to a hash table object. This switch was introduced in PowerShell 6.0. Starting with PowerShell 7.3, the object is an **OrderedHashtable** and preserves the ordering of the keys from the JSON. In prior versions, the object is a **Hashtable**. There are several scenarios where it can overcome some limitations of the `ConvertFrom-Json` cmdlet. - Without this switch, when two or more keys in a JSON object are case-insensitively identical, they are treated as identical keys. In that case, only the last of those case-insensitively identical keys is included in the converted object. - Without this switch, the cmdlet throws an error whenever the JSON contains a key that's an empty string. **PSCustomObject** can't have property names that are empty strings. For example, this can occur in `project.lock.json` files. - Hash tables can be processed faster for certain data structures. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -DateKind Specifies the method used when parsing date time values in the JSON string. The acceptable values for this parameter are: - `Default` - `Local` - `Utc` - `Offset` - `String` For information about how these values affect conversion, see the details in the [NOTES](#notes). This parameter was introduced in PowerShell 7.5. ```yaml Type: Microsoft.PowerShell.Commands.JsonDateKind Parameter Sets: (All) Aliases: Accepted values: Default, Local, Utc, Offset, String Required: False Position: Named Default value: Default Accept pipeline input: False Accept wildcard characters: False ``` ### -Depth Gets or sets the maximum depth the JSON input is allowed to have. The default is 1024. This parameter was introduced in PowerShell 6.2. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the JSON strings to convert to JSON objects. Enter a variable that contains the string, or type a command or expression that gets the string. You can also pipe a string to `ConvertFrom-Json`. The **InputObject** parameter is required, but its value can be an empty string. When the input object is an empty string, `ConvertFrom-Json` doesn't generate any output. The **InputObject** value can't be `$null`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -NoEnumerate Specifies that output isn't enumerated. Setting this parameter causes arrays to be sent as a single object instead of sending every element separately. This guarantees that JSON can be round-tripped via `ConvertTo-Json`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a JSON string to `ConvertFrom-Json`. ## OUTPUTS ### PSCustomObject ### System.Management.Automation.OrderedHashtable ## NOTES This cmdlet is implemented using [Newtonsoft Json.NET](https://www.newtonsoft.com/json). Beginning in PowerShell 6, `ConvertTo-Json` attempts to convert strings formatted as timestamps to **DateTime** values. PowerShell 7.5 added the **DateKind** parameter, which allows you to control how timestamp string are converted. The parameter accepts the following values: - `Default` - Converts the timestamp to a `[datetime]` instance according to the following rules: - If there is no time zone information in the input string, the Json.NET serializer converts the value as an unspecified time value. - If the time zone information is a trailing `Z`, the Json.NET serializer converts the timestamp to a _UTC_ value. - If the timestamp includes a UTC offset like `+02:00`, the offset is converted to the caller's configured time zone. The default output formatting doesn't indicate the original time zone offset. - `Local` - Converts the timestamp to a `[datetime]` instance in the _local_ time. If the timestamp includes a UTC offset, the offset is converted to the caller's configured time zone. The default output formatting doesn't indicate the original time zone offset. - `Utc` - Converts the value to a `[datetime]` instance in UTC time. - `Offset` - Converts the timestamp to a `[DateTimeOffset]` instance with the timezone offset of the original string preserved in that instance. If the raw string did not contain a timezone offset, the **DateTimeOffset** value will be specified in the local timezone. - `String` - Preserves the value the `[string]` instance. This ensures that any custom parsing logic can be applied to the raw string value. The **PSObject** type maintains the order of the properties as presented in the JSON string. Beginning with PowerShell 7.3, The **AsHashtable** parameter creates an **OrderedHashtable**. The key-value pairs are added in the order presented in the JSON string. The **OrderedHashtable** preserves that order. ## RELATED LINKS [An Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET](/previous-versions/dotnet/articles/bb299886(v=msdn.10)) [ConvertTo-Json](ConvertTo-Json.md) [Invoke-WebRequest](Invoke-WebRequest.md) [Invoke-RestMethod](Invoke-RestMethod.md) [datetime](xref:System.DateTime) [DateTimeOffset](xref:System.DateTimeOffset)

#File: reference/7.6/Microsoft.PowerShell.Utility/ConvertFrom-Markdown.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 11/02/2018 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertfrom-markdown?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: ConvertFrom-Markdown --- # ConvertFrom-Markdown ## SYNOPSIS Convert the contents of a string or a file to a **MarkdownInfo** object. ## SYNTAX ### PathParamSet (Default) ``` ConvertFrom-Markdown [-Path] <String[]> [-AsVT100EncodedString] [<CommonParameters>] ``` ### LiteralParamSet ``` ConvertFrom-Markdown -LiteralPath <String[]> [-AsVT100EncodedString] [<CommonParameters>] ``` ### InputObjParamSet ``` ConvertFrom-Markdown -InputObject <PSObject> [-AsVT100EncodedString] [<CommonParameters>] ``` ## DESCRIPTION This cmdlet converts the specified content into a **MarkdownInfo**. When a file path is specified for the **Path** parameter, the contents on the file are converted. The output object has three properties: - The **Token** property has the abstract syntax tree (AST) of the converted object - The **Html** property has the HTML conversion of the specified input - The **VT100EncodedString** property has the converted string with ANSI (VT100) escape sequences if the **AsVT100EncodedString** parameter was specified This cmdlet was introduced in PowerShell 6.1. ## EXAMPLES ### Example 1: Convert a file containing Markdown content to HTML ```powershell ConvertFrom-Markdown -Path .\README.md ``` The **MarkdownInfo** object is returned. The **Tokens** property has the AST of the converted content of the `README.md` file. The **Html** property has the HTML converted content of the `README.md` file. ### Example 2: Convert a file containing Markdown content to a VT100-encoded string ```powershell ConvertFrom-Markdown -Path .\README.md -AsVT100EncodedString ``` The **MarkdownInfo** object is returned. The **Tokens** property has the AST of the converted content of the `README.md` file. The **VT100EncodedString** property has the VT100-encoded string converted content of the `README.md` file. ### Example 3: Convert input object containing Markdown content to a VT100-encoded string ```powershell Get-Item .\README.md | ConvertFrom-Markdown -AsVT100EncodedString ``` The **MarkdownInfo** object is returned. The **FileInfo** object from `Get-Item` is converted to a VT100-encoded string. The **Tokens** property has the AST of the converted content of the `README.md` file. The **VT100EncodedString** property has the VT100-encoded string converted content of the `README.md` file. ### Example 4: Convert a string containing Markdown content to a VT100-encoded string ```powershell "**Bold text**" | ConvertFrom-Markdown -AsVT100EncodedString ``` The **MarkdownInfo** object is returned. The specified string `**Bold text**` is converted to a VT100-encoded string and available in **VT100EncodedString** property. ## PARAMETERS ### -AsVT100EncodedString Specifies if the output should be encoded as a string with VT100 escape codes. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the object to be converted. When an object of type **System.String** is specified, the string is converted. When an object of type **System.IO.FileInfo** is specified, the contents of the file specified by the object are converted. Objects of any other type result in an error. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: InputObjParamSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -LiteralPath Specifies a path to the file to be converted. ```yaml Type: System.String[] Parameter Sets: LiteralParamSet Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies a path to the file to be converted. ```yaml Type: System.String[] Parameter Sets: PathParamSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject ## OUTPUTS ### Microsoft.PowerShell.MarkdownRender.MarkdownInfo ## NOTES ## RELATED LINKS [Markdown Parser](https://github.com/lunet-io/markdig) [ANSI escape code](https://wikipedia.org/wiki/ANSI_escape_code)

#File: reference/7.6/Microsoft.PowerShell.Utility/ConvertFrom-SddlString.md

--- external help file: Microsoft.PowerShell.Utility-help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertfrom-sddlstring?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: ConvertFrom-SddlString --- # ConvertFrom-SddlString ## SYNOPSIS Converts a SDDL string to a custom object. ## SYNTAX ### All ``` ConvertFrom-SddlString [-Sddl] <String> [-Type <AccessRightTypeNames>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `ConvertFrom-SddlString` cmdlet converts a Security Descriptor Definition Language string to a custom **PSCustomObject** object with the following properties: Owner, Group, DiscretionaryAcl, SystemAcl and RawDescriptor. Owner, Group, DiscretionaryAcl and SystemAcl properties contain a readable text representation of the access rights specified in a SDDL string. This cmdlet was introduced in PowerShell 5.0. ## EXAMPLES ### Example 1: Convert file system access rights SDDL to a PSCustomObject ```powershell $acl = Get-Acl -Path C:\Windows ConvertFrom-SddlString -Sddl $acl.Sddl ``` The first command uses the `Get-Acl` cmdlet to get the security descriptor for the C:\Windows folder and saves it in the variable. The second command uses the `ConvertFrom-SddlString` cmdlet to get the text representation of the SDDL string, contained in the Sddl property of the object representing the security descriptor. ### Example 2: Convert registry access rights SDDL to a PSCustomObject ```powershell $acl = Get-Acl HKLM:\SOFTWARE\Microsoft\ ConvertFrom-SddlString -Sddl $acl.Sddl -Type RegistryRights ``` The first command uses the `Get-Acl` cmdlet to get the security descriptor for the HKLM:\SOFTWARE\Microsoft\ key and saves it in the variable. The second command uses the `ConvertFrom-SddlString` cmdlet to get the text representation of the SDDL string, contained in the Sddl property of the object representing the security descriptor. It uses the `-Type` parameter to specify that SDDL string represents a registry security descriptor. ### Example 3: Convert registry access rights SDDL to a PSCustomObject by using ConvertFrom-SddlString with and without the `-Type` parameter ```powershell $acl = Get-Acl -Path HKLM:\SOFTWARE\Microsoft\ ConvertFrom-SddlString -Sddl $acl.Sddl | ForEach-Object {$_.DiscretionaryAcl[0]} BUILTIN\Administrators: AccessAllowed (ChangePermissions, CreateDirectories, Delete, ExecuteKey, FullControl, GenericExecute, GenericWrite, ListDirectory, ReadExtendedAttributes, ReadPermissions, TakeOwnership, Traverse, WriteData, WriteExtendedAttributes, WriteKey) ConvertFrom-SddlString -Sddl $acl.Sddl -Type RegistryRights | ForEach-Object {$_.DiscretionaryAcl[0]} BUILTIN\Administrators: AccessAllowed (ChangePermissions, CreateLink, CreateSubKey, Delete, EnumerateSubKeys, ExecuteKey, FullControl, GenericExecute, GenericWrite, Notify, QueryValues, ReadPermissions, SetValue, TakeOwnership, WriteKey) ``` The first command uses the `Get-Acl` cmdlet to get the security descriptor for the HKLM:\SOFTWARE\Microsoft\ key and saves it in the variable. The second command uses the `ConvertFrom-SddlString` cmdlet to get the text representation of the SDDL string, contained in the Sddl property of the object representing the security descriptor. It doesn't use the `-Type` parameter, so the access rights shown are for file system. The third command uses the `ConvertFrom-SddlString` cmdlet with the `-Type` parameter, so the access rights returned are for registry. ## PARAMETERS ### -Sddl Specifies the string representing the security descriptor in SDDL syntax. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Type Specifies the type of rights that SDDL string represents. The acceptable values for this parameter are: - FileSystemRights - RegistryRights - ActiveDirectoryRights - MutexRights - SemaphoreRights - CryptoKeyRights - EventWaitHandleRights By default cmdlet uses file system rights. **CryptoKeyRights** and **ActiveDirectoryRights** are not supported in PowerShell v6 and higher. ```yaml Type: Microsoft.PowerShell.Commands.ConvertFromSddlStringCommand+AccessRightTypeNames Parameter Sets: (All) Aliases: Accepted values: FileSystemRights, RegistryRights, ActiveDirectoryRights, MutexRights, SemaphoreRights, CryptoKeyRights, EventWaitHandleRights Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a SDDL string to this cmdlet. ## OUTPUTS ## NOTES This cmdlet is only available on Windows platforms. ## RELATED LINKS [Security Descriptor Definition Language](/windows/win32/secauthz/security-descriptor-definition-language)

#File: reference/7.6/Microsoft.PowerShell.Utility/ConvertFrom-StringData.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/09/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertfrom-stringdata?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: ConvertFrom-StringData --- # ConvertFrom-StringData ## SYNOPSIS Converts a string containing one or more key and value pairs to a hash table. ## SYNTAX ``` ConvertFrom-StringData [-StringData] <String> [[-Delimiter] <Char>] [<CommonParameters>] ``` ## DESCRIPTION The `ConvertFrom-StringData` cmdlet converts a string that contains one or more key and value pairs into a hash table. Because each key-value pair must be on a separate line, here-strings are often used as the input format. By default, the **key** must be separated from the **value** by an equals sign (`=`) character. The `ConvertFrom-StringData` cmdlet is considered to be a safe cmdlet that can be used in the `data` section of a script or function. When used in a `data` section, the contents of the string must conform to the rules for a `data` section. For more information, see [about_Data_Sections](../Microsoft.PowerShell.Core/About/about_Data_Sections.md). `ConvertFrom-StringData` supports escape character sequences that are allowed by conventional machine translation tools. That is, the cmdlet can interpret backslashes (`\`) as escape characters in the string data by using the [Regex.Unescape Method](/dotnet/api/system.text.regularexpressions.regex.unescape), instead of the PowerShell backtick character (`` ` ``) that would normally signal the end of a line in a script. Inside the here-string, the backtick character doesn't work. You can also preserve a literal backslash in your results by escaping it with a preceding backslash, like this: `\\`. Unescaped backslash characters, such as those that are commonly used in file paths, can render as illegal escape sequences in your results. PowerShell 7 adds the **Delimiter** parameter. ## EXAMPLES ### Example 1: Convert a single-quoted here-string to a hash table This example converts a single-quoted here-string of user messages into a hash table. In a single-quoted string, values aren't substituted for variables and expressions aren't evaluated. The `ConvertFrom-StringData` cmdlet converts the value in the `$Here` variable to a hash table. ```powershell $Here = @' Msg1 = The string parameter is required. Msg2 = Credentials are required for this command. Msg3 = The specified variable doesn't exist. '@ ConvertFrom-StringData -StringData $Here ``` ```Output Name Value ---- ----- Msg3 The specified variable doesn't exist. Msg2 Credentials are required for this command. Msg1 The string parameter is required. ``` ### Example 2: Convert string data using a different delimiter This example shows how to convert string data that uses a different character as a delimiter. In this example the string data is using the pipe character (`|`) as the delimiter. ```powershell $StringData = @' color|red model|coupe year|1965 condition|mint '@ $carData = ConvertFrom-StringData -StringData $StringData -Delimiter '|' $carData ``` ```Output Name Value ---- ----- condition mint model coupe color red year 1965 ``` ### Example 3: Convert a here-string containing a comment This example converts a here-string that contains a comment and multiple key-value pairs into a hash table. ```powershell ConvertFrom-StringData -StringData @' Name = Disks.ps1 # Category is optional. Category = Storage Cost = Free '@ ``` ```Output Name Value ---- ----- Cost Free Category Storage Name Disks.ps1 ``` The value of the **StringData** parameter is a here-string, instead of a variable that contains a here-string. Either format is valid. The here-string includes a comment about one of the strings. `ConvertFrom-StringData` ignores single-line comments, but the hash character (`#`) must be the first non-whitespace character on the line. ### Example 4: Convert a string to a hash table This example converts a regular double-quoted string (not a here-string) into a hash table and saves it in the `$A` variable. ```powershell $A = ConvertFrom-StringData -StringData "Top = Red `n Bottom = Blue" $A ``` ```Output Name Value ---- ----- Bottom Blue Top Red ``` To satisfy the condition that each key-value pair must be on a separate line, the string uses the PowerShell newline character (`` `n ``) to separate the pairs. ### Example 5: Use in the `data` section of a script This example shows a `ConvertFrom-StringData` command used in the `data` section of a script. The statements below the `data` section display the text to the user. ```powershell $TextMsgs = data { ConvertFrom-StringData @' Text001 = The $Notebook variable contains the name of the user's system notebook. Text002 = The $MyNotebook variable contains the name of the user's private notebook. '@ } $TextMsgs ``` ```Output Name Value ---- ----- Text001 The $Notebook variable contains the name of the user's system notebook. Text002 The $MyNotebook variable contains the name of the user's private notebook. ``` Because the text includes variable names, it must be enclosed in a single-quoted string so that the variables are interpreted literally and not expanded. Variables aren't permitted in the `data` section. ### Example 6: Use the pipeline operator to pass a string This example shows that you can use a pipeline operator (`|`) to send a string to `ConvertFrom-StringData`. The value of the `$Here` variable is piped to `ConvertFrom-StringData` and the result in the `$Hash` variable. ```powershell $Here = @' Msg1 = The string parameter is required. Msg2 = Credentials are required for this command. Msg3 = The specified variable doesn't exist. '@ $Hash = $Here | ConvertFrom-StringData $Hash ``` ```Output Name Value ---- ----- Msg3 The specified variable doesn't exist. Msg2 Credentials are required for this command. Msg1 The string parameter is required. ``` ### Example 7: Use escape characters to add new lines and return characters This example shows the use of escape characters to create new lines and return characters in source data. The escape sequence `\n` is used to create new lines within a block of text that's associated with a name or item in the resulting hash table. ```powershell ConvertFrom-StringData @" Vincentio = Heaven doth with us as we with torches do,\nNot light them for themselves; for if our virtues\nDid not go forth of us, 'twere all alike\nAs if we had them not. Angelo = Let there be some more test made of my metal,\nBefore so noble and so great a figure\nBe stamp'd upon it. "@ | Format-List ``` ```Output Name : Angelo Value : Let there be some more test made of my metal, Before so noble and so great a figure Be stamp'd upon it. Name : Vincentio Value : Heaven doth with us as we with torches do, Not light them for themselves; for if our virtues Didn't go forth of us, 'twere all alike As if we had them not. ``` ### Example 8: Use backslash escape character to correctly render a file path This example shows how to use of the backslash escape character in the string data to allow a file path to render correctly in the resulting `ConvertFrom-StringData` hash table. The double backslash ensures that the literal backslash characters render correctly in the hash table output. ```powershell ConvertFrom-StringData "Message=Look in C:\\Windows\\System32" ``` ```Output Name Value ---- ----- Message Look in C:\Windows\System32 ``` ## PARAMETERS ### -Delimiter The character used to separate the **key** from the **value** data in the string being converted. The default delimiter is the equals sign (`=`) character. This parameter was added in PowerShell 7. ```yaml Type: System.Char Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: '=' Accept pipeline input: False Accept wildcard characters: False ``` ### -StringData Specifies the string to be converted. You can use this parameter or pipe a string to `ConvertFrom-StringData`. The parameter name is optional. The value of this parameter must be a string that contains one or more key-value pairs. Each key-value pair must be on a separate line, or each pair must be separated by newline characters (`` `n ``). You can include comments in the string, but the comments can't be on the same line as a key-value pair. `ConvertFrom-StringData` ignores single-line comments. The hash character (`#`) must be the first non-whitespace character on the line. All characters on the line after the hash character (`#`) are ignored. The comments aren't included in the hash table. A here-string is a string consisting of one or more lines. Quotation marks within the here-string are interpreted literally as part of the string data. For more information, see [about_Quoting_Rules](../Microsoft.PowerShell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string containing a key-value pair to this cmdlet. ## OUTPUTS ### System.Collections.Hashtable This cmdlet returns a hash table that it creates from the key-value pairs. ## NOTES A here-string is a string consisting of one or more lines within which quotation marks are interpreted literally. This cmdlet can be useful in scripts that display user messages in multiple spoken languages. You can use the dictionary-style hash tables to isolate text strings from code, such as in resource files, and to format the text strings for use in translation tools. ## RELATED LINKS

#File: reference/7.6/Microsoft.PowerShell.Utility/ConvertTo-CliXml.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 08/19/2024 online version: https://go.microsoft.com/fwlink/?LinkID=2280866 schema: 2.0.0 title: ConvertTo-CliXml --- # ConvertTo-CliXml ## SYNOPSIS Converts an object to a CliXml-formatted string. ## SYNTAX ``` ConvertTo-CliXml [-InputObject] <PSObject> [-Depth <Int32>] [<CommonParameters>] ``` ## DESCRIPTION The `ConvertTo-CliXml` cmdlet converts objects to strings that are formatted as Common Language Infrastructure (CLI) XML. This command is similar to `Export-Clixml`, but it doesn't write to a file. Instead, it outputs a string. This cmdlet was introduced in PowerShell 7.5-preview.4. ## EXAMPLES ### Example 1 - Convert a process object to CliXml and back This example shows the result of converting a process object to CliXml and back. First, the current process is stored in the variable `$process`. The **pstypenames** property of the process object shows that the object is of type **System.Diagnostics.Process**. The next command displays the count for each type of member in the process object. ```powershell $process = Get-Process -Id $PID $process.pstypenames ``` ```Output System.Diagnostics.Process System.ComponentModel.Component System.MarshalByRefObject System.Object ``` ```powershell $process | Get-Member | Group-Object MemberType | Select-Object Name, Count ``` ```Output Name Count ---- ----- AliasProperty 7 CodeProperty 1 Property 52 NoteProperty 1 ScriptProperty 8 PropertySet 2 Method 19 Event 4 ``` ```powershell $xml = $process | ConvertTo-CliXml $fromXML = ConvertFrom-CliXml $xml $fromXML.pstypenames ``` ```Output Deserialized.System.Diagnostics.Process Deserialized.System.ComponentModel.Component Deserialized.System.MarshalByRefObject Deserialized.System.Object ``` ```powershell $fromXML | Get-Member | Group-Object MemberType | Select-Object Name, Count ``` ```Output Name Count ---- ----- Property 46 NoteProperty 17 PropertySet 2 Method 2 ``` Next, the process object is converted to CliXml and back. The type of the new object is prefixed with `Deserialized`. The count of members in the new object is different from the original object. ## PARAMETERS ### -Depth Specifies how many levels of contained objects are included in the XML representation. The default values is 2. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 2 Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject The object to be converted to a CliXml-formatted string. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject ## OUTPUTS ### System.String ## NOTES ## RELATED LINKS [ConvertFrom-CliXml](ConvertFrom-CliXml.md) [ConvertTo-Xml](ConvertTo-Xml.md) [Export-Clixml](Export-Clixml.md) [Import-Clixml](Import-Clixml.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/ConvertTo-Csv.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 03/14/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertto-csv?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: ConvertTo-Csv --- # ConvertTo-Csv ## SYNOPSIS Converts .NET objects into a series of character-separated value (CSV) strings. ## SYNTAX ### Delimiter (Default) ``` ConvertTo-Csv [-InputObject] <PSObject> [[-Delimiter] <Char>] [-IncludeTypeInformation] [-NoTypeInformation] [-QuoteFields <String[]>] [-UseQuotes <QuoteKind>] [-NoHeader] [<CommonParameters>] ``` ### UseCulture ``` ConvertTo-Csv [-InputObject] <PSObject> [-UseCulture] [-IncludeTypeInformation] [-NoTypeInformation] [-QuoteFields <String[]>] [-UseQuotes <QuoteKind>] [-NoHeader] [<CommonParameters>] ``` ## DESCRIPTION The `ConvertTo-Csv` cmdlet returns a series of character-separated value (CSV) strings that represent the objects that you submit. You can then use the `ConvertFrom-Csv` cmdlet to recreate objects from the CSV strings. The objects converted from CSV are string values of the original objects that contain property values and no methods. You can use the `Export-Csv` cmdlet to convert objects to CSV strings. `Export-Csv` is similar to `ConvertTo-Csv`, except that it saves the CSV strings to a file. The `ConvertTo-Csv` cmdlet has parameters to specify a delimiter other than a comma or use the current culture as the delimiter. ## EXAMPLES ### Example 1: Convert an object to CSV This example converts a **Process** object to a CSV string. ```powershell Get-Process -Name pwsh | ConvertTo-Csv -NoTypeInformation ``` ```Output "Name","SI","Handles","VM","WS","PM","NPM","Path","Parent","Company","CPU","FileVersion", ... "pwsh","8","950","2204001161216","100925440","59686912","67104", ... ``` The `Get-Process` cmdlet gets the **Process** object and uses the **Name** parameter to specify the PowerShell process. The process object is sent down the pipeline to the `ConvertTo-Csv` cmdlet. The `ConvertTo-Csv` cmdlet converts the object to CSV strings. The **NoTypeInformation** parameter removes the **#TYPE** information header from the CSV output and is not required in PowerShell 6. ### Example 2: Convert a DateTime object to CSV This example converts a **DateTime** object to a CSV string. ```powershell $Date = Get-Date ConvertTo-Csv -InputObject $Date -Delimiter ';' -NoTypeInformation ``` ```Output "DisplayHint";"DateTime";"Date";"Day";"DayOfWeek";"DayOfYear";"Hour";"Kind";"Millisecond";"Minute";"Month";"Second";"Ticks";"TimeOfDay";"Year" "DateTime";"Friday, January 4, 2019 14:40:51";"1/4/2019 00:00:00";"4";"Friday";"4";"14";"Local";"711";"40";"1";"51";"636822096517114991";"14:40:51.7114991";"2019" ``` The `Get-Date` cmdlet gets the **DateTime** object and saves it in the `$Date` variable. The `ConvertTo-Csv` cmdlet converts the **DateTime** object to strings. The **InputObject** parameter uses the **DateTime** object stored in the `$Date` variable. The **Delimiter** parameter specifies a semicolon to separate the string values. The **NoTypeInformation** parameter removes the **#TYPE** information header from the CSV output and is not required in PowerShell 6. ### Example 3: Convert the PowerShell event log to CSV This example converts the Windows event log for PowerShell to a series of CSV strings. ```powershell (Get-Culture).TextInfo.ListSeparator Get-WinEvent -LogName 'PowerShellCore/Operational' | ConvertTo-Csv -UseCulture -NoTypeInformation ``` ```Output , "Message","Id","Version","Qualifiers","Level","Task","Opcode","Keywords","RecordId", ... "Error Message = System error""4100","1",,"3","106","19","0","31716","PowerShellCore", ... ``` The `Get-Culture` cmdlet uses the nested properties **TextInfo** and **ListSeparator** and displays the current culture's default list separator. The `Get-WinEvent` cmdlet gets the event log objects and uses the **LogName** parameter to specify the log file name. The event log objects are sent down the pipeline to the `ConvertTo-Csv` cmdlet. The `ConvertTo-Csv` cmdlet converts the event log objects to a series of CSV strings. The **UseCulture** parameter uses the current culture's default list separator as the delimiter. The **NoTypeInformation** parameter removes the **#TYPE** information header from the CSV output and is not required in PowerShell 6. ### Example 4: Convert to CSV with quotes around two columns This example converts a **DateTime** object to a CSV string. ```powershell Get-Date | ConvertTo-Csv -QuoteFields "DateTime","Date" ``` ```Output DisplayHint,"DateTime","Date",Day,DayOfWeek,DayOfYear,Hour,Kind,Millisecond,Minute,Month,Second,Ticks,TimeOfDay,Year DateTime,"Thursday, August 22, 2019 11:27:34 AM","8/22/2019 12:00:00 AM",22,Thursday,234,11,Local,569,27,8,34,637020700545699784,11:27:34.5699784,2019 ``` ### Example 5: Convert to CSV with quotes only when needed This example converts a **DateTime** object to a CSV string. ```powershell Get-Date | ConvertTo-Csv -UseQuotes AsNeeded ``` ```Output DisplayHint,DateTime,Date,Day,DayOfWeek,DayOfYear,Hour,Kind,Millisecond,Minute,Month,Second,Ticks,TimeOfDay,Year DateTime,"Thursday, August 22, 2019 11:31:00 AM",8/22/2019 12:00:00 AM,22,Thursday,234,11,Local,713,31,8,0,637020702607132640,11:31:00.7132640,2019 ``` ### Example 6: Convert hashtables to CSV In PowerShell 7.2 and above, when you convert hashtables to CSV, the keys of the first hashtable are serialized and used as headers in the output. ```powershell $person1 = @{ Name = 'John Smith' Number = 1 } $person2 = @{ Name = 'Jane Smith' Number = 2 } $allPeople = $person1, $person2 $allPeople | ConvertTo-Csv ``` ```Output "Name","Number" "John Smith","1" "Jane Smith","2" ``` ### Example 7: Converting hashtables to CSV with additional properties In PowerShell 7.2 and above, when you convert a hashtable that has additional properties added with `Add-Member` or `Select-Object` the additional properties are also added as a header in the CSV output. ```powershell $allPeople | Add-Member -Name ExtraProp -Value 42 $allPeople | ConvertTo-Csv ``` ```Output "Name","Number","ExtraProp" "John Smith","1","42" "Jane Smith","2","42" ``` Each hashtable has a property named `ExtraProp` added by `Add-Member` and then converted to CSV. You can see `ExtraProp` is now a header in the output. If an added property has the _same_ name as a key from the hashtable, the key takes precedence and only the key is converted to CSV. ## PARAMETERS ### -Delimiter Specifies the delimiter to separate the property values in CSV strings. The default is a comma (`,`). Enter a character, such as a colon (`:`). To specify a semicolon (`;`) enclose it in single quotation marks. ```yaml Type: System.Char Parameter Sets: Delimiter Aliases: Required: False Position: 1 Default value: comma (,) Accept pipeline input: False Accept wildcard characters: False ``` ### -IncludeTypeInformation When this parameter is used the first line of the output contains `#TYPE` followed by the fully qualified name of the object type. For example, `#TYPE System.Diagnostics.Process`. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: ITI Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects that are converted to CSV strings. Enter a variable that contains the objects or type a command or expression that gets the objects. You can also pipe objects to `ConvertTo-Csv`. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -NoHeader When this parameter is used, the cmdlet doesn't write a header row containing the column names to the output. This parameter was added in PowerShell 7.4. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -NoTypeInformation Removes the `#TYPE` information header from the output. This parameter became the default in PowerShell 6.0 and is included for backwards compatibility. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: NTI Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -QuoteFields Specifies the names of the columns that should be quoted. When this parameter is used only the specified columns are quoted. This parameter was added in PowerShell 7.0. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: QF Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseCulture Uses the list separator for the current culture as the item delimiter. To find the list separator for a culture, use the following command: `(Get-Culture).TextInfo.ListSeparator`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: UseCulture Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -UseQuotes Specifies when quotes are used in the CSV files. Possible values are: - Never - don't quote anything - Always - quote everything (default behavior) - AsNeeded - only quote fields that contain a delimiter character, double-quote, or newline character This parameter was added in PowerShell 7.0. ```yaml Type: Microsoft.PowerShell.Commands.BaseCsvWritingCommand+QuoteKind Parameter Sets: (All) Aliases: UQ Required: False Position: Named Default value: Always Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object that has an Extended Type System (ETS) adapter to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns one or more strings representing each converted object. ## NOTES In CSV format, each object is represented by a character-separated list of its property value. The property values are converted to strings using the object's **ToString()** method. The strings are represented by the property value name. `ConvertTo-Csv` does not export the object's methods. The CSV strings are output as follows: - If **IncludeTypeInformation** is used, the first string consists of **#TYPE** followed by the object type's fully qualified name. For example, **#TYPE System.Diagnostics.Process**. - If **IncludeTypeInformation** is not used the first string includes the column headers. The headers contain the first object's property names as a character-separated list. - The remaining strings contain character-separated lists of each object's property values. Beginning with PowerShell 6.0 the default behavior of `ConvertTo-Csv` is to not include the **#TYPE** information in the CSV and **NoTypeInformation** is implied. **IncludeTypeInformation** can be used to include the **#TYPE** information and emulate the default behavior of `ConvertTo-Csv` prior to PowerShell 6.0. When you submit multiple objects to `ConvertTo-Csv`, `ConvertTo-Csv` orders the strings based on the properties of the first object that you submit. If the remaining objects do not have one of the specified properties, the property value of that object is Null, as represented by two consecutive commas. If the remaining objects have additional properties, those property values are ignored. ## RELATED LINKS [ConvertFrom-Csv](ConvertFrom-Csv.md) [Export-Csv](Export-Csv.md) [Import-Csv](Import-Csv.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/ConvertTo-Html.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertto-html?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: ConvertTo-Html --- # ConvertTo-Html ## SYNOPSIS Converts .NET objects into HTML that can be displayed in a Web browser. ## SYNTAX ### Page (Default) ``` ConvertTo-Html [-InputObject <PSObject>] [[-Property] <Object[]>] [[-Body] <String[]>] [[-Head] <String[]>] [[-Title] <String>] [-As <String>] [-CssUri <Uri>] [-PostContent <String[]>] [-PreContent <String[]>] [-Meta <Hashtable>] [-Charset <String>] [-Transitional] [<CommonParameters>] ``` ### Fragment ``` ConvertTo-Html [-InputObject <PSObject>] [[-Property] <Object[]>] [-As <String>] [-Fragment] [-PostContent <String[]>] [-PreContent <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `ConvertTo-Html` cmdlet converts .NET objects into HTML that can be displayed in a Web browser. You can use this cmdlet to display the output of a command in a Web page. You can use the parameters of `ConvertTo-Html` to select object properties, to specify a table or list format, to specify the HTML page title, to add text before and after the object, and to return only the table or list fragment, instead of a strict DTD page. When you submit multiple objects to `ConvertTo-Html`, PowerShell creates the table (or list) based on the properties of the first object that you submit. If the remaining objects do not have one of the specified properties, the property value of that object is an empty cell. If the remaining objects have additional properties, those property values are not included in the file. ## EXAMPLES ### Example 1: Create a web page to display the date ```powershell ConvertTo-Html -InputObject (Get-Date) ``` This command creates an HTML page that displays the properties of the current date. It uses the **InputObject** parameter to submit the results of a `Get-Date` command to the `ConvertTo-Html` cmdlet. ### Example 2: Create a web page to display PowerShell aliases ```powershell Get-Alias | ConvertTo-Html | Out-File aliases.htm Invoke-Item aliases.htm ``` This command creates an HTML page that lists the PowerShell aliases in the current console. The command uses the `Get-Alias` cmdlet to get the aliases. It uses the pipeline operator (`|`) to send the aliases to the `ConvertTo-Html` cmdlet, which creates the HTML page. The command also uses the `Out-File` cmdlet to send the HTML code to the `aliases.htm` file. ### Example 3: Create a web page to display PowerShell events ```powershell Get-EventLog -LogName "Windows PowerShell" | ConvertTo-Html | Out-File pslog.htm ``` This command creates an HTML page called `pslog.htm` that displays the events in the Windows PowerShell event log on the local computer. It uses the `Get-EventLog` cmdlet to get the events in the Windows PowerShell log and then uses the pipeline operator (`|`) to send the events to the `ConvertTo-Html` cmdlet. The command also uses the `Out-File` cmdlet to send the HTML code to the `pslog.htm` file. The command also uses the `Out-File` cmdlet to send the HTML code to the `pslog.htm` file. ### Example 4: Create a web page to display processes ```powershell Get-Process | ConvertTo-Html -Property Name, Path, Company -Title "Process Information" | Out-File proc.htm Invoke-Item proc.htm ``` These commands create and open an HTML page that lists the name, path, and company of the processes on the local computer. The first command uses the `Get-Process` cmdlet to get objects that represent the processes running on the computer. The command uses the pipeline operator (`|`) to send the process objects to the `ConvertTo-Html` cmdlet. The command uses the **Property** parameter to select three properties of the process objects to be included in the table. The command uses the **Title** parameter to specify a title for the HTML page. The command also uses the `Out-File` cmdlet to send the resulting HTML to a file named `Proc.htm`. The second command uses the `Invoke-Item` cmdlet to open the `Proc.htm` in the default browser. ### Example 5: Create a web page to display service objects ```powershell Get-Service | ConvertTo-Html -CssUri "test.css" ``` ```Output <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>HTML TABLE</title> <link rel="stylesheet" type="text/css" href="test.css" /> ... ``` This command creates an HTML page of the service objects that the `Get-Service` cmdlet returns. The command uses the **CssUri** parameter to specify a cascading style sheet for the HTML page. The **CssUri** parameter adds an additional `<link rel="stylesheet" type="text/css" href="test.css">` tag to the resulting HTML. The HREF attribute in the tag contains the name of the style sheet. ### Example 6: Create a web page to display service objects ```powershell Get-Service | ConvertTo-Html -As List | Out-File services.htm ``` This command creates an HTML page of the service objects that the `Get-Service` cmdlet returns. The command uses the **As** parameter to specify a list format. The cmdlet `Out-File` sends the resulting HTML to the `Services.htm` file. ### Example 7: Create a web table for the current date ```powershell Get-Date | ConvertTo-Html -Fragment ``` ```Output <table> <colgroup>...</colgroup> <tr><th>DisplayHint</th><th>DateTime</th><th>Date</th><th>Day</th><th>DayOfWeek</th><th>DayOfYear</th><th>Hour</th> <th>Kind</th><th>Millisecond</th><th>Minute</th><th>Month</th><th>Second</th><th>Ticks</th><th>TimeOfDay</th><th>Year</th></tr> <tr><td>DateTime</td><td>Monday, May 05, 2008 10:40:04 AM</td><td>5/5/2008 12:00:00 AM</td><td>5</td><td>Monday</td> <td>126</td><td>10</td><td>Local</td><td>123</td><td>40</td><td>5</td><td>4</td><td>633455808041237213</td><td>10:40:04.12 37213</td><td>2008</td></tr> </table> ``` This command uses `ConvertTo-Html` to generate an HTML table of the current date. The command uses the `Get-Date` cmdlet to get the current date. It uses a pipeline operator (`|`) to send the results to the `ConvertTo-Html` cmdlet. The `ConvertTo-Html` command includes the **Fragment** parameter, which limits the output to an HTML table. As a result, the other elements of an HTML page, such as the `<HEAD>` and `<BODY>` tags, are omitted. ### Example 8: Create a web page to display PowerShell events ```powershell Get-EventLog -Log "Windows PowerShell" | ConvertTo-Html -Property Id, Level, Task ``` This command uses the `Get-EventLog` cmdlet to get events from the Windows PowerShell event log. It uses a pipeline operator (`|`) to send the events to the `ConvertTo-Html` cmdlet, which converts the events to HTML format. The `ConvertTo-Html` command uses the **Property** parameter to select only the **Id**, **Level**, and **Task** properties of the event. ### Example 9: Create a web page to display specified services ```powershell $htmlParams = @{ Title = "Windows Services: Server01" Body = Get-Date PreContent = "<P>Generated by Corporate IT</P>" PostContent = "For details, contact Corporate IT." } Get-Service A* | ConvertTo-Html @htmlParams | Out-File Services.htm Invoke-Item Services.htm ``` This command creates and opens a Web page that displays the services on the computer that begin with `A`. It uses the **Title**, **Body**, **PreContent**, and **PostContent** parameters of `ConvertTo-Html` to customize the output. The first part of the command uses the `Get-Service` cmdlet to get the services on the computer that begin with `A`. The command uses a pipeline operator (`|`) to send the results to the `ConvertTo-Html` cmdlet. The command also uses the `Out-File` cmdlet to send the output to the `Services.htm` file. A semicolon (`;`) ends the first command and starts a second command, which uses the `Invoke-Item` cmdlet to open the `Services.htm` file in the default browser. ### Example 10: Set the Meta properties and Charset of the HTML ```powershell Get-Service | ConvertTo-Html -Meta @{ refresh=10 author="Author's Name" keywords="PowerShell, HTML, ConvertTo-Html" } -Charset "UTF-8" ``` This command creates the HTML for a webpage with the meta tags for refresh, author, and keywords. The charset for the page is set to UTF-8 ### Example 11: Set the HTML to XHTML Transitional DTD ```powershell Get-Service | ConvertTo-Html -Transitional ``` This command sets the `DOCTYPE` of the returned HTML to **XHTML Transitional DTD** ## PARAMETERS ### -As Determines whether the object is formatted as a table or a list. Valid values are **Table** and **List**. The default value is **Table**. The **Table** value generates an HTML table that resembles the PowerShell table format. The header row displays the property names. Each table row represents an object and displays the object's values for each property. The **List** value generates a two-column HTML table for each object that resembles the PowerShell list format. The first column displays the property name. The second column displays the property value. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: Table, List Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Body Specifies the text to add after the opening `<BODY>` tag. By default, there is no text in that position. ```yaml Type: System.String[] Parameter Sets: Page Aliases: Required: False Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Charset Specifies text to add to the opening `<charset>` tag. By default, there is no text in that position. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.String Parameter Sets: Page Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CssUri Specifies the Uniform Resource Identifier (URI) of the cascading style sheet (CSS) that is applied to the HTML file. The URI is included in a style sheet link in the output. ```yaml Type: System.Uri Parameter Sets: Page Aliases: cu, uri Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Fragment Generates only an HTML table. The `<HTML>`, `<HEAD>`, `<TITLE>`, and `<BODY>` tags are omitted. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Fragment Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Head Specifies the content of the `<HEAD>` tag. The default is `<title\>HTML TABLE</title>`. If you use the **Head** parameter, the **Title** parameter is ignored. ```yaml Type: System.String[] Parameter Sets: Page Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects to be represented in HTML. Enter a variable that contains the objects or type a command or expression that gets the objects. If you use this parameter to submit multiple objects, such as all of the services on a computer, `ConvertTo-Html` creates a table that displays the properties of a collection or of an array of objects. To create a table of the individual objects, use the pipeline operator to pipe the objects to `ConvertTo-Html`. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Meta Specifies text to add to the opening `<meta>` tag. By default, there is no text in that position. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Collections.Hashtable Parameter Sets: Page Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PostContent Specifies text to add after the closing `</TABLE>` tag. By default, there is no text in that position. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PreContent Specifies text to add before the opening `<TABLE>` tag. By default, there is no text in that position. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Property Includes the specified properties of the objects in the HTML. The value of the **Property** parameter can be a new calculated property. The calculated property can be a script block or a hash table. Valid key-value pairs are: - `Name` (or label) - `<string>` (added in PowerShell 6.x) - `Expression` - `<string>` or `<script block>` - `FormatString` - `<string>` - `Width` - `<int32>` - must be greater than `0` - `Alignment` - value can be `Left`, `Center`, or `Right` For more information, see [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Title Specifies a title for the HTML file, that is, the text that appears between the `<TITLE>` tags. ```yaml Type: System.String Parameter Sets: Page Aliases: Required: False Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Transitional Changes the `DOCTYPE` to **XHTML Transitional DTD**, Default `DOCTYPE` is **XHTML Strict DTD**. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Page Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns an array of strings of HTML representing the converted object. ## NOTES To use this cmdlet, pipe one or more objects to the cmdlet or use the **InputObject** parameter to specify the object. When the input consists of multiple objects, the output of these two methods is quite different. - When you pipe multiple objects to a cmdlet, PowerShell sends the objects to the cmdlet one at a time. As a result, `ConvertTo-Html` creates a table that displays the individual objects. For example, if you pipe the processes on a computer to `ConvertTo-Html`, the resulting table displays all of the processes. - When you use the **InputObject** parameter to submit multiple objects, `ConvertTo-Html` receives these objects as a collection or as an array. As a result, it creates a table that displays the array and its properties, not the items in the array. For example, if you use **InputObject** to submit the processes on a computer to `ConvertTo-Html`, the resulting table displays an object array and its properties. To comply with the XHTML Strict DTD, the `DOCTYPE` tag is modified accordingly: `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"\>` ## RELATED LINKS [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md) [ConvertTo-Csv](ConvertTo-Csv.md) [ConvertTo-Json](ConvertTo-Json.md) [ConvertTo-Xml](ConvertTo-Xml.md) [Export-Clixml](Export-Clixml.md) [Import-Clixml](Import-Clixml.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/ConvertTo-Json.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 05/16/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertto-json?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: ConvertTo-Json --- # ConvertTo-Json ## SYNOPSIS Converts an object to a JSON-formatted string. ## SYNTAX ``` ConvertTo-Json [-InputObject] <Object> [-Depth <Int32>] [-Compress] [-EnumsAsStrings] [-AsArray] [-EscapeHandling <StringEscapeHandling>] [<CommonParameters>] ``` ## DESCRIPTION The `ConvertTo-Json` cmdlet converts any .NET object to a string in JavaScript Object Notation (JSON) format. The properties are converted to field names, the field values are converted to property values, and the methods are removed. > [!NOTE] > As of PowerShell 7.2, Extended Type System properties of **DateTime** and > **String** objects are no longer serialized and only the simple object is > converted to JSON format You can then use the `ConvertFrom-Json` cmdlet to convert a JSON-formatted string to a JSON object, which is easily managed in PowerShell. Many web sites use JSON instead of XML to serialize data for communication between servers and web-based apps. As of PowerShell 7.1, `ConvertTo-Json` emits a warning if the depth of the input object exceeds the depth specified for the command. This prevents unwanted data loss when converting objects. As of PowerShell 7.5-preview.3, `ConvertTo-Json` can serialize **BigInteger** values as raw JSON numbers. This cmdlet was introduced in Windows PowerShell 3.0. ## EXAMPLES ### Example 1 ```powershell (Get-UICulture).Calendar | ConvertTo-Json ``` ```Output { "MinSupportedDateTime": "0001-01-01T00:00:00", "MaxSupportedDateTime": "9999-12-31T23:59:59.9999999", "AlgorithmType": 1, "CalendarType": 1, "Eras": [ 1 ], "TwoDigitYearMax": 2029, "IsReadOnly": true } ``` This command uses the `ConvertTo-Json` cmdlet to convert a GregorianCalendar object to a JSON-formatted string. ### Example 2 ```powershell Get-Date | ConvertTo-Json; Get-Date | ConvertTo-Json -AsArray ``` ```Output "2021-08-05T16:13:05.6394416-07:00" [ "2021-08-05T16:13:05.6421709-07:00" ] ``` This example shows the output from `ConvertTo-Json` cmdlet with and without the **AsArray** switch parameter. You can see the second portion of the output is wrapped in array brackets. ### Example 3 ```powershell @{Account="User01";Domain="Domain01";Admin="True"} | ConvertTo-Json -Compress ``` ```Output {"Domain":"Domain01","Account":"User01","Admin":"True"} ``` This command shows the effect of using the **Compress** parameter of `ConvertTo-Json`. The compression affects only the appearance of the string, not its validity. ### Example 4 ```powershell Get-Date | Select-Object -Property * | ConvertTo-Json ``` ```Output { "DisplayHint": 2, "DateTime": "October 12, 2018 10:55:32 PM", "Date": "2018-10-12T00:00:00-05:00", "Day": 12, "DayOfWeek": 5, "DayOfYear": 285, "Hour": 22, "Kind": 2, "Millisecond": 639, "Minute": 55, "Month": 10, "Second": 32, "Ticks": 636749817326397744, "TimeOfDay": { "Ticks": 825326397744, "Days": 0, "Hours": 22, "Milliseconds": 639, "Minutes": 55, "Seconds": 32, "TotalDays": 0.95523888627777775, "TotalHours": 22.925733270666665, "TotalMilliseconds": 82532639.774400011, "TotalMinutes": 1375.54399624, "TotalSeconds": 82532.6397744 }, "Year": 2018 } ``` This example uses the `ConvertTo-Json` cmdlet to convert a **System.DateTime** object from the `Get-Date` cmdlet to a JSON-formatted string. The command uses the `Select-Object` cmdlet to get all (`*`) of the properties of the **DateTime** object. The output shows the JSON string that `ConvertTo-Json` returned. ### Example 5 ```powershell Get-Date | Select-Object -Property * | ConvertTo-Json | ConvertFrom-Json ``` ```Output DisplayHint : 2 DateTime : October 12, 2018 10:55:52 PM Date : 2018-10-12 12:00:00 AM Day : 12 DayOfWeek : 5 DayOfYear : 285 Hour : 22 Kind : 2 Millisecond : 768 Minute : 55 Month : 10 Second : 52 Ticks : 636749817527683372 TimeOfDay : @{Ticks=825527683372; Days=0; Hours=22; Milliseconds=768; Minutes=55; Seconds=52; TotalDays=0.95547185575463; TotalHours=22.9313245381111; TotalMilliseconds=82552768.3372; TotalMinutes=1375.87947228667; TotalSeconds=82552.7683372} Year : 2018 ``` This example shows how to use the `ConvertTo-Json` and `ConvertFrom-Json` cmdlets to convert an object to a JSON string and a JSON object. ## PARAMETERS ### -AsArray Outputs the object in array brackets, even if the input is a single object. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Compress Omits white space and indented formatting in the output string. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Depth Specifies how many levels of contained objects are included in the JSON representation. The value can be any number from `0` to `100`. The default value is `2`. `ConvertTo-Json` emits a warning if the number of levels in an input object exceeds this number. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 2 Accept pipeline input: False Accept wildcard characters: False ``` ### -EnumsAsStrings Provides an alternative serialization option that converts all enumerations to their string representation. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -EscapeHandling Controls how certain characters are escaped in the resulting JSON output. By default, only control characters (like newline) are escaped. Acceptable values are: - Default - Only control characters are escaped. - EscapeNonAscii - All non-ASCII and control characters are escaped. - EscapeHtml - HTML (`<`, `>`, `&`, `'`, `"`) and control characters are escaped. This parameter was introduced in PowerShell 6.2. ```yaml Type: Newtonsoft.Json.StringEscapeHandling Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Default Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects to convert to JSON format. Enter a variable that contains the objects, or type a command or expression that gets the objects. You can also pipe an object to `ConvertTo-Json`. The **InputObject** parameter is required, but its value can be null (`$null`) or an empty string. When the input object is `$null`, `ConvertTo-Json` returns the JSON representation of `null`. When the input object is an empty string, `ConvertTo-Json` returns the JSON representation of an empty string. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.Object You can pipe any object to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns a string representing the input object converted to a JSON string. ## NOTES The `ConvertTo-Json` cmdlet is implemented using [Newtonsoft Json.NET](https://www.newtonsoft.com/json). ## RELATED LINKS [An Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET](/previous-versions/dotnet/articles/bb299886(v=msdn.10)) [ConvertFrom-Json](ConvertFrom-Json.md) [Get-Content](../Microsoft.PowerShell.Management/Get-Content.md) [Get-UICulture](Get-UICulture.md) [Invoke-WebRequest](Invoke-WebRequest.md) [Invoke-RestMethod](Invoke-RestMethod.md) [NewtonSoft.Json.StringEscapeHandling](https://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_StringEscapeHandling.htm)

#File: reference/7.6/Microsoft.PowerShell.Utility/ConvertTo-Xml.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/18/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/convertto-xml?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: ConvertTo-Xml --- # ConvertTo-Xml ## SYNOPSIS Creates an XML-based representation of an object. ## SYNTAX ``` ConvertTo-Xml [-Depth <Int32>] [-InputObject] <PSObject> [-NoTypeInformation] [-As <String>] [<CommonParameters>] ``` ## DESCRIPTION The `ConvertTo-Xml` cmdlet creates an [XML-based](/dotnet/api/system.xml.xmldocument) representation of one or more .NET objects. To use this cmdlet, pipe one or more objects to the cmdlet, or use the **InputObject** parameter to specify the object. When you pipe multiple objects to `ConvertTo-Xml` or use the **InputObject** parameter to submit multiple objects, `ConvertTo-Xml` returns a single, in-memory XML document that includes representations of all the objects. This cmdlet is similar to [Export-Clixml](./Export-Clixml.md) except that `Export-Clixml` stores the resulting XML in a [Common Language Infrastructure (CLI)](https://www.ecma-international.org/publications-and-standards/standards/ecma-335/) file that can be reimported as objects with [Import-Clixml](./Import-Clixml.md). `ConvertTo-Xml` returns an in-memory representation of an XML document, so you can continue to process it in PowerShell. `ConvertTo-Xml` doesn't have an option to convert objects to CLI XML. ## EXAMPLES ### Example 1: Convert a date to XML ```powershell Get-Date | ConvertTo-Xml ``` This command converts the current date (a **DateTime** object) to XML. ### Example 2: Convert processes to XML ```powershell ConvertTo-Xml -As "Document" -InputObject (Get-Process) -Depth 3 ``` This command converts the process objects that represent all the processes on the computer into an XML document. The objects are expanded to a depth of three levels. ## PARAMETERS ### -As Determines the output format. The acceptable values for this parameter are: - `String` - Returns a single string. - `Stream` - Returns an array of strings. - `Document` - Returns an **XmlDocument** object. The default value is `Document`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: Stream, String, Document Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Depth Specifies how many levels of contained objects are included in the XML representation. The default value is 1. For example, if the object's properties also contain objects, to save an XML representation of the properties of the contained objects, you must specify a depth of 2. The default value can be overridden for the object type in the Types.ps1xml files. For more information, see [about_Types.ps1xml](../Microsoft.PowerShell.Core/About/about_Types.ps1xml.md). ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the object to be converted. Enter a variable that contains the objects, or type a command or expression that gets the objects. You can also pipe objects to `ConvertTo-Xml`. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -NoTypeInformation Omits the Type attribute from the object nodes. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet ## OUTPUTS ### System.String When you use the **As** parameter and set the value to `string`, this cmdlet returns the XML as a string. When the value is `stream`, this cmdlet returns an array of strings. ### System.Xml.XmlDocument By default, this cmdlet returns an XML document. ## NOTES ## RELATED LINKS [ConvertTo-Csv](ConvertTo-Csv.md) [ConvertTo-Html](ConvertTo-Html.md) [Export-Clixml](Export-Clixml.md) [Get-Date](Get-Date.md) [Import-Clixml](Import-Clixml.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Debug-Runspace.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/20/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/debug-runspace?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Debug-Runspace --- # Debug-Runspace ## SYNOPSIS Starts an interactive debugging session with a runspace. ## SYNTAX ### RunspaceParameterSet (Default) ``` Debug-Runspace [-Runspace] <Runspace> [-BreakAll] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### NameParameterSet ``` Debug-Runspace [-Name] <String> [-BreakAll] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### IdParameterSet ``` Debug-Runspace [-Id] <Int32> [-BreakAll] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### InstanceIdParameterSet ``` Debug-Runspace [-InstanceId] <Guid> [-BreakAll] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Debug-Runspace` cmdlet starts an interactive debugging session with a local or remote active runspace. You can find a runspace that you want to debug by first running `Get-Process` to find processes associated with PowerShell, then `Enter-PSHostProcess` with the process ID specified in the **Id** parameter to attach to the process, and then `Get-Runspace` to list runspaces within the PowerShell host process. After you have selected a runspace to debug, if the runspace is currently running a command or script, or if the script has stopped at a breakpoint, PowerShell opens a remote debugger session for the runspace. You can debug the runspace script in the same way remote session scripts are debugged. You can only attach to a PowerShell host process if you are an administrator on the computer that is running the process, or you are running the script that you want to debug. Also, you cannot enter the host process that is running the current PowerShell session. You can only enter a host process that is running a different PowerShell session. ## EXAMPLES ### Example 1: Debug a remote runspace In this example, you debug a runspace that is open on a remote computer, WS10TestServer. In the first line of the command, you run `Get-Process` on the remote computer, and filter for Windows PowerShell host processes. In this example, you want to debug process ID 1152, the Windows PowerShell ISE host process. ```powershell PS C:\> Get-Process -ComputerName "WS10TestServer" -Name "*powershell*" Handles WS(K) VM(M) CPU(s) Id ProcessName ------- ----- ----- ------ -- ----------- 377 69912 63 2.09 2420 powershell 399 123396 829 4.48 1152 powershell_ise PS C:\> Enter-PSSession -ComputerName "WS10TestServer" [WS10TestServer]:PS C:\> Enter-PSHostProcess -Id 1152 [WS10TestServer:][Process:1152]: PS C:\Users\Test\Documents> Get-Runspace Id Name ComputerName Type State Availability -- ---- ------------ ---- ----- ------------ 1 Runspace1 WS10TestServer Remote Opened Available 2 RemoteHost WS10TestServer Remote Opened Busy [WS10TestServer][Process:1152]: PS C:\Users\Test\Documents> Debug-Runspace -Id 2 Hit Line breakpoint on 'C:\TestWFVar1.ps1:83' At C:\TestWFVar1.ps1:83 char:1 + $scriptVar = "Script Variable" + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [Process:1152]: [RSDBG: 2]: PS C:\> > ``` In the second command, you run `Enter-PSSession` to open a remote session on WS10TestServer. In the third command, you attach to the Windows PowerShell ISE host process running on the remote server by running `Enter-PSHostProcess`, and specifying the ID of the host process that you obtained in the first command, 1152. In the fourth command, you list available runspaces for process ID 1152 by running `Get-Runspace`. You note the ID number of the Busy runspace; it is running a script that you want to debug. In the last command, you start debugging an opened runspace that is running a script, `TestWFVar1.ps1`, by running `Debug-Runspace`, and identifying the runspace by its ID, 2, by adding the **Id** parameter. Because there's a breakpoint in the script, the debugger opens. ## PARAMETERS ### -BreakAll Allows you to break immediately in the current location when the debugger attaches. This parameter was added in PowerShell 7.2. ```yaml Type: SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies the ID number of a runspace. You can run `Get-Runspace` to show runspace IDs. ```yaml Type: System.Int32 Parameter Sets: IdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InstanceId Specifies a runspace by its instance ID, a GUID that you can show by running `Get-Runspace`. ```yaml Type: System.Guid Parameter Sets: InstanceIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies a runspace by its name. You can run `Get-Runspace` to show the names of runspaces. ```yaml Type: System.String Parameter Sets: NameParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Runspace Specifies a runspace object. The simplest way to provide a value for this parameter is to specify a variable that contains the results of a filtered `Get-Runspace` command. ```yaml Type: System.Management.Automation.Runspaces.Runspace Parameter Sets: RunspaceParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: True Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: True Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.Runspaces.Runspace You can pipe the results of a `Get-Runspace` command to this cmdlet. ## OUTPUTS ## NOTES `Debug-Runspace` works on runspaces that are in the Opened state. If a runspace state changes from Opened to another state, that runspace is automatically removed from the running list. A runspace is added to the running list only if it meets the following criteria. - If it is coming from Invoke-Command; that is, it has an `Invoke-Command` GUID ID. - If it is coming from `Debug-Runspace`; that is, it has a `Debug-Runspace` GUID ID. - If it is coming from a PowerShell workflow, and its workflow job ID is the same as the current active debugger workflow job ID. ## RELATED LINKS [about_Debuggers](../Microsoft.PowerShell.Core/About/about_Debuggers.md) [Debug-Job](../Microsoft.PowerShell.Core/Debug-Job.md) [Get-Runspace](Get-Runspace.md) [Get-Process](../Microsoft.PowerShell.Management/Get-Process.md) [Enter-PSHostProcess](../Microsoft.PowerShell.Core/Enter-PSHostProcess.md) [Enter-PSSession](../Microsoft.PowerShell.Core/Enter-PSSession.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Disable-PSBreakpoint.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/20/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/disable-psbreakpoint?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Disable-PSBreakpoint --- # Disable-PSBreakpoint ## SYNOPSIS Disables the breakpoints in the current console. ## SYNTAX ### Breakpoint (Default) ``` Disable-PSBreakpoint [-PassThru] [-Breakpoint] <Breakpoint[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Id ``` Disable-PSBreakpoint [-PassThru] [-Id] <Int32[]> [-Runspace <Runspace>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Disable-PSBreakpoint` cmdlet disables breakpoints, which assures that they are not hit when the script runs. You can use it to disable all breakpoints, or you can specify breakpoints by submitting breakpoint objects or breakpoint IDs. Technically, this cmdlet changes the value of the Enabled property of a breakpoint object to False. To re-enable a breakpoint, use the `Enable-PSBreakpoint` cmdlet. Breakpoints are enabled by default when you create them using the `Set-PSBreakpoint` cmdlet. A breakpoint is a point in a script where execution stops temporarily so that you can examine the instructions in the script. `Disable-PSBreakpoint` is one of several cmdlets designed for debugging PowerShell scripts. For more information about the PowerShell debugger, see [about_Debuggers](../microsoft.powershell.core/about/about_debuggers.md). ## EXAMPLES ### Example 1: Set a breakpoint and disable it These commands disable a newly-created breakpoint. ```powershell $B = Set-PSBreakpoint -Script "sample.ps1" -Variable "name" $B | Disable-PSBreakpoint ``` The `Set-PSBreakpoint` cmdlet creates a breakpoint on the `$Name` variable in the `Sample.ps1` script and saves the breakpoint object in the `$B` variable. The `Disable-PSBreakpoint` cmdlet disables the new breakpoint. It uses a pipeline operator (`|`) to send the breakpoint object in `$B` to the `Disable-PSBreakpoint` cmdlet. As a result of this command, the value of the **Enabled** property of the breakpoint object in `$B` is **False**. ### Example 2: Disable a breakpoint This command disables the breakpoint with breakpoint ID 0. ```powershell Disable-PSBreakpoint -Id 0 ``` ### Example 3: Create a disabled breakpoint This command creates a new breakpoint that is disabled until you enable it. ```powershell Disable-PSBreakpoint -Breakpoint ($B = Set-PSBreakpoint -Script "sample.ps1" -Line 5) ``` It uses the `Disable-PSBreakpoint` cmdlet to disable the breakpoint. The value of the **Breakpoint** parameter is a `Set-PSBreakpoint` command that sets a new breakpoint, generates a breakpoint object, and saves the object in the `$B` variable. Cmdlet parameters that take objects as their values can accept a variable that contains the object or a command that gets or generates the object. In this case, because `Set-PSBreakpoint` generates a breakpoint object, it can be used as the value of the **Breakpoint** parameter. ### Example 4: Disable all breakpoints in the current console This command disables all breakpoints in the current console. ```powershell `Get-PSBreakpoint` | Disable-PSBreakpoint ``` ### Example 5: Disable a breakpoint in a runspace In this example, a job is started and a breakpoint is set to break when the `Set-PSBreakpoint` is run. The runspace is stored in a variable and passed to the `Get-PSBreakpoint` command with the **Runspace** parameter. The output of `Get-PSBreakpoint` is piped to `Disable-PSBreakpoint` to disable the breakpoint in the runspace. ```powershell Start-Job -ScriptBlock { Set-PSBreakpoint -Command Start-Sleep Start-Sleep -Seconds 10 } $runspace = Get-Runspace -Id 1 Get-PSBreakpoint -Runspace $runspace | Disable-Breakpoint -Runspace $runspace ``` ## PARAMETERS ### -Breakpoint Specifies the breakpoints to disable. Enter a variable that contains breakpoint objects or a command that gets breakpoint objects, such as a `Get-PSBreakpoint` command. You can also pipe breakpoint objects to the `Disable-PSBreakpoint` cmdlet. ```yaml Type: System.Management.Automation.Breakpoint[] Parameter Sets: Breakpoint Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Id Disables the breakpoints with the specified breakpoint IDs. Enter the IDs or a variable that contains the IDs. You cannot pipe IDs to `Disable-PSBreakpoint`. ```yaml Type: System.Int32[] Parameter Sets: Id Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Returns an object representing the enabled breakpoints. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Runspace Specifies the Id of a **Runspace** object so you can interact with breakpoints in the specified runspace. This parameter was added in PowerShell 7.2. ```yaml Type: Runspace Parameter Sets: Id Aliases: RunspaceId Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.Breakpoint You can pipe a breakpoint object to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.Breakpoint When you use the **PassThru** parameter, this cmdlet returns a breakpoint object representing the disabled breakpoint. ## NOTES PowerShell includes the following aliases for `Disable-PSBreakpoint`: - All platforms: - `dbp` ## RELATED LINKS [Enable-PSBreakpoint](Enable-PSBreakpoint.md) [Get-PSBreakpoint](Get-PSBreakpoint.md) [Get-PSCallStack](Get-PSCallStack.md) [Remove-PSBreakpoint](Remove-PSBreakpoint.md) [Set-PSBreakpoint](Set-PSBreakpoint.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Disable-RunspaceDebug.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 03/19/2020 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/disable-runspacedebug?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Disable-RunspaceDebug --- # Disable-RunspaceDebug ## SYNOPSIS Disables debugging on one or more runspaces, and releases any pending debugger stop. ## SYNTAX ### RunspaceNameParameterSet (Default) ``` Disable-RunspaceDebug [[-RunspaceName] <String[]>] [<CommonParameters>] ``` ### RunspaceParameterSet ``` Disable-RunspaceDebug [-Runspace] <Runspace[]> [<CommonParameters>] ``` ### RunspaceIdParameterSet ``` Disable-RunspaceDebug [-RunspaceId] <Int32[]> [<CommonParameters>] ``` ### RunspaceInstanceIdParameterSet ``` Disable-RunspaceDebug [-RunspaceInstanceId] <Guid[]> [<CommonParameters>] ``` ### ProcessNameParameterSet ``` Disable-RunspaceDebug [[-ProcessName] <String>] [[-AppDomainName] <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Disable-RunspaceDebug` cmdlet disables debugging on one or more runspaces, and releases any pending debugger stop. ## EXAMPLES ### 1: Disable the default runspace debugger ```powershell Disable-RunspaceDebug Get-RunspaceDebug ``` ```Output Id Name Enabled BreakAll -- ---- ------- -------- 1 Runspace1 False False ``` ## PARAMETERS ### -AppDomainName The name of the application domain that hosts the PowerShell runspace. ```yaml Type: System.String[] Parameter Sets: ProcessNameParameterSet Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProcessName The name of the process that hosts the PowerShell runspace. ```yaml Type: System.String Parameter Sets: ProcessNameParameterSet Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Runspace One or more **Runspace** objects to be disabled. ```yaml Type: System.Management.Automation.Runspaces.Runspace[] Parameter Sets: RunspaceParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -RunspaceId One or more **Runspace** Id numbers to be disabled. ```yaml Type: System.Int32[] Parameter Sets: RunspaceIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RunspaceInstanceId One or more **Runspace** GUIDs to be disabled. ```yaml Type: System.Guid[] Parameter Sets: RunspaceInstanceIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RunspaceName One or more **Runspace** names to be disabled. ```yaml Type: System.String[] Parameter Sets: RunspaceNameParameterSet Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ## NOTES ## RELATED LINKS [Enable-RunspaceDebug](Enable-RunspaceDebug.md) [Get-RunspaceDebug](Get-RunspaceDebug.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Enable-PSBreakpoint.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/20/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/enable-psbreakpoint?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Enable-PSBreakpoint --- # Enable-PSBreakpoint ## SYNOPSIS Enables the breakpoints in the current console. ## SYNTAX ### Breakpoint (Default) ``` Enable-PSBreakpoint [-PassThru] [-Breakpoint] <Breakpoint[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Id ``` Enable-PSBreakpoint [-PassThru] [-Id] <Int32[]> [-Runspace <Runspace>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Enable-PSBreakpoint` cmdlet re-enables disabled breakpoints. You can use it to enable all breakpoints, or specific breakpoints by providing breakpoint objects or IDs. A breakpoint is a point in a script where execution stops temporarily so that you can examine the state of the script. Newly created breakpoints are automatically enabled, but can be disabled using `Disable-PSBreakpoint`. Technically, this cmdlet changes the value of the **Enabled** property of a breakpoint object to **True**. `Enable-PSBreakpoint` is one of several cmdlets designed for debugging PowerShell scripts. For more information about the PowerShell debugger, see [about_Debuggers](../Microsoft.PowerShell.Core/About/about_Debuggers.md). ## EXAMPLES ### Example 1: Enable all breakpoints This example enables all breakpoints in the current session. ```powershell Get-PSBreakpoint | Enable-PSBreakpoint ``` Using aliases, this example can be abbreviated as `gbp | ebp`. ### Example 2: Enable breakpoints by ID This example enables multiple breakpoints using their breakpoint IDs. ```powershell Enable-PSBreakpoint -Id 0, 1, 5 ``` ### Example 3: Enable a disabled breakpoint This example re-enables a breakpoint that has been disabled. ```powershell $B = Set-PSBreakpoint -Script "sample.ps1" -Variable Name -PassThru $B | Enable-PSBreakpoint -PassThru ``` ```Output AccessMode : Write Variable : Name Action : Enabled : False HitCount : 0 Id : 0 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 AccessMode : Write Variable : Name Action : Enabled : True HitCount : 0 Id : 0 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 ``` `Set-PSBreakpoint` creates a breakpoint on the **Name** variable in the `Sample.ps1` script saving the breakpoint object in the `$B` variable. The **PassThru** parameter displays the value of the **Enabled** property of the breakpoint is **False**. `Enable-PSBreakpoint` re-enables the breakpoint. Again, using the **PassThru** parameter we see that the value of the **Enabled** property is **True**. ### Example 4: Enable breakpoints using a variable This example enables a set of breakpoints using the breakpoint objects. ```powershell $B = Get-PSBreakpoint -Id 3, 5 Enable-PSBreakpoint -Breakpoint $B ``` `Get-PSBreakpoint` gets the breakpoints and saves them in the `$B` variable. Using the **Breakpoint** parameter, `Enable-PSBreakpoint` enables the breakpoints. This example is equivalent to running `Enable-PSBreakpoint -Id 3, 5`. ### Example 5: Enable a breakpoint in a runspace In this example, a job is started with a breakpoint is set to break then disabled. The runspace is stored in a variable and passed to the `Get-PSBreakpoint` command with the **Runspace** parameter. The output of `Get-PSBreakpoint` is piped to `Enable-PSBreakpoint` to enable the breakpoint in the runspace. ```powershell Start-Job -ScriptBlock { $bp = Set-PSBreakpoint -Command Start-Sleep Disable-PSBreakpoint $bp Start-Sleep -Seconds 10 } $runspace = Get-Runspace -Id 1 Get-PSBreakpoint -Runspace $runspace | Enable-Breakpoint -Runspace $runspace ``` ## PARAMETERS ### -Breakpoint Specifies the breakpoints to enable. Provide a variable containing breakpoints or a command that gets breakpoint objects, such as `Get-PSBreakpoint`. You can also pipe breakpoint objects to `Enable-PSBreakpoint`. ```yaml Type: System.Management.Automation.Breakpoint[] Parameter Sets: Breakpoint Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Id Specifies the **Id** numbers of the breakpoints to enable. The default value is all breakpoints. Provide the **Id** by number or in a variable. You can't pipe **Id** numbers to `Enable-PSBreakpoint`. To find the **Id** of a breakpoint, use the `Get-PSBreakpoint` cmdlet. ```yaml Type: System.Int32[] Parameter Sets: Id Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Returns an object representing the breakpoint being enabled. By default, this cmdlet doesn't generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Runspace Specifies the Id of a **Runspace** object so you can interact with breakpoints in the specified runspace. This parameter was added in PowerShell 7.2. ```yaml Type: Runspace Parameter Sets: Id Aliases: RunspaceId Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.Breakpoint You can pipe a breakpoint object to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.Breakpoint When you use the **PassThru** parameter, this cmdlet returns a breakpoint object representing the enabled breakpoint. ## NOTES PowerShell includes the following aliases for `Enable-PSBreakpoint`: - All platforms: - `ebp` - The `Enable-PSBreakpoint` cmdlet doesn't generate an error if you try to enable a breakpoint that is already enabled. As such, you can enable all breakpoints without error, even when only a few are disabled. - Breakpoints are enabled when you create them by using the `Set-PSBreakpoint` cmdlet. You don't need to enable newly created breakpoints. ## RELATED LINKS [Disable-PSBreakpoint](Disable-PSBreakpoint.md) [Get-PSBreakpoint](Get-PSBreakpoint.md) [Get-PSCallStack](Get-PSCallStack.md) [Remove-PSBreakpoint](Remove-PSBreakpoint.md) [Set-PSBreakpoint](Set-PSBreakpoint.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Enable-RunspaceDebug.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 03/19/2020 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/enable-runspacedebug?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Enable-RunspaceDebug --- # Enable-RunspaceDebug ## SYNOPSIS Enables debugging on runspaces where any breakpoint is preserved until a debugger is attached. ## SYNTAX ### RunspaceNameParameterSet (Default) ``` Enable-RunspaceDebug [-BreakAll] [[-RunspaceName] <String[]>] [<CommonParameters>] ``` ### RunspaceParameterSet ``` Enable-RunspaceDebug [-BreakAll] [-Runspace] <Runspace[]> [<CommonParameters>] ``` ### RunspaceIdParameterSet ``` Enable-RunspaceDebug [-BreakAll] [-RunspaceId] <Int32[]> [<CommonParameters>] ``` ### RunspaceInstanceIdParameterSet ``` Enable-RunspaceDebug [-RunspaceInstanceId] <Guid[]> [<CommonParameters>] ``` ### ProcessNameParameterSet ``` Enable-RunspaceDebug [[-ProcessName] <String>] [[-AppDomainName] <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Enable-RunspaceDebug` cmdlet enables debugging on runspaces where any breakpoint is preserved until a debugger is attached. ## EXAMPLES ### 1: Enable the default runspace debugger ```powershell Enable-RunspaceDebug Get-RunspaceDebug ``` ```Output Id Name Enabled BreakAll -- ---- ------- -------- 1 Runspace1 True False ``` ## PARAMETERS ### -AppDomainName The name of the application domain that hosts the PowerShell runspace. ```yaml Type: System.String[] Parameter Sets: ProcessNameParameterSet Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -BreakAll Causes any running command or script in the Runspace to stop in step mode, regardless of whether a debugger is currently attached. The script or command will remain stopped until a debugger is attached to debug the current stop point. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: RunspaceNameParameterSet, RunspaceParameterSet, RunspaceIdParameterSet Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProcessName The name of the process that hosts the PowerShell runspace. ```yaml Type: System.String Parameter Sets: ProcessNameParameterSet Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Runspace One or more **Runspace** objects to be disabled. ```yaml Type: System.Management.Automation.Runspaces.Runspace[] Parameter Sets: RunspaceParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -RunspaceId One or more **Runspace** Id numbers to be disabled. ```yaml Type: System.Int32[] Parameter Sets: RunspaceIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RunspaceInstanceId One or more **Runspace** GUIDs to be disabled. ```yaml Type: System.Guid[] Parameter Sets: RunspaceInstanceIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RunspaceName One or more **Runspace** names to be disabled. ```yaml Type: System.String[] Parameter Sets: RunspaceNameParameterSet Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ## NOTES ## RELATED LINKS [Disable-RunspaceDebug](Disable-RunspaceDebug.md) [Get-RunspaceDebug](Get-RunspaceDebug.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Export-Alias.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/export-alias?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Export-Alias --- # Export-Alias ## SYNOPSIS Exports information about currently defined aliases to a file. ## SYNTAX ### ByPath (Default) ``` Export-Alias [-Path] <String> [[-Name] <String[]>] [-PassThru] [-As <ExportAliasFormat>] [-Append] [-Force] [-NoClobber] [-Description <String>] [-Scope <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ByLiteralPath ``` Export-Alias -LiteralPath <String> [[-Name] <String[]>] [-PassThru] [-As <ExportAliasFormat>] [-Append] [-Force] [-NoClobber] [-Description <String>] [-Scope <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Export-Alias` cmdlet exports the aliases in the current session to a file. If the output file does not exist, the cmdlet will create it. `Export-Alias` can export the aliases in a particular scope or all scopes, it can generate the data in CSV format or as a series of Set-Alias commands that you can add to a session or to a PowerShell profile. ## EXAMPLES ### Example 1: Export an alias ```powershell Export-Alias -Path "alias.csv" ``` This command exports current alias information to a file named Alias.csv in the current directory. ### Example 2: Export an alias unless the export file already exists ```powershell Export-Alias -Path "alias.csv" -NoClobber ``` This command exports the aliases in the current session to an Alias.csv file. Because the **NoClobber** parameter is specified, the command will fail if an Alias.csv file already exists in the current directory. ### Example 3: Append aliases to a file ```powershell Export-Alias -Path "alias.csv" -Append -Description "Appended Aliases" -Force ``` This command appends the aliases in the current session to the Alias.csv file. The command uses the **Description** parameter to add a description to the comments at the top of the file. The command also uses the **Force** parameter to overwrite any existing Alias.csv files, even if they have the read-only attribute. ### Example 4: Export aliases as a script ```powershell Export-Alias -Path "alias.ps1" -As Script Add-Content -Path $PROFILE -Value (Get-Content alias.ps1) $S = New-PSSession -ComputerName Server01 Invoke-Command -Session $S -FilePath .\alias.ps1 ``` This example shows how to use the script file format that `Export-Alias` generates. The first command exports the aliases in the session to the Alias.ps1 file. It uses the **As** parameter with a value of Script to generate a file that contains a Set-Alias command for each alias. The second command adds the aliases in the Alias.ps1 file to the CurrentUser-CurrentHost profile. The path to the profile is saved in the `$PROFILE` variable. The command uses the `Get-Content` cmdlet to get the aliases from the Alias.ps1 file and the `Add-Content` cmdlet to add them to the profile. For more information, see [about_Profiles](../Microsoft.PowerShell.Core/About/about_Profiles.md). The third and fourth commands add the aliases in the Alias.ps1 file to a remote session on the Server01 computer. The third command uses the `New-PSSession` cmdlet to create the session. The fourth command uses the **FilePath** parameter of the `Invoke-Command` cmdlet to run the Alias.ps1 file in the new session. ## PARAMETERS ### -Append Indicates that this cmdlet appends the output to the specified file, rather than overwriting the existing contents of that file. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -As Specifies the output format. CSV is the default. The acceptable values for this parameter are: - CSV. Comma-separated value (CSV) format. - Script. Creates a `Set-Alias` command for each exported alias. If you name the output file with a `.ps1` file name extension, you can run it as a script to add the aliases to any session. ```yaml Type: Microsoft.PowerShell.Commands.ExportAliasFormat Parameter Sets: (All) Aliases: Accepted values: Csv, Script Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Description Specifies the description of the exported file. The description appears as a comment at the top of the file, following the header information. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Forces the command to run without asking for user confirmation. Overwrites the output file, even if the read-only attribute is set on the file. By default, `Export-Alias` overwrites files without warning, unless the read-only or hidden attribute is set or the **NoClobber** parameter is used in the command. The **NoClobber** parameter takes precedence over the **Force** parameter when both are used in a command. The **Force** parameter cannot force `Export-Alias` to overwrite files with the hidden attribute. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to the output file. Unlike **Path**, the value of the **LiteralPath** parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String Parameter Sets: ByLiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies the names as an array of the aliases to export. Wildcards are permitted. By default, `Export-Alias` exports all aliases in the session or scope. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -NoClobber Indicates that this cmdlet prevents `Export-Alias` from overwriting any files, even if the **Force** parameter is used in the command. If the **NoClobber** parameter is omitted, `Export-Alias` will overwrite an existing file without warning, unless the read-only attribute is set on the file. **NoClobber** takes precedence over the **Force** parameter, which permits `Export-Alias` to overwrite a file with the read-only attribute. **NoClobber** does not prevent the **Append** parameter from adding content to an existing file. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: NoOverwrite Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to the output file. Wildcards are permitted, but the resulting path value must resolve to a single file name. ```yaml Type: System.String Parameter Sets: ByPath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Scope Specifies the scope from which the aliases should be exported. The acceptable values for this parameter are: - `Global` - `Local` - `Script` - A number relative to the current scope (0 through the number of scopes where 0 is the current scope and 1 is its parent) The default value is `Local`. For more information, see [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.AliasInfo When you use the **PassThru** parameter, this cmdlet returns an **AliasInfo** object representing the alias. ## NOTES PowerShell includes the following aliases for `Export-Alias`: - All platforms: - `epal` * You can only Export-Aliases to a file. ## RELATED LINKS [Get-Alias](Get-Alias.md) [Import-Alias](Import-Alias.md) [New-Alias](New-Alias.md) [Set-Alias](Set-Alias.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Export-Clixml.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/31/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/export-clixml?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Export-Clixml --- # Export-Clixml ## SYNOPSIS Creates an XML-based representation of an object or objects and stores it in a file. ## SYNTAX ### ByPath (Default) ``` Export-Clixml [-Depth <Int32>] [-Path] <String> -InputObject <PSObject> [-Force] [-NoClobber] [-Encoding <Encoding>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ByLiteralPath ``` Export-Clixml [-Depth <Int32>] -LiteralPath <String> -InputObject <PSObject> [-Force] [-NoClobber] [-Encoding <Encoding>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Export-Clixml` cmdlet serialized an object into a Common Language Infrastructure (CLI) XML-based representation stores it in a file. You can then use the `Import-Clixml` cmdlet to recreate the saved object based on the contents of that file. For more information about CLI, see [Language independence](/dotnet/standard/language-independence). This cmdlet is similar to `ConvertTo-Xml`, except that `Export-Clixml` stores the resulting XML in a file. `ConvertTo-Xml` returns the XML, so you can continue to process it in PowerShell. A valuable use of `Export-Clixml` on Windows computers is to export credentials and secure strings securely as XML. For an example, see Example 3. ## EXAMPLES ### Example 1: Export a string to an XML file This example creates an XML file that stores in the current directory, a representation of the string **This is a test**. ```powershell "This is a test" | Export-Clixml -Path .\sample.xml ``` The string `This is a test` is sent down the pipeline. `Export-Clixml` uses the **Path** parameter to create an XML file named `sample.xml` in the current directory. ### Example 2: Export an object to an XML file This example shows how to export an object to an XML file and then create an object by importing the XML from the file. ```powershell Get-Acl C:\test.txt | Export-Clixml -Path .\FileACL.xml $fileacl = Import-Clixml -Path .\FileACL.xml ``` The `Get-Acl` cmdlet gets the security descriptor of the `Test.txt` file. It sends the object down the pipeline to pass the security descriptor to `Export-Clixml`. The XML-based representation of the object is stored in a file named `FileACL.xml`. The `Import-Clixml` cmdlet creates an object from the XML in the `FileACL.xml` file. Then, it saves the object in the `$fileacl` variable. ### Example 3: Encrypt an exported credential object on Windows In this example, given a credential that you've stored in the `$Credential` variable by running the `Get-Credential` cmdlet, you can run the `Export-Clixml` cmdlet to save the credential to disk. > [!IMPORTANT] > `Export-Clixml` only exports encrypted credentials on Windows. On non-Windows operating systems > such as macOS and Linux, credentials are exported as a plain text stored as a Unicode character > array. This provides some obfuscation but does not provide encryption. ```powershell $Credxmlpath = Join-Path (Split-Path $PROFILE) TestScript.ps1.credential $Credential | Export-Clixml $Credxmlpath $Credxmlpath = Join-Path (Split-Path $PROFILE) TestScript.ps1.credential $Credential = Import-Clixml $Credxmlpath ``` The `Export-Clixml` cmdlet encrypts credential objects by using the Windows [Data Protection API](/previous-versions/windows/apps/hh464970(v=win.10)). The encryption ensures that only your user account on only that computer can decrypt the contents of the credential object. The exported `CLIXML` file can't be used on a different computer or by a different user. In the example, the file in which the credential is stored is represented by `TestScript.ps1.credential`. Replace **TestScript** with the name of the script with which you're loading the credential. You send the credential object down the pipeline to `Export-Clixml`, and save it to the path, `$Credxmlpath`, that you specified in the first command. To import the credential automatically into your script, run the final two commands. Run `Import-Clixml` to import the secured credential object into your script. This import eliminates the risk of exposing plain-text passwords in your script. ### Example 4: Exporting a credential object on Linux or macOS In this example, we create a **PSCredential** in the `$Credential` variable using the `Get-Credential` cmdlet. Then we use `Export-Clixml` to save the credential to disk. > [!IMPORTANT] > `Export-Clixml` only exports encrypted credentials on Windows. On non-Windows operating systems > such as macOS and Linux, credentials are exported as a plain text stored as a Unicode character > array. This provides some obfuscation but does not provide encryption. ```powershell PS> $Credential = Get-Credential PowerShell credential request Enter your credentials. User: User1 Password for user User1: ******** PS> $Credential | Export-Clixml ./cred2.xml PS> Get-Content ./cred2.xml ... <Props> <S N="UserName">User1</S> <SS N="Password">700061007300730077006f0072006400</SS> </Props> ... PS> 'password' | Format-Hex -Encoding unicode Label: String (System.String) <52D60C91> Offset Bytes Ascii 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ------ ----------------------------------------------- ----- 0000000000000000 70 00 61 00 73 00 73 00 77 00 6F 00 72 00 64 00 p a s s w o r d ``` The output of `Get-Content` in this example has been truncate to focus on the credential information in the XML file. Note that the plain text value of the password is stored in the XML file as a Unicode character array as proven by `Format-Hex`. So the value is encoded but not encrypted. ## PARAMETERS ### -Depth Specifies how many levels of contained objects are included in the XML representation. The default value is `2`. The default value can be overridden for the object type in the `Types.ps1xml` files. For more information, see [about_Types.ps1xml](../Microsoft.PowerShell.Core/About/about_Types.ps1xml.md). ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 2 Accept pipeline input: False Accept wildcard characters: False ``` ### -Encoding Specifies the type of encoding for the target file. The default value is `utf8NoBOM`. The acceptable values for this parameter are as follows: - `ascii`: Uses the encoding for the ASCII (7-bit) character set. - `ansi`: Uses the encoding for the for the current culture's ANSI code page. This option was added in 7.4. - `bigendianunicode`: Encodes in UTF-16 format using the big-endian byte order. - `bigendianutf32`: Encodes in UTF-32 format using the big-endian byte order. - `oem`: Uses the default encoding for MS-DOS and console programs. - `unicode`: Encodes in UTF-16 format using the little-endian byte order. - `utf7`: Encodes in UTF-7 format. - `utf8`: Encodes in UTF-8 format. - `utf8BOM`: Encodes in UTF-8 format with Byte Order Mark (BOM) - `utf8NoBOM`: Encodes in UTF-8 format without Byte Order Mark (BOM) - `utf32`: Encodes in UTF-32 format. Beginning with PowerShell 6.2, the **Encoding** parameter also allows numeric IDs of registered code pages (like `-Encoding 1251`) or string names of registered code pages (like `-Encoding "windows-1251"`). For more information, see the .NET documentation for [Encoding.CodePage](/dotnet/api/system.text.encoding.codepage?view=netcore-2.2). Starting with PowerShell 7.4, you can use the `Ansi` value for the **Encoding** parameter to pass the numeric ID for the current culture's ANSI code page without having to specify it manually. > [!NOTE] > **UTF-7*** is no longer recommended to use. As of PowerShell 7.1, a warning is written if you > specify `utf7` for the **Encoding** parameter. ```yaml Type: System.Text.Encoding Parameter Sets: (All) Aliases: Accepted values: ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 Required: False Position: Named Default value: UTF8NoBOM Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Forces the command to run without asking for user confirmation. Causes the cmdlet to clear the read-only attribute of the output file if necessary. The cmdlet will attempt to reset the read-only attribute when the command completes. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the object to be converted. Enter a variable that contains the objects, or type a command or expression that gets the objects. You can also pipe objects to `Export-Clixml`. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to the file where the XML representation of the object will be stored. Unlike **Path**, the value of the **LiteralPath** parameter is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String Parameter Sets: ByLiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NoClobber Indicates that the cmdlet doesn't overwrite the contents of an existing file. By default, if a file exists in the specified path, `Export-Clixml` overwrites the file without warning. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: NoOverwrite Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to the file where the XML representation of the object will be stored. ```yaml Type: System.String Parameter Sets: ByPath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipeline any object to this cmdlet. ## OUTPUTS ### System.IO.FileInfo This cmdlet returns a **FileInfo** object representing the created file with the stored data. ## NOTES ## RELATED LINKS [ConvertTo-Html](ConvertTo-Html.md) [ConvertTo-Xml](ConvertTo-Xml.md) [Export-Csv](Export-Csv.md) [Import-Clixml](Import-Clixml.md) [Join-Path](../Microsoft.PowerShell.Management/Join-Path.md) [Securely Store Credentials on Disk](https://powershellcookbook.com/recipe/PukO/securely-store-credentials-on-disk) [Use PowerShell to Pass Credentials to Legacy Systems](https://devblogs.microsoft.com/scripting/use-powershell-to-pass-credentials-to-legacy-systems/) [Windows.Security.Cryptography.DataProtection](/uwp/api/windows.security.cryptography.dataprotection)

#File: reference/7.6/Microsoft.PowerShell.Utility/Export-Csv.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 03/15/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/export-csv?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Export-Csv --- # Export-Csv ## SYNOPSIS Converts objects into a series of character-separated value (CSV) strings and saves the strings to a file. ## SYNTAX ### Delimiter (Default) ``` Export-Csv -InputObject <PSObject> [[-Path] <String>] [-LiteralPath <String>] [-Force] [-NoClobber] [-Encoding <Encoding>] [-Append] [[-Delimiter] <Char>] [-IncludeTypeInformation] [-NoTypeInformation] [-QuoteFields <String[]>] [-UseQuotes <QuoteKind>] [-NoHeader] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### UseCulture ``` Export-Csv -InputObject <PSObject> [[-Path] <String>] [-LiteralPath <String>] [-Force] [-NoClobber] [-Encoding <Encoding>] [-Append] [-UseCulture] [-IncludeTypeInformation] [-NoTypeInformation] [-QuoteFields <String[]>] [-UseQuotes <QuoteKind>] [-NoHeader] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Export-Csv` cmdlet creates a CSV file of the objects that you submit. Each object is a row that includes a character-separated list of the object's property values. You can use the `Export-Csv` cmdlet to create spreadsheets and share data with programs that accept CSV files as input. Do not format objects before sending them to the `Export-Csv` cmdlet. If `Export-Csv` receives formatted objects the CSV file contains the format properties rather than the object properties. To export only selected properties of an object, use the `Select-Object` cmdlet. ## EXAMPLES ### Example 1: Export process properties to a CSV file This example selects **Process** objects with specific properties, exports the objects to a CSV file. ```powershell Get-Process -Name WmiPrvSE | Select-Object -Property BasePriority,Id,SessionId,WorkingSet | Export-Csv -Path .\WmiData.csv -NoTypeInformation Import-Csv -Path .\WmiData.csv ``` ```Output BasePriority Id SessionId WorkingSet ------------ -- --------- ---------- 8 976 0 20267008 8 2292 0 36786176 8 3816 0 30351360 8 8604 0 15011840 8 10008 0 8830976 8 11764 0 14237696 8 54632 0 9502720 ``` The `Get-Process` cmdlet gets the **Process** objects. The **Name** parameter filters the output to include only the WmiPrvSE process objects. The process objects are sent down the pipeline to the `Select-Object` cmdlet. `Select-Object` uses the **Property** parameter to select a subset of process object properties. The process objects are sent down the pipeline to the `Export-Csv` cmdlet. `Export-Csv` converts the process objects to a series of CSV strings. The **Path** parameter specifies that the `WmiData.csv` file is saved in the current directory. The **NoTypeInformation** parameter removes the **#TYPE** information header from the CSV output and is not required in PowerShell 6. The `Import-Csv` cmdlet uses the **Path** parameter to display the file located in the current directory. ### Example 2: Export processes to a comma-delimited file This example gets **Process** objects and exports the objects to a CSV file. ```powershell Get-Process | Export-Csv -Path .\Processes.csv -NoTypeInformation Get-Content -Path .\Processes.csv ``` ```Output "Name","SI","Handles","VM","WS","PM","NPM","Path","Parent","Company","CPU","FileVersion", ... "ApplicationFrameHost","4","511","2203597099008","35364864","21979136","30048", ... ``` The `Get-Process` cmdlet gets **Process** objects. The process objects are sent down the pipeline to the `Export-Csv` cmdlet. `Export-Csv` converts the process objects to a series of CSV strings. The **Path** parameter specifies that the `Processes.csv` file is saved in the current directory. The **NoTypeInformation** parameter removes the **#TYPE** information header from the CSV output and is not required in PowerShell 6. The `Get-Content` cmdlet uses the **Path** parameter to display the file located in the current directory. ### Example 3: Export processes to a semicolon delimited file This example gets **Process** objects and exports the objects to a file with a semicolon delimiter. ```powershell Get-Process | Export-Csv -Path .\Processes.csv -Delimiter ';' -NoTypeInformation Get-Content -Path .\Processes.csv ``` ```Output "Name";"SI";"Handles";"VM";"WS";"PM";"NPM";"Path";"Parent";"Company";"CPU";"FileVersion"; ... "ApplicationFrameHost";"4";"509";"2203595321344";"34807808";"21770240";"29504"; ... ``` The `Get-Process` cmdlet gets **Process** objects. The process objects are sent down the pipeline to the `Export-Csv` cmdlet. `Export-Csv` converts the process objects to a series of CSV strings. The **Path** parameter specifies that the `Processes.csv` file is saved in the current directory. The **Delimiter** parameter specifies a semicolon to separate the string values. The **NoTypeInformation** parameter removes the **#TYPE** information header from the CSV output and is not required in PowerShell 6. The `Get-Content` cmdlet uses the **Path** parameter to display the file located in the current directory. ### Example 4: Export processes using the current culture's list separator This example gets **Process** objects and exports the objects to a file. The delimiter is the current culture's list separator. ```powershell (Get-Culture).TextInfo.ListSeparator Get-Process | Export-Csv -Path .\Processes.csv -UseCulture -NoTypeInformation Get-Content -Path .\Processes.csv ``` ```Output "Name","SI","Handles","VM","WS","PM","NPM","Path","Parent","Company","CPU","FileVersion", ... "ApplicationFrameHost","4","511","2203597099008","35364864","21979136","30048", ... ``` The `Get-Culture` cmdlet uses the nested properties **TextInfo** and **ListSeparator** and displays the current culture's default list separator. The `Get-Process` cmdlet gets **Process** objects. The process objects are sent down the pipeline to the `Export-Csv` cmdlet. `Export-Csv` converts the process objects to a series of CSV strings. The **Path** parameter specifies that the `Processes.csv` file is saved in the current directory. The **UseCulture** parameter uses the current culture's default list separator as the delimiter. The **NoTypeInformation** parameter removes the **#TYPE** information header from the CSV output and is not required in PowerShell 6. The `Get-Content` cmdlet uses the **Path** parameter to display the file located in the current directory. ### Example 5: Export processes with type information This example explains how to include the **#TYPE** header information in a CSV file. The **#TYPE** header is the default in versions prior to PowerShell 6.0. ```powershell Get-Process | Export-Csv -Path .\Processes.csv -IncludeTypeInformation Get-Content -Path .\Processes.csv ``` ```Output #TYPE System.Diagnostics.Process "Name","SI","Handles","VM","WS","PM","NPM","Path","Company","CPU","FileVersion", ... "ApplicationFrameHost","4","507","2203595001856","35139584","20934656","29504", ... ``` The `Get-Process` cmdlet gets **Process** objects. The process objects are sent down the pipeline to the `Export-Csv` cmdlet. `Export-Csv` converts the process objects to a series of CSV strings. The **Path** parameter specifies that the `Processes.csv` file is saved in the current directory. The **IncludeTypeInformation** includes the **#TYPE** information header in the CSV output. The `Get-Content` cmdlet uses the **Path** parameter to display the file located in the current directory. ### Example 6: Export and append objects to a CSV file This example describes how to export objects to a CSV file and use the **Append** parameter to add objects to an existing file. ```powershell $AppService = (Get-Service -DisplayName *Application* | Select-Object -Property DisplayName, Status) $AppService | Export-Csv -Path .\Services.Csv -NoTypeInformation Get-Content -Path .\Services.Csv $WinService = (Get-Service -DisplayName *Windows* | Select-Object -Property DisplayName, Status) $WinService | Export-Csv -Path .\Services.csv -NoTypeInformation -Append Get-Content -Path .\Services.Csv ``` ```Output "DisplayName","Status" "Application Layer Gateway Service","Stopped" "Application Identity","Running" "Windows Audio Endpoint Builder","Running" "Windows Audio","Running" "Windows Event Log","Running" ``` The `Get-Service` cmdlet gets service objects. The **DisplayName** parameter returns services that contain the word Application. The service objects are sent down the pipeline to the `Select-Object` cmdlet. `Select-Object` uses the **Property** parameter to specify the **DisplayName** and **Status** properties. The `$AppService` variable stores the objects. The `$AppService` objects are sent down the pipeline to the `Export-Csv` cmdlet. `Export-Csv` converts the service objects to a series of CSV strings. The **Path** parameter specifies that the `Services.csv` file is saved in the current directory. The **NoTypeInformation** parameter removes the **#TYPE** information header from the CSV output and is not required in PowerShell 6. The `Get-Content` cmdlet uses the **Path** parameter to display the file located in the current directory. The `Get-Service` and `Select-Object` cmdlets are repeated for services that contain the word Windows. The `$WinService` variable stores the service objects. The `Export-Csv` cmdlet uses the **Append** parameter to specify that the `$WinService` objects are added to the existing `Services.csv` file. The `Get-Content` cmdlet is repeated to display the updated file that includes the appended data. ### Example 7: Format cmdlet within a pipeline creates unexpected results This example shows why it is important not to use a format cmdlet within a pipeline. When unexpected output is received, troubleshoot the pipeline syntax. ```powershell Get-Date | Select-Object -Property DateTime, Day, DayOfWeek, DayOfYear | Export-Csv -Path .\DateTime.csv -NoTypeInformation Get-Content -Path .\DateTime.csv ``` ```Output "DateTime","Day","DayOfWeek","DayOfYear" "Wednesday, January 2, 2019 14:59:34","2","Wednesday","2" ``` ```powershell Get-Date | Format-Table -Property DateTime, Day, DayOfWeek, DayOfYear | Export-Csv -Path .\FTDateTime.csv -NoTypeInformation Get-Content -Path .\FTDateTime.csv ``` ```Output "ClassId2e4f51ef21dd47e99d3c952918aff9cd","pageHeaderEntry","pageFooterEntry","autosizeInfo", ... "033ecb2bc07a4d43b5ef94ed5a35d280",,,,"Microsoft.PowerShell.Commands.Internal.Format. ... "9e210fe47d09416682b841769c78b8a3",,,,, "27c87ef9bbda4f709f6b4002fa4af63c",,,,, "4ec4f0187cb04f4cb6973460dfe252df",,,,, "cf522b78d86c486691226b40aa69e95c",,,,, ``` The `Get-Date` cmdlet gets the **DateTime** object. The object is sent down the pipeline to the `Select-Object` cmdlet. `Select-Object` uses the **Property** parameter to select a subset of object properties. The object is sent down the pipeline to the `Export-Csv` cmdlet. `Export-Csv` converts the object to a CSV format. The **Path** parameter specifies that the `DateTime.csv` file is saved in the current directory. The **NoTypeInformation** parameter removes the **#TYPE** information header from the CSV output and is not required in PowerShell 6. The `Get-Content` cmdlet uses the **Path** parameter to display the CSV file located in the current directory. When the `Format-Table` cmdlet is used within the pipeline to select properties unexpected results are received. `Format-Table` sends table format objects down the pipeline to the `Export-Csv` cmdlet rather than the **DateTime** object. `Export-Csv` converts the table format objects to a series of CSV strings. The `Get-Content` cmdlet displays the CSV file which contains the table format objects. ### Example 8: Using the Force parameter to overwrite read-only files This example creates an empty, read-only file and uses the **Force** parameter to update the file. ```powershell New-Item -Path .\ReadOnly.csv -ItemType File Set-ItemProperty -Path .\ReadOnly.csv -Name IsReadOnly -Value $true Get-Process | Export-Csv -Path .\ReadOnly.csv -NoTypeInformation ``` ```Output Export-Csv : Access to the path 'C:\ReadOnly.csv' is denied. At line:1 char:15 + Get-Process | Export-Csv -Path .\ReadOnly.csv -NoTypeInformation + ~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : OpenError: (:) [Export-Csv], UnauthorizedAccessException + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.ExportCsvCommand ``` ```powershell Get-Process | Export-Csv -Path .\ReadOnly.csv -NoTypeInformation -Force Get-Content -Path .\ReadOnly.csv ``` ```Output "Name";"SI";"Handles";"VM";"WS";"PM";"NPM";"Path";"Parent";"Company";"CPU";"FileVersion"; ... "ApplicationFrameHost";"4";"509";"2203595321344";"34807808";"21770240";"29504"; ... ``` The `New-Item` cmdlet uses the **Path** and **ItemType** parameters to create the `ReadOnly.csv` file in the current directory. The `Set-ItemProperty` cmdlet uses the **Name** and **Value** parameters to change the file's **IsReadOnly** property to true. The `Get-Process` cmdlet gets **Process** objects. The process objects are sent down the pipeline to the `Export-Csv` cmdlet. `Export-Csv` converts the process objects to a series of CSV strings. The **Path** parameter specifies that the `ReadOnly.csv` file is saved in the current directory. The **NoTypeInformation** parameter removes the **#TYPE** information header from the CSV output and is not required in PowerShell 6. The output shows that the file is not written because access is denied. The **Force** parameter is added to the `Export-Csv` cmdlet to force the export to write to the file. The `Get-Content` cmdlet uses the **Path** parameter to display the file located in the current directory. ### Example 9: Using the Force parameter with Append This example shows how to use the **Force** and **Append** parameters. When these parameters are combined, mismatched object properties can be written to a CSV file. ```powershell $Content = [pscustomobject]@{Name = 'PowerShell'; Version = '7.0'} $Content | Export-Csv -Path .\ParmFile.csv -NoTypeInformation $AdditionalContent = [pscustomobject]@{Name = 'Windows PowerShell'; Edition = 'Desktop'} $AdditionalContent | Export-Csv -Path .\ParmFile.csv -NoTypeInformation -Append ``` ```Output Export-Csv : Cannot append CSV content to the following file: ParmFile.csv. The appended object does not have a property that corresponds to the following column: Version. To continue with mismatched properties, add the -Force parameter, and then retry the command. At line:1 char:22 + $AdditionalContent | Export-Csv -Path .\ParmFile.csv -NoTypeInformation -Append + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidData: (Version:String) [Export-Csv], InvalidOperationException + FullyQualifiedErrorId : CannotAppendCsvWithMismatchedPropertyNames,Microsoft.PowerShell. ... ``` ```powershell $AdditionalContent | Export-Csv -Path .\ParmFile.csv -NoTypeInformation -Append -Force Import-Csv -Path .\ParmFile.csv ``` ```Output Name Version ---- ------- PowerShell 7.0 Windows PowerShell ``` An expression creates the **PSCustomObject** with **Name** and **Version** properties. The values are stored in the `$Content` variable. The `$Content` variable is sent down the pipeline to the `Export-Csv` cmdlet. `Export-Csv` uses the **Path** parameter and saves the `ParmFile.csv` file in the current directory. The **NoTypeInformation** parameter removes the **#TYPE** information header from the CSV output and is not required in PowerShell 6. Another expression creates a **PSCustomObject** with the **Name** and **Edition** properties. The values are stored in the `$AdditionalContent` variable. The `$AdditionalContent` variable is sent down the pipeline to the `Export-Csv` cmdlet. The **Append** parameter is used to add the data to the file. The append fails because there is a property name mismatch between **Version** and **Edition**. The `Export-Csv` cmdlet **Force** parameter is used to force the export to write to the file. The **Edition** property is discarded. The `Import-Csv` cmdlet uses the **Path** parameter to display the file located in the current directory. ### Example 10: Export to CSV with quotes around two columns This example converts a **DateTime** object to a CSV string. ```powershell Get-Date | Export-Csv -QuoteFields "DateTime","Date" -Path .\FTDateTime.csv Get-Content -Path .\FTDateTime.csv ``` ```Output DisplayHint,"DateTime","Date",Day,DayOfWeek,DayOfYear,Hour,Kind,Millisecond,Minute,Month,Second,Ticks,TimeOfDay,Year DateTime,"Thursday, August 22, 2019 11:27:34 AM","8/22/2019 12:00:00 AM",22,Thursday,234,11,Local,569,27,8,34,637020700545699784,11:27:34.5699784,2019 ``` ### Example 11: Export to CSV with quotes only when needed This example converts a **DateTime** object to a CSV string. ```powershell Get-Date | Export-Csv -UseQuotes AsNeeded -Path .\FTDateTime.csv Get-Content -Path .\FTDateTime.csv ``` ```Output DisplayHint,DateTime,Date,Day,DayOfWeek,DayOfYear,Hour,Kind,Millisecond,Minute,Month,Second,Ticks,TimeOfDay,Year DateTime,"Thursday, August 22, 2019 11:31:00 AM",8/22/2019 12:00:00 AM,22,Thursday,234,11,Local,713,31,8,0,637020702607132640,11:31:00.7132640,2019 ``` ### Example 12: Convert hashtables to CSV In PowerShell 7.2 and above, when you export hashtables to CSV, the keys of the first hashtable are serialized and used as headers in the csv file output. ```powershell $person1 = @{ Name = 'John Smith' Number = 1 } $person2 = @{ Name = 'Jane Smith' Number = 1 } $allPeople = $person1, $person2 $allPeople | Export-Csv -Path .\People.csv Get-Content -Path .\People.csv ``` ```Output "Name","Number" "John Smith","1" "Jane Smith","2" ``` ### Example 13: Converting hashtables to CSV with additional properties In PowerShell 7.2 and above, when you export a hashtable that has additional properties added with `Add-Member` or `Select-Object` the additional properties are also added as a header in the CSV file. ```powershell $allPeople | Add-Member -Name ExtraProp -Value 42 -MemberType NoteProperty $allPeople | Export-Csv -Path .\People.csv Get-Content -Path .\People.csv ``` ```Output "Name","Number","ExtraProp" "John Smith","1","42" "Jane Smith","2","42" ``` Each hashtable has a property named `ExtraProp` added by `Add-Member` and then exported to CSV. You can see `ExtraProp` is now a header in the CSV file output. If an added property has the _same_ name as a key from the hashtable, the key takes precedence and only the key is exported to CSV. ## PARAMETERS ### -Append Use this parameter so that `Export-Csv` adds CSV output to the end of the specified file. Without this parameter, `Export-Csv` replaces the file contents without warning. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Delimiter Specifies a delimiter to separate the property values. The default is a comma (`,`). Enter a character, such as a colon (`:`). To specify a semicolon (`;`), enclose it in quotation marks. ```yaml Type: System.Char Parameter Sets: Delimiter Aliases: Required: False Position: 1 Default value: comma (,) Accept pipeline input: False Accept wildcard characters: False ``` ### -Encoding Specifies the encoding for the exported CSV file. The default value is `utf8NoBOM`. The acceptable values for this parameter are as follows: - `ascii`: Uses the encoding for the ASCII (7-bit) character set. - `ansi`: Uses the encoding for the for the current culture's ANSI code page. This option was added - `bigendianunicode`: Encodes in UTF-16 format using the big-endian byte order. - `bigendianutf32`: Encodes in UTF-32 format using the big-endian byte order. - `oem`: Uses the default encoding for MS-DOS and console programs. - `unicode`: Encodes in UTF-16 format using the little-endian byte order. - `utf7`: Encodes in UTF-7 format. - `utf8`: Encodes in UTF-8 format. - `utf8BOM`: Encodes in UTF-8 format with Byte Order Mark (BOM) - `utf8NoBOM`: Encodes in UTF-8 format without Byte Order Mark (BOM) - `utf32`: Encodes in UTF-32 format. Beginning with PowerShell 6.2, the **Encoding** parameter also allows numeric IDs of registered code pages (like `-Encoding 1251`) or string names of registered code pages (like `-Encoding "windows-1251"`). For more information, see the .NET documentation for [Encoding.CodePage](/dotnet/api/system.text.encoding.codepage?view=netcore-2.2). Starting with PowerShell 7.4, you can use the `Ansi` value for the **Encoding** parameter to pass the numeric ID for the current culture's ANSI code page without having to specify it manually. > [!NOTE] > **UTF-7*** is no longer recommended to use. As of PowerShell 7.1, a warning is written if you > specify `utf7` for the **Encoding** parameter. ```yaml Type: System.Text.Encoding Parameter Sets: (All) Aliases: Accepted values: ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 Required: False Position: Named Default value: UTF8NoBOM Accept pipeline input: False Accept wildcard characters: False ``` ### -Force This parameter allows `Export-Csv` to overwrite files with the **Read Only** attribute. When **Force** and **Append** parameters are combined, objects that contain mismatched properties can be written to a CSV file. Only the properties that match are written to the file. The mismatched properties are discarded. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -IncludeTypeInformation When this parameter is used the first line of the CSV output contains `#TYPE` followed by the fully qualified name of the object type. For example, `#TYPE System.Diagnostics.Process`. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: ITI Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects to export as CSV strings. Enter a variable that contains the objects or type a command or expression that gets the objects. You can also pipe objects to `Export-Csv`. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to the CSV output file. Unlike **Path**, the value of the **LiteralPath** parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, use single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String Parameter Sets: (All) Aliases: PSPath, LP Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NoClobber Use this parameter so that `Export-Csv` does not overwrite an existing file. By default, if the file exists in the specified path, `Export-Csv` overwrites the file without warning. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: NoOverwrite Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -NoHeader When this parameter is used, the cmdlet doesn't write a header row containing the column names to the output. This parameter was added in PowerShell 7.4. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -NoTypeInformation Removes the `#TYPE` information header from the output. This parameter became the default in PowerShell 6.0 and is included for backwards compatibility. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: NTI Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Path A required parameter that specifies the location to save the CSV output file. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -QuoteFields Specifies the names of the columns that should be quoted. When this parameter is used, only the specified columns are quoted. This parameter was added in PowerShell 7.0. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: QF Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseCulture Uses the list separator for the current culture as the item delimiter. To find the list separator for a culture, use the following command: `(Get-Culture).TextInfo.ListSeparator`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: UseCulture Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -UseQuotes Specifies when quotes are used in the CSV files. Possible values are: - Never - don't quote anything - Always - quote everything (default behavior) - AsNeeded - only quote fields that contain a delimiter character, double-quote, or newline character This parameter was added in PowerShell 7.0. ```yaml Type: Microsoft.PowerShell.Commands.BaseCsvWritingCommand+QuoteKind Parameter Sets: (All) Aliases: UQ Required: False Position: Named Default value: Always Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Prevents the cmdlet from being processed or making changes. The output shows what would happen if the cmdlet were run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object with an Extended Type System (ETS) adapter to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Export-Csv`: - All platforms: - `epcsv` The `Export-Csv` cmdlet converts the objects that you submit into a series of CSV strings and saves them in the specified text file. You can use `Export-Csv -IncludeTypeInformation` to save objects in a CSV file and then use the `Import-Csv` cmdlet to create objects from the text in the CSV file. In the CSV file, each object is represented by a character-separated list of the property values of the object. The property values are converted to strings using the **ToString()** method. The strings are represented by the property value name. `Export-Csv -IncludeTypeInformation` does not export the methods of the object. The CSV strings are output as follows: - If **IncludeTypeInformation** is used, the first string contains the **#TYPE** information header followed by the object type's fully qualified name. For example, **#TYPE System.Diagnostics.Process**. - If **IncludeTypeInformation** is not used the first string includes the column headers. The headers contain the first object's property names as a character-separated list. - The remaining strings contain character-separated lists of each object's property values. Beginning with PowerShell 6.0 the default behavior of `Export-Csv` is to not include the **#TYPE** information in the CSV and **NoTypeInformation** is implied. **IncludeTypeInformation** can be used to include the **#TYPE** Information and emulate the default behavior of `Export-Csv` prior to PowerShell 6.0. When you submit multiple objects to `Export-Csv`, `Export-Csv` organizes the file based on the properties of the first object that you submit. If the remaining objects do not have one of the specified properties, the property value of that object is null, as represented by two consecutive commas. If the remaining objects have additional properties, those property values are not included in the file. You can use the `Import-Csv` cmdlet to recreate objects from the CSV strings in the files. The resulting objects are CSV versions of the original objects that consist of string representations of the property values and no methods. The `ConvertTo-Csv` and `ConvertFrom-Csv` cmdlets convert objects to CSV strings and from CSV strings. `Export-Csv` is the same as `ConvertTo-Csv`, except that it saves the CSV strings in a file. ## RELATED LINKS [ConvertFrom-Csv](ConvertFrom-Csv.md) [ConvertTo-Csv](ConvertTo-Csv.md) [Format-Table](Format-Table.md) [Import-Csv](Import-Csv.md) [Select-Object](Select-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Export-FormatData.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/export-formatdata?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Export-FormatData --- # Export-FormatData ## SYNOPSIS Saves formatting data from the current session in a formatting file. ## SYNTAX ### ByPath (Default) ``` Export-FormatData -InputObject <ExtendedTypeDefinition[]> -Path <String> [-Force] [-NoClobber] [-IncludeScriptBlock] [<CommonParameters>] ``` ### ByLiteralPath ``` Export-FormatData -InputObject <ExtendedTypeDefinition[]> -LiteralPath <String> [-Force] [-NoClobber] [-IncludeScriptBlock] [<CommonParameters>] ``` ## DESCRIPTION The `Export-FormatData` cmdlet creates PowerShell formatting files (`format.ps1xml`) from the formatting objects in the current session. It takes the **ExtendedTypeDefinition** objects that `Get-FormatData` returns and saves them in a file in XML format. PowerShell uses the data in formatting files (`format.ps1xml`) to generate the default display of Microsoft .NET Framework objects in the session. You can view and edit the formatting files and use the Update-FormatData cmdlet to add the formatting data to a session. For more information about formatting files in PowerShell, see [about_Format.ps1xml](../Microsoft.PowerShell.Core/About/about_Format.ps1xml.md). ## EXAMPLES ### Example 1: Export session format data ```powershell Get-FormatData -TypeName "*" | Export-FormatData -Path "AllFormat.ps1xml" -IncludeScriptBlock ``` This command exports all of the format data in the session to the `AllFormat.ps1xml` file. The command uses the `Get-FormatData` cmdlet to get the format data in the session. A value of `*` (all) for the **TypeName** parameter directs the cmdlet to get all of the data in the session. The command uses a pipeline operator (`|`) to send the format data from the `Get-FormatData` command to the `Export-FormatData` cmdlet, which exports the format data to the `AllFormat.ps1xml` file. The `Export-FormatData` command uses the **IncludeScriptBlock** parameter to include script blocks in the format data in the file. ### Example 2: Export format data for a type ```powershell $F = Get-FormatData -TypeName "helpinfoshort" Export-FormatData -InputObject $F -Path "C:\test\Help.format.ps1xml" -IncludeScriptBlock ``` These commands export the format data for the **HelpInfoShort** type to the `Help.format.ps1xml` file. The first command uses the `Get-FormatData` cmdlet to get the format data for the **HelpInfoShort** type, and it saves it in the `$F` variable. The second command uses the **InputObject** parameter of the `Export-FormatData` cmdlet to enter the format data saved in the `$F` variable. It also uses the **IncludeScriptBlock** parameter to include script blocks in the output. ### Example 3: Export format data without a script block ```powershell Get-FormatData -TypeName "System.Diagnostics.Process" | Export-FormatData -Path Process.format.ps1xml Update-FormatData -PrependPath ".\Process.format.ps1xml" Get-Process p* ``` ```Output Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 323 5600 powershell 336 3900 powershell_ise 138 4076 PresentationFontCache ``` This example shows the effect of omitting the **IncludeScriptBlock** parameter from an `Export-FormatData` command. The first command uses the `Get-FormatData` cmdlet to get the format data for the **System.Diagnostics.Process** object that the Get-Process cmdlet returns. The command uses a pipeline operator (`|`) to send the formatting data to the `Export-FormatData` cmdlet, which exports it to the `Process.format.ps1xml` file in the current directory. In this case, the `Export-FormatData` command does not use the **IncludeScriptBlock** parameter. The second command uses the `Update-FormatData` cmdlet to add the `Process.format.ps1xml` file to the current session. The command uses the **PrependPath** parameter to ensure that the formatting data for process objects in the Process.format.ps1xml file is found before the standard formatting data for process objects. The third command shows the effects of this change. The command uses the `Get-Process` cmdlet to get processes that have names that begin with P. The output shows that property values that are calculated by using script blocks are missing from the display. ## PARAMETERS ### -Force Forces the command to run without asking for user confirmation. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -IncludeScriptBlock Indicates whether script blocks in the format data are exported. Because script blocks contain code and can be used maliciously, they are not exported by default. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the format data objects to be exported. Enter a variable that contains the objects or a command that gets the objects, such as a `Get-FormatData` command. You can also pipe the objects from `Get-FormatData` to `Export-FormatData`. ```yaml Type: System.Management.Automation.ExtendedTypeDefinition[] Parameter Sets: (All) Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -LiteralPath Specifies a location for the output file. Unlike the **Path** parameter, the value of **LiteralPath** is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String Parameter Sets: ByLiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NoClobber Indicates that the cmdlet does not overwrite existing files. By default, `Export-FormatData` overwrites files without warning unless the file has the read-only attribute. To direct `Export-FormatData` to overwrite read-only files, use the **Force** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: NoOverwrite Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies a location for the output file. Enter a path (optional) and file name with a `format.ps1xml` file name extension. If you omit the path, `Export-FormatData` creates the file in the current directory. If you use a file name extension other than `.ps1xml`, the `Update-FormatData` cmdlet will not recognize the file. If you specify an existing file, `Export-FormatData` overwrites the file without warning, unless the file has the read-only attribute. To overwrite a read-only file, use the **Force** parameter. To prevent files from being overwritten, use the **NoClobber** parameter. ```yaml Type: System.String Parameter Sets: ByPath Aliases: FilePath Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.ExtendedTypeDefinition You can pipe **ExtendedTypeDefinition** objects from `Get-FormatData` to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. It generates a file and saves it in the specified path. ## NOTES - To use any formatting file, including an exported formatting file, the execution policy for the session must allow scripts and configuration files to run. For more information, see [about_Execution_Policies](../Microsoft.PowerShell.Core/About/about_Execution_Policies.md). ## RELATED LINKS [Get-FormatData](Get-FormatData.md) [Update-FormatData](Update-FormatData.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Export-PSSession.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 03/15/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/export-pssession?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Export-PSSession --- # Export-PSSession ## SYNOPSIS Exports commands from another session and saves them in a PowerShell module. ## SYNTAX ### All ``` Export-PSSession [-OutputModule] <String> [-Force] [-Encoding <Encoding>] [[-CommandName] <String[]>] [-AllowClobber] [-ArgumentList <Object[]>] [-CommandType <CommandTypes>] [-Module <String[]>] [-FullyQualifiedModule <ModuleSpecification[]>] [[-FormatTypeName] <String[]>] [-Certificate <X509Certificate2>] [-Session] <PSSession> [<CommonParameters>] ``` ## DESCRIPTION The `Export-PSSession` cmdlet gets cmdlets, functions, aliases, and other command types from another PowerShell session (PSSession) on a local or remote computer and saves them in a PowerShell module. To add the commands from the module to the current session, use the `Import-Module` cmdlet. Unlike `Import-PSSession`, which imports commands from another PSSession into the current session, `Export-PSSession` saves the commands in a module. The commands are not imported into the current session. To export commands, use the `New-PSSession` cmdlet to create a PSSession that has the commands that you want to export. Then use the `Export-PSSession` cmdlet to export the commands. To prevent command name conflicts, the default for `Export-PSSession` is to export all commands, except for commands that exist in the current session. You can use the **CommandName** parameter to specify the commands to export. The `Export-PSSession` cmdlet uses the implicit remoting feature of PowerShell. When you import commands into the current session, they run implicitly in the original session or in a similar session on the originating computer. ## EXAMPLES ### Example 1: Export commands from a PSSession This example creates a new PSSession from the local computer to the Server01 computer. All of the commands, except those that exist in the current session, are exported to the module named Server01 on the local computer. The export includes the formatting data for the commands. ```powershell $S = New-PSSession -ComputerName Server01 Export-PSSession -Session $S -OutputModule Server01 ``` The `New-PSSession` command creates a PSSession on the Server01 computer. The PSSession is stored in the `$S` variable. The `Export-PSSession` command exports the `$S` variable's commands and formatting data into the Server01 module. ### Example 2: Export the Get and Set commands This example exports all of the `Get` and `Set` commands from a server. ```powershell $S = New-PSSession -ConnectionUri https://exchange.microsoft.com/mailbox -Credential exchangeadmin01@hotmail.com -Authentication Negotiate Export-PSSession -Session $S -Module exch* -CommandName Get-*, Set-* -FormatTypeName * -OutputModule $PSHOME\Modules\Exchange -Encoding ascii ``` These commands export the `Get` and `Set` commands from a Microsoft Exchange Server snap-in on a remote computer to an Exchange module in the `$PSHOME\Modules` directory on the local computer. Placing the module in the `$PSHOME\Modules` directory makes it accessible to all users of the computer. ### Example 3: Export commands from a remote computer This example exports cmdlets from a PSSession on a remote computer and saves them in a module on the local computer. The cmdlets from the module are added to the current session so that they can be used. ```powershell $S = New-PSSession -ComputerName Server01 -Credential Server01\User01 Export-PSSession -Session $S -OutputModule TestCmdlets -Type Cmdlet -CommandName *test* -FormatTypeName * Remove-PSSession $S Import-Module TestCmdlets Get-Help Test* Test-Files ``` The `New-PSSession` command creates a PSSession on the Server01 computer and saves it in the `$S` variable. The `Export-PSSession` command exports the cmdlets whose names begin with Test from the PSSession in `$S` to the TestCmdlets module on the local computer. The `Remove-PSSession` cmdlet deletes the PSSession in `$S` from the current session. This command shows that the PSSession need not be active to use the commands that were imported from the session. The `Import-Module` cmdlet adds the cmdlets in the TestCmdlets module to the current session. The command can be run in any session at any time. The `Get-Help` cmdlet gets help for cmdlets whose names begin with Test. After the commands in a module are added to the current session, you can use the `Get-Help` and `Get-Command` cmdlets to learn about the imported commands. The `Test-Files` cmdlet was exported from the Server01 computer and added to the session. The `Test-Files` cmdlet runs in a remote session on the computer from which the command was imported. PowerShell creates a session from information that is stored in the TestCmdlets module. ### Example 4: Export and clobber commands in the current session This example exports commands that are stored in a variable into the current session. ```powershell Export-PSSession -Session $S -AllowClobber -OutputModule AllCommands ``` This `Export-PSSession` command exports all commands and all formatting data from the PSSession in the `$S` variable into the current session. The **AllowClobber** parameter includes commands with the same names as commands in the current session. ### Example 5: Export commands from a closed PSSession This example shows how to run the exported commands with special options when the PSSession that created the exported commands is closed. If the original remote session is closed when a module is imported, the module will use any open remote session that connects to the originating computer. If there is no current session to the originating computer, the module will reestablish a session. To run exported commands with special options in a remote session, you must create a remote session with those options before you import the module. Use the `New-PSSession` cmdlet with the **SessionOption** parameter ```powershell $Options = New-PSSessionOption -NoMachineProfile $S = New-PSSession -ComputerName Server01 -SessionOption $Options Export-PSSession -Session $S -OutputModule Server01 Remove-PSSession $S New-PSSession -ComputerName Server01 -SessionOption $Options Import-Module Server01 ``` The `New-PSSessionOption` cmdlet creates a **PSSessionOption** object, and it saves the object in the `$Options` variable. The `New-PSSession` command creates a PSSession on the Server01 computer. The **SessionOption** parameter uses the object stored in `$Options`. The session is stored in the `$S` variable. The `Export-PSSession` cmdlet exports commands from the PSSession in `$S` to the Server01 module. The `Remove-PSSession` cmdlet deletes the PSSession in the `$S` variable. The `New-PSSession` cmdlet creates a new PSSession that connects to the Server01 computer. The **SessionOption** parameter uses the object stored in `$Options`. The `Import-Module` cmdlet imports the commands from the Server01 module. The commands in the module are run in the PSSession on the Server01 computer. ## PARAMETERS ### -AllowClobber Exports the specified commands, even if they have the same names as commands in the current session. If you export a command with the same name as a command in the current session, the exported command hides or replaces the original commands. For more information, see [about_Command_Precedence](../Microsoft.PowerShell.Core/About/about_Command_Precedence.md). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ArgumentList Exports the variant of the command that results from using the specified arguments (parameter values). For example, to export the variant of the `Get-Item` command in the certificate (Cert:) drive in the PSSession in `$S`, type `Export-PSSession -Session $S -Command Get-Item -ArgumentList Cert:`. ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Args Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Certificate Specifies the client certificate that is used to sign the format files (*.Format.ps1xml) or script module files (`.psm1`) in the module that `Export-PSSession` creates. Enter a variable that contains a certificate or a command or expression that gets the certificate. To find a certificate, use the `Get-PfxCertificate` cmdlet or use the `Get-ChildItem` cmdlet in the Certificate (Cert:) drive. If the certificate is not valid or does not have sufficient authority, the command fails. ```yaml Type: System.Security.Cryptography.X509Certificates.X509Certificate2 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CommandName Exports only the commands with the specified names or name patterns. Wildcards are permitted. Use **CommandName** or its alias, **Name**. By default, `Export-PSSession` exports all commands from the PSSession except for commands that have the same names as commands in the current session. This prevents commands from being hidden or replaced by commands in the current session. To export all commands, even those that hide or replace other commands, use the **AllowClobber** parameter. If you use the **CommandName** parameter, the formatting files for the commands are not exported unless you use the **FormatTypeName** parameter. Similarly, if you use the **FormatTypeName** parameter, no commands are exported unless you use the **CommandName** parameter. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Name Required: False Position: 2 Default value: All commands in the session. Accept pipeline input: False Accept wildcard characters: True ``` ### -CommandType Exports only the specified types of command objects. Use **CommandType** or its alias, **Type**. The acceptable values for this parameter are as follows: - `Alias`: All PowerShell aliases in the current session. - `All`: All command types. It is the equivalent of `Get-Command -Name *`. - `Application`: All files other than PowerShell files in paths listed in the PATH environment variable (`$Env:PATH`), including .txt, .exe, and .dll files. - `Cmdlet`: The cmdlets in the current session. Cmdlet is the default. - `Configuration`: A PowerShell configuration. For more information, see [about_Session_Configurations](../Microsoft.PowerShell.Core/About/about_Session_Configurations.md). - `ExternalScript`: All `.ps1` files in the paths listed in the PATH environment variable (`$Env:PATH`). - `Filter` and `Function`: All PowerShell functions. - `Script` Script blocks in the current session. - `Workflow` A PowerShell workflow. For more information, see [about_Workflows](/powershell/module/PSWorkflow/About/about_Workflows). These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **CommandType** parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. ```yaml Type: System.Management.Automation.CommandTypes Parameter Sets: (All) Aliases: Type Accepted values: Alias, All, Application, Cmdlet, Configuration, ExternalScript, Filter, Function, Script, Workflow Required: False Position: Named Default value: All commands in the session. Accept pipeline input: False Accept wildcard characters: False ``` ### -Encoding Specifies the type of encoding for the target file. The default value is `utf8NoBOM`. The acceptable values for this parameter are as follows: - `ascii`: Uses the encoding for the ASCII (7-bit) character set. - `ansi`: Uses the encoding for the for the current culture's ANSI code page. This option was added in PowerShell 7.4. - `bigendianunicode`: Encodes in UTF-16 format using the big-endian byte order. - `bigendianutf32`: Encodes in UTF-32 format using the big-endian byte order. - `oem`: Uses the default encoding for MS-DOS and console programs. - `unicode`: Encodes in UTF-16 format using the little-endian byte order. - `utf7`: Encodes in UTF-7 format. - `utf8`: Encodes in UTF-8 format. - `utf8BOM`: Encodes in UTF-8 format with Byte Order Mark (BOM) - `utf8NoBOM`: Encodes in UTF-8 format without Byte Order Mark (BOM) - `utf32`: Encodes in UTF-32 format. Beginning with PowerShell 6.2, the **Encoding** parameter also allows numeric IDs of registered code pages (like `-Encoding 1251`) or string names of registered code pages (like `-Encoding "windows-1251"`). For more information, see the .NET documentation for [Encoding.CodePage](/dotnet/api/system.text.encoding.codepage?view=netcore-2.2). Starting with PowerShell 7.4, you can use the `Ansi` value for the **Encoding** parameter to pass the numeric ID for the current culture's ANSI code page without having to specify it manually. > [!NOTE] > **UTF-7*** is no longer recommended to use. As of PowerShell 7.1, a warning is written if you > specify `utf7` for the **Encoding** parameter. ```yaml Type: System.Text.Encoding Parameter Sets: (All) Aliases: Accepted values: ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 Required: False Position: Named Default value: UTF8NoBOM Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Overwrites one or more existing output files, even if the file has the read-only attribute. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FormatTypeName Exports formatting instructions only for the specified Microsoft .NET Framework types. Enter the type names. By default, `Export-PSSession` exports formatting instructions for all .NET Framework types that are not in the **System.Management.Automation** namespace. The value of this parameter must be the name of a type that is returned by a `Get-FormatData` command in the session from which the commands are being imported. To get all of the formatting data in the remote session, type `*`. If you use the **FormatTypeName** parameter, no commands are exported unless you use the **CommandName** parameter. If you use the **CommandName** parameter, the formatting files for the commands are not exported unless you use the **FormatTypeName** parameter. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FullyQualifiedModule The value can be a module name, a full module specification, or a path to a module file. When the value is a path, the path can be fully qualified or relative. A relative path is resolved relative to the script that contains the using statement. When the value is a name or module specification, PowerShell searches the **PSModulePath** for the specified module. A module specification is a hashtable that has the following keys. - `ModuleName` - **Required** Specifies the module name. - `GUID` - **Optional** Specifies the GUID of the module. - It's also **Required** to specify at least one of the three below keys. - `ModuleVersion` - Specifies a minimum acceptable version of the module. - `MaximumVersion` - Specifies the maximum acceptable version of the module. - `RequiredVersion` - Specifies an exact, required version of the module. This can't be used with the other Version keys. You can't specify the **FullyQualifiedModule** parameter in the same command as a **Module** parameter. the two parameters are mutually exclusive. ```yaml Type: Microsoft.PowerShell.Commands.ModuleSpecification[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Module Exports only the commands in the specified PowerShell snap-ins and modules. Enter the snap-in and module names. Wildcards are not permitted. For more information, see `Import-Module` and [about_PSSnapins](/powershell/module/microsoft.powershell.core/about/about_pssnapins?view=powershell-5.1). ```yaml Type: System.String[] Parameter Sets: (All) Aliases: PSSnapin Required: False Position: Named Default value: All commands in the session. Accept pipeline input: False Accept wildcard characters: False ``` ### -OutputModule Specifies an optional path and name for the module created by `Export-PSSession`. The default path is `$HOME\Documents\WindowsPowerShell\Modules`. This parameter is required. If the module subdirectory or any of the files that `Export-PSSession` creates already exist, the command fails. To overwrite existing files, use the **Force** parameter. ```yaml Type: System.String Parameter Sets: (All) Aliases: PSPath, ModuleName Required: True Position: 1 Default value: $HOME\Documents\WindowsPowerShell\Modules Accept pipeline input: False Accept wildcard characters: False ``` ### -Session Specifies the PSSession from which the commands are exported. Enter a variable that contains a session object or a command that gets a session object, such as a `Get-PSSession` command. This parameter is required. ```yaml Type: System.Management.Automation.Runspaces.PSSession Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.IO.FileInfo This cmdlet returns a list of files that comprise the module that it created. ## NOTES `Export-PSSession` relies on the PowerShell remoting infrastructure. To use this cmdlet, the computer must be configured for remoting. For more information, see [about_Remote_Requirements](../Microsoft.PowerShell.Core/About/about_Remote_Requirements.md). You cannot use `Export-PSSession` to export a PowerShell provider. Exported commands run implicitly in the PSSession from which they were exported. The details of running the commands remotely are handled entirely by PowerShell. You can run the exported commands just as you would run local commands. `Export-ModuleMember` captures and saves information about the PSSession in the module that it exports. If the PSSession from which the commands were exported is closed when you import the module, and there are no active PSSessions to the same computer, the commands in the module attempt to recreate the PSSession. If attempts to recreate the PSSession fail, the exported commands will not run. The session information that `Export-ModuleMember` captures and saves in the module does not include session options, such as those that you specify in the `$PSSessionOption` preference variable or by using the **SessionOption** parameter of the `New-PSSession`, `Enter-PSSession`, or `Invoke-Command` cmdlets. If the original PSSession is closed when you import the module, the module will use another PSSession to the same computer, if one is available. To enable the imported commands to run in a correctly configured session, create a PSSession with the options that you want before you import the module. To find the commands to export, `Export-PSSession` uses the `Invoke-Command` cmdlet to run a `Get-Command` command in the PSSession. To get and save formatting data for the commands, it uses the `Get-FormatData` and `Export-FormatData` cmdlets. You might see error messages from `Invoke-Command`, `Get-Command`, `Get-FormatData`, and `Export-FormatData` when you run an `Export-PSSession` command. Also, `Export-PSSession` cannot export commands from a session that does not include the `Get-Command`, `Get-FormatData`, `Select-Object`, and `Get-Help` cmdlets. `Export-PSSession` uses the `Write-Progress` cmdlet to display the progress of the command. You might see the progress bar while the command is running. Exported commands have the same limitations as other remote commands, including the inability to start a program with a user interface, such as Notepad. Because PowerShell profiles are not run in PSSessions, the commands that a profile adds to a session are not available to `Export-PSSession`. To export commands from a profile, use an `Invoke-Command` command to run the profile in the PSSession manually before exporting commands. The module that `Export-PSSession` creates might include a formatting file, even if the command does not import formatting data. If the command does not import formatting data, any formatting files that are created will not contain formatting data. ## RELATED LINKS [about_Command_Precedence](../Microsoft.PowerShell.Core/About/about_Command_Precedence.md) [about_PSSessions](../Microsoft.PowerShell.Core/About/about_PSSessions.md) [about_PSSnapins](/powershell/module/microsoft.powershell.core/about/about_pssnapins?view=powershell-5.1) [about_Remote_Requirements](../Microsoft.PowerShell.Core/About/about_Remote_Requirements.md) [Import-Module](../Microsoft.PowerShell.Core/Import-Module.md) [Import-PSSession](Import-PSSession.md) [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md) [New-PSSession](../Microsoft.PowerShell.Core/New-PSSession.md) [New-PSSessionOption](../Microsoft.PowerShell.Core/New-PSSessionOption.md) [Remove-PSSession](../Microsoft.PowerShell.Core/Remove-PSSession.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Format-Custom.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/format-custom?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Format-Custom --- # Format-Custom ## SYNOPSIS Uses a customized view to format the output. ## SYNTAX ``` Format-Custom [[-Property] <Object[]>] [-Depth <Int32>] [-GroupBy <Object>] [-View <String>] [-ShowError] [-DisplayError] [-Force] [-Expand <String>] [-InputObject <PSObject>] [<CommonParameters>] ``` ## DESCRIPTION The `Format-Custom` cmdlet formats the output of a command as defined in an alternate view. `Format-Custom` is designed to display views that are not just tables or just lists. You can use the views defined in PowerShell, or you can create your own views in a new `format.ps1xml` file and use the `Update-FormatData` cmdlet to add them to PowerShell. ## EXAMPLES ### Example 1: Format output with a custom view ```powershell Get-Command Start-Transcript | Format-Custom -View MyView ``` This command formats information about the `Start-Transcript` cmdlet in the format defined by the MyView view, a custom view created by the user. To run this command successfully, you must first create a new PS1XML file, define the **MyView** view, and then use the `Update-FormatData` command to add the PS1XML file to PowerShell. ### Example 2: Format output with the default view ```powershell Get-Process Winlogon | Format-Custom ``` This command formats information about the **Winlogon** process in an alternate customized view. Because the command does not use the **View** parameter, `Format-Custom` uses a default custom view to format the data. ### Example 3: Troubleshooting format errors The following examples show of the results of adding the **DisplayError** or **ShowError** parameters with an expression. ```powershell PC /> Get-Date | Format-Custom DayOfWeek,{ $_ / $null } -DisplayError class DateTime { DayOfWeek = Friday $_ / $null = #ERR } PC /> Get-Date | Format-Custom DayOfWeek,{ $_ / $null } -ShowError class DateTime { DayOfWeek = Friday $_ / $null = } Failed to evaluate expression " $_ / $null ". + CategoryInfo : InvalidArgument: (12/21/2018 8:01:04 AM:PSObject) [], RuntimeException + FullyQualifiedErrorId : PSPropertyExpressionError ``` ## PARAMETERS ### -Depth Specifies the number of columns in the display. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DisplayError Displays errors at the command line. This parameter is rarely used, but can be used as a debugging aid when you are formatting expressions in a `Format-Custom` command, and the expressions do not appear to be working. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Expand Formats the collection object, as well as the objects in the collection. This parameter is designed to format objects that support the **System.Collections.ICollection** interface. The default value is **EnumOnly**. Valid values are: - EnumOnly: Displays the properties of the objects in the collection. - CoreOnly: Displays the properties of the collection object. - Both: Displays the properties of the collection object and the objects in the collection. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: CoreOnly, EnumOnly, Both Required: False Position: Named Default value: EnumOnly Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Directs the cmdlet to display all of the error information. Use with the **DisplayError** or **ShowError** parameters. By default, when an error object is written to the error or display streams, only some of the error information is displayed. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -GroupBy Formats the output in groups based on a shared property or value. Enter an expression or a property of the output. The **GroupBy** parameter expects that the objects are sorted. Use the `Sort-Object` cmdlet before using `Format-Custom` to group the objects. The value of the **GroupBy** parameter can be a new calculated property. The calculated property can be a script block or a hash table. Valid key-value pairs are: - Name (or Label) - `<string>` - Expression - `<string>` or `<script block>` - FormatString - `<string>` For more information, see [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects to be formatted. Enter a variable that contains the objects or type a command or expression that gets the objects. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Property Specifies the object properties that appear in the display and the order in which they appear. Wildcards are permitted. If you omit this parameter, the properties that appear in the display depend on the object being displayed. The parameter name **Property** is optional. You cannot use the **Property** and **View** parameters in the same command. The value of the **Property** parameter can be a new calculated property. The calculated property can be a script block or a hash table. Valid key-value pairs are: - Expression - `<string>` or `<script block>` - Depth - `<int32>` For more information, see [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -ShowError Sends errors through the pipeline. This parameter is rarely used, but can be used as a debugging aid when you are formatting expressions in a `Format-Custom` command, and the expressions do not appear to be working. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -View Specifies the name of an alternate format or view. If you omit this parameter, `Format-Custom` uses a default custom view. You cannot use the **Property** and **View** parameters in the same command. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.Internal.Format This cmdlet returns the format objects that represent the display. ## NOTES PowerShell includes the following aliases for `Format-Custom`: - All platforms: - `fc` `Format-Custom` is designed to display views that are not just tables or just lists. To display an alternate table view, use `Format-Table`. To display an alternate list view, use `Format-List`. The **GroupBy** parameter assumes that the objects are sorted. Before using `Format-Custom` to group the objects, use `Sort-Object` to sort them. ## RELATED LINKS [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md) [Format-Hex](Format-Hex.md) [Format-List](Format-List.md) [Format-Table](Format-Table.md) [Format-Wide](Format-Wide.md) [Get-Process](../Microsoft.PowerShell.Management/Get-Process.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Format-Hex.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/19/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/format-hex?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Format-Hex --- # Format-Hex ## SYNOPSIS Displays a file or other input as hexadecimal. ## SYNTAX ### Path ``` Format-Hex [-Path] <String[]> [-Count <Int64>] [-Offset <Int64>] [<CommonParameters>] ``` ### LiteralPath ``` Format-Hex -LiteralPath <String[]> [-Count <Int64>] [-Offset <Int64>] [<CommonParameters>] ``` ### ByInputObject ``` Format-Hex -InputObject <PSObject> [-Encoding <Encoding>] [-Count <Int64>] [-Offset <Int64>] [-Raw] [<CommonParameters>] ``` ## DESCRIPTION The `Format-Hex` cmdlet displays a file or other input as hexadecimal values. To determine the offset of a character from the output, add the number at the leftmost of the row to the number at the top of the column for that character. The `Format-Hex` cmdlet can help you determine the file type of a corrupted file or a file that might not have a filename extension. You can run this cmdlet, and then read the hexadecimal output to get file information. When using `Format-Hex` on a file, the cmdlet ignores newline characters and returns the entire contents of a file in one string with the newline characters preserved. ## EXAMPLES ### Example 1: Get the hexadecimal representation of a string This command returns the hexadecimal values of a string. ```powershell 'Hello World' | Format-Hex ``` ```Output Label: String (System.String) <2944BEC3> Offset Bytes Ascii 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ------ ----------------------------------------------- ----- 0000000000000000 48 65 6C 6C 6F 20 57 6F 72 6C 64 Hello World ``` The string **Hello World** is sent down the pipeline to the `Format-Hex` cmdlet. The hexadecimal output from `Format-Hex` shows the values of each character in the string. ### Example 2: Find a file type from hexadecimal output This example uses the hexadecimal output to determine the file type. The cmdlet displays the file's full path and the hexadecimal values. To test the following command, make a copy of an existing PDF file on your local computer and rename the copied file to `File.t7f`. ```powershell Format-Hex -Path .\File.t7f -Count 48 ``` ```Output Label: C:\Test\File.t7f Offset Bytes Ascii 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ------ ----------------------------------------------- ----- 0000000000000000 25 50 44 46 2D 31 2E 35 0D 0A 25 B5 B5 B5 B5 0D %PDF-1.5..%????. 0000000000000010 0A 31 20 30 20 6F 62 6A 0D 0A 3C 3C 2F 54 79 70 .1 0 obj..<</Typ 0000000000000020 65 2F 43 61 74 61 6C 6F 67 2F 50 61 67 65 73 20 e/Catalog/Pages ``` The `Format-Hex` cmdlet uses the **Path** parameter to specify a filename in the current directory, `File.t7f`. The file extension `.t7f` is uncommon, but the hexadecimal output `%PDF` shows that it is a PDF file. In this example, the **Count** parameter is used to limit the output to the first 48 bytes of the file. ### Example 3: Format an array of different data types This example uses an array of different data types to highlight how `Format-Hex` handles them in the Pipeline. It will pass each object through the Pipeline and process individually. However, if it's numeric data, and the adjacent object is also numeric, it will group them into a single output block. ```powershell 'Hello world!', 1, 1138, 'foo', 'bar', 0xdeadbeef, 1gb, 0b1101011100 , $true, $false | Format-Hex ``` ```Output Label: String (System.String) <24F1F0A3> Offset Bytes Ascii 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ------ ----------------------------------------------- ----- 0000000000000000 48 65 6C 6C 6F 20 77 6F 72 6C 64 21 Hello world! Label: Int32 (System.Int32) <2EB933C5> Offset Bytes Ascii 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ------ ----------------------------------------------- ----- 0000000000000000 01 00 00 00 72 04 00 00 � r� Label: String (System.String) <4078B66C> Offset Bytes Ascii 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ------ ----------------------------------------------- ----- 0000000000000000 66 6F 6F foo Label: String (System.String) <51E4A317> Offset Bytes Ascii 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ------ ----------------------------------------------- ----- 0000000000000000 62 61 72 bar Label: Int32 (System.Int32) <5ADF167B> Offset Bytes Ascii 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ------ ----------------------------------------------- ----- 0000000000000000 EF BE AD DE 00 00 00 40 5C 03 00 00 ï¾-Þ @\� Label: Boolean (System.Boolean) <7D8C4C1D> Offset Bytes Ascii 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F ------ ----------------------------------------------- ----- 0000000000000000 01 00 00 00 00 00 00 00 � ``` ## PARAMETERS ### -Count This represents the number of bytes to include in the hex output. This parameter was introduced in PowerShell 6.2. ```yaml Type: System.Int64 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Int64.MaxValue Accept pipeline input: False Accept wildcard characters: False ``` ### -Encoding Specifies the encoding of the input strings. This only applies to `[string]` input. The parameter has no effect on numeric types. The output value is always `utf8NoBOM`. The acceptable values for this parameter are as follows: - `ascii`: Uses the encoding for the ASCII (7-bit) character set. - `ansi`: Uses the encoding for the for the current culture's ANSI code page. This option was added in PowerShell 7.4. - `bigendianunicode`: Encodes in UTF-16 format using the big-endian byte order. - `bigendianutf32`: Encodes in UTF-32 format using the big-endian byte order. - `oem`: Uses the default encoding for MS-DOS and console programs. - `unicode`: Encodes in UTF-16 format using the little-endian byte order. - `utf7`: Encodes in UTF-7 format. - `utf8`: Encodes in UTF-8 format. - `utf8BOM`: Encodes in UTF-8 format with Byte Order Mark (BOM) - `utf8NoBOM`: Encodes in UTF-8 format without Byte Order Mark (BOM) - `utf32`: Encodes in UTF-32 format. Beginning with PowerShell 6.2, the **Encoding** parameter also allows numeric IDs of registered code pages (like `-Encoding 1251`) or string names of registered code pages (like `-Encoding "windows-1251"`). For more information, see the .NET documentation for [Encoding.CodePage](/dotnet/api/system.text.encoding.codepage?view=netcore-2.2). Starting with PowerShell 7.4, you can use the `Ansi` value for the **Encoding** parameter to pass the numeric ID for the current culture's ANSI code page without having to specify it manually. > [!NOTE] > **UTF-7*** is no longer recommended to use. As of PowerShell 7.1, a warning is written if you > specify `utf7` for the **Encoding** parameter. ```yaml Type: System.Text.Encoding Parameter Sets: ByInputObject Aliases: Accepted values: ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 Required: False Position: Named Default value: UTF8NoBOM Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects to be formatted. Enter a variable that contains the objects or type a command or expression that gets the objects. Only certain [scalar](/powershell/scripting/learn/glossary#scalar-value) types and `[System.IO.FileInfo]` are supported. The supported scalar types are: - `[string]`, `[char]` - `[byte]`, `[sbyte]` - `[int16]`, `[uint16]`, `[short]`, `[ushort]` - `[int]`, `[uint]`, `[int32]`, `[uint32]`, - `[long]`, `[ulong]`, `[int64]`, `[uint64]` - `[single]`, `[float]`, `[double]` - `[boolean]` Prior to PowerShell 6.2, `Format-Hex` would handle a Pipeline input with multiple input types by grouping all like objects together. Now, it handles each individual object as it passes through the Pipeline and won't group objects together unless like objects are adjacent. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: ByInputObject Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -LiteralPath Specifies the complete path to a file. The value of **LiteralPath** is used exactly as it is typed. This parameter does not accept wildcard characters. To specify multiple paths to files, separate the paths with a comma. If the **LiteralPath** parameter includes escape characters, enclose the path in single quotation marks. PowerShell does not interpret any characters in a single quoted string as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Offset This represents the number of bytes to skip from being part of the hex output. This parameter was introduced in PowerShell 6.2. ```yaml Type: System.Int64 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 0 Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to files. Use a dot (`.`) to specify the current location. The wildcard character (`*`) is accepted and can be used to specify all the items in a location. If the **Path** parameter includes escape characters, enclose the path in single quotation marks. To specify multiple paths to files, separate the paths with a comma. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Raw This parameter no longer does anything. It is retained for script compatibility. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ByInputObject Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.ByteCollection This cmdlet returns a **ByteCollection**. This object represents a collection of bytes. It includes methods that convert the collection of bytes to a string formatted like each line of output returned by `Format-Hex`. The output also states they type of bytes being processed. If you specify the **Path** or **LiteralPath** parameter, the object contains the path of the file that contains each byte. If you pass a string, boolean, integer, etc, it will be labeled appropriately. ## NOTES PowerShell includes the following aliases for `Format-Hex`: - All platforms: - `fhx` The right-most column of output tries to render the bytes as ASCII characters: Generally, each byte is interpreted as a Unicode code point, which means that: - Printable ASCII characters are always rendered correctly - Multi-byte UTF-8 characters never render correctly - UTF-16 characters render correctly only if their high-order byte happens be `NUL`. ## RELATED LINKS [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md) [Format-Custom](Format-Custom.md) [Format-List](Format-List.md) [Format-Table](Format-Table.md) [Format-Wide](Format-Wide.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Format-List.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/format-list?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Format-List --- # Format-List ## SYNOPSIS Formats the output as a list of properties in which each property appears on a new line. ## SYNTAX ``` Format-List [[-Property] <Object[]>] [-GroupBy <Object>] [-View <string>] [-ShowError] [-DisplayError] [-Force] [-Expand <string>] [-InputObject <psobject>] [<CommonParameters>] ``` ## DESCRIPTION The `Format-List` cmdlet formats the output of a command as a list of properties in which each property is displayed on a separate line. You can use `Format-List` to format and display all or selected properties of an object as a list (`Format-List -Property *`). Because more space is available for each item in a list than in a table, PowerShell displays more properties of the object in the list, and the property values are less likely to be truncated. ## EXAMPLES ### Example 1: Format computer services ```powershell Get-Service | Format-List ``` This command formats information about services on the computer as a list. By default, the services are formatted as a table. The `Get-Service` cmdlet gets objects representing the services on the computer. The pipeline operator (`|`) passes the results through the pipeline to `Format-List`. Then, the `Format-List` command formats the service information in a list and sends it to the default output cmdlet for display. ### Example 2: Format PS1XML files These commands display information about the PS1XML files in the PowerShell directory as a list. ```powershell $A = Get-ChildItem $PSHOME\*.ps1xml Format-List -InputObject $A ``` The first command gets the objects representing the files and stores them in the `$A` variable. The second command uses `Format-List` to format information about objects stored in `$A`. This command uses the **InputObject** parameter to pass the variable to `Format-List`, which then sends the formatted output to the default output cmdlet for display. ### Example 3: Format process properties by name This command displays the name, base priority, and priority class of each process on the computer. ```powershell Get-Process | Format-List -Property Name, BasePriority, PriorityClass ``` It uses the `Get-Process` cmdlet to get an object representing each process. The pipeline operator (`|`) passes the process objects through the pipeline to `Format-List`. `Format-List` formats the processes as a list of the specified properties. The **Property** parameter name is optional, so you can omit it. ### Example 4: Format all properties for a process This command displays all the properties of the Winlogon process. ```powershell Get-Process winlogon | Format-List -Property * ``` It uses the Get-Process cmdlet to get an object representing the Winlogon process. The pipeline operator (`|`) passes the Winlogon process object through the pipeline to `Format-List`. The command uses the **Property** parameter to specify the properties and the `*` to indicate all properties. Because the name of the **Property** parameter is optional, you can omit it and type the command as `Format-List *`. `Format-List` automatically sends the results to the default output cmdlet for display. ### Example 5: Troubleshooting format errors The following examples show of the results of adding the **DisplayError** or **ShowError** parameters with an expression. ```powershell PC /> Get-Date | Format-List DayOfWeek,{ $_ / $null } -DisplayError DayOfWeek : Friday $_ / $null : #ERR PC /> Get-Date | Format-List DayOfWeek,{ $_ / $null } -ShowError DayOfWeek : Friday $_ / $null : Failed to evaluate expression " $_ / $null ". + CategoryInfo : InvalidArgument: (12/21/2018 7:59:23 AM:PSObject) [], RuntimeException + FullyQualifiedErrorId : PSPropertyExpressionError ``` ## PARAMETERS ### -DisplayError Indicates that this cmdlet displays errors at the command line. This parameter is rarely used, but can be used as a debugging aid when you are formatting expressions in a `Format-List` command, and the expressions do not appear to be working. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Expand Specifies the formatted collection object, as well as the objects in the collection. This parameter is designed to format objects that support the **System.Collections.ICollection** interface. The default value is `EnumOnly`. The acceptable values for this parameter are: - `EnumOnly`. Displays the properties of the objects in the collection. - `CoreOnly`. Displays the properties of the collection object. - `Both`. Displays the properties of the collection object and the properties of objects in the collection. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: CoreOnly, EnumOnly, Both Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Indicates that this cmdlet displays all the error information. Use with the **DisplayError** or **ShowError** parameter. By default, when an error object is written to the error or display streams, only some error information is displayed. Also required when formatting certain .NET types. For more information, see the [Notes](#notes) section. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -GroupBy Specifies the output in groups based on a shared property or value. Enter an expression or a property of the output. The **GroupBy** parameter expects that the objects are sorted. Use the `Sort-Object` cmdlet before using `Format-List` to group the objects. The value of the **GroupBy** parameter can be a new calculated property. The calculated property can be a script block or a hash table. Valid key-value pairs are: - `Name` (or `Label`) - `<string>` - `Expression` - `<string>` or `<script block>` - `FormatString` - `<string>` For more information, see [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects to be formatted. Enter a variable that contains the objects or type a command or expression that gets the objects. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Property Specifies the object properties that appear in the display and the order in which they appear. Wildcards are permitted. If you omit this parameter, the properties that appear in the display depend on the object being displayed. The parameter name **Property** is optional. You cannot use the **Property** and **View** parameters in the same command. The value of the **Property** parameter can be a new calculated property. The calculated property can be a script block or a hash table. Valid key-value pairs are: - `Name` (or `Label`) - `<string>` - `Expression` - `<string>` or `<script block>` - `FormatString` - `<string>` For more information, see [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -ShowError Indicates that the cmdlet sends errors through the pipeline. This parameter is rarely used, but can be used as a debugging aid when you are formatting expressions in a `Format-List` command, and the expressions do not appear to be working. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -View Specifies the name of an alternate list format or view. You cannot use the **Property** and **View** parameters in the same command. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.Internal.Format This cmdlet returns the format objects that represent the list. ## NOTES PowerShell includes the following aliases for `Format-List`: - All platforms: - `fl` The format cmdlets, such as `Format-List`, arrange the data to be displayed but do not display it. The data is displayed by the output features of PowerShell and by the cmdlets that contain the `Out` verb (the `Out` cmdlets), such as `Out-Host` or `Out-File`. If you do not use a format cmdlet, PowerShell applies that default format for each object that it displays. The **View** parameter lets you specify an alternate format for the table. You can use the views defined in the `*.format.ps1xml` files in the PowerShell directory, or you can create your own views in new PS1XML files and use the `Update-FormatData` cmdlet to include them in PowerShell. The alternate view for the **View** parameter must use the list format, otherwise, the command fails. If the alternate view is a table, use `Format-Table`. If the alternate view is not a list or a table, use `Format-Custom`. If you want to use `Format-List` with the **Property** parameter, you need to include the **Force** parameter under any of the following conditions: - The input objects are formatted out-of-band using the `ToString()` method. This applies to `[string]` and .NET primitive types that are a superset of the built-in numeric types such as `[int]`, `[long]`, and others. - The input objects have no public properties. - The input objects are instances of the wrapper types PowerShell uses for output streams other than the Success output stream. This applies only when these wrapper types are sent to the Success output stream, which requires either having captured them via common parameters such as **ErrorVariable** first or using a redirection such as `*>&1`. - The wrapper types include: - [System.Management.Automation.ErrorRecord](/dotnet/api/System.Management.Automation.ErrorRecord) - [System.Management.Automation.WarningRecord](/dotnet/api/System.Management.Automation.WarningRecord) - [System.Management.Automation.VerboseRecord](/dotnet/api/System.Management.Automation.VerboseRecord) - [System.Management.Automation.DebugRecord](/dotnet/api/System.Management.Automation.DebugRecord) - [System.Management.Automation.InformationRecord](/dotnet/api/System.Management.Automation.InformationRecord) ## RELATED LINKS [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md) [Format-Custom](Format-Custom.md) [Format-Hex](Format-Hex.md) [Format-Table](Format-Table.md) [Format-Wide](Format-Wide.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Format-Table.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/format-table?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Format-Table --- # Format-Table ## SYNOPSIS Formats the output as a table. ## SYNTAX ### All ``` Format-Table [[-Property] <Object[]>] [-AutoSize] [-RepeatHeader] [-HideTableHeaders] [-Wrap] [-GroupBy <Object>] [-View <string>] [-ShowError] [-DisplayError] [-Force] [-Expand <string>] [-InputObject <psobject>] [<CommonParameters>] ``` ## DESCRIPTION The `Format-Table` cmdlet formats the output of a command as a table with the selected properties of the object in each column. The object type determines the default layout and properties that are displayed in each column. You can use the **Property** parameter to select the properties that you want to display. PowerShell uses default formatters to define how object types are displayed. You can use `.ps1xml` files to create custom views that display an output table with specified properties. After a custom view is created, use the **View** parameter to display the table with your custom view. For more information about views, see [about_Format.ps1xml](../Microsoft.PowerShell.Core/About/about_Format.ps1xml.md). You can use a hash table to add calculated properties to an object before displaying it and to specify the column headings in the table. To add a calculated property, use the **Property** or **GroupBy** parameter. For more information about hash tables, see [about_Hash_Tables](../Microsoft.PowerShell.Core/About/about_Hash_Tables.md). ## EXAMPLES ### Example 1: Format PowerShell host This example displays information about the host program for PowerShell in a table. ```powershell Get-Host | Format-Table -AutoSize ``` The `Get-Host` cmdlet gets **System.Management.Automation.Internal.Host.InternalHost** objects that represent the host. The objects are sent down the pipeline to `Format-Table` and displayed in a table. The **AutoSize** parameter adjusts the column widths to minimize truncation. ### Example 2: Format processes by BasePriority In this example, processes are displayed in groups that have the same **BasePriority** property. ```powershell Get-Process | Sort-Object -Property BasePriority | Format-Table -GroupBy BasePriority -Wrap ``` The `Get-Process` cmdlet gets objects that represent each process on the computer and sends them down the pipeline to `Sort-Object`. The objects are sorted in the order of their **BasePriority** property. The sorted objects are sent down the pipeline to `Format-Table`. The **GroupBy** parameter arranges the process data into groups based on their **BasePriority** property's value. The **Wrap** parameter ensures that data isn't truncated. ### Example 3: Format processes by start date This example displays information about the processes running on the computer. The objects are sorted and `Format-Table` uses a view to group the objects by their start date. ```powershell Get-Process | Sort-Object StartTime | Format-Table -View StartTime ``` `Get-Process` gets the **System.Diagnostics.Process** objects that represent the processes running on the computer. The objects are sent down the pipeline to `Sort-Object`, and are sorted based on the **StartTime** property. The sorted objects are sent down the pipeline to `Format-Table`. The **View** parameter specifies the **StartTime** view that's defined in the PowerShell `DotNetTypes.format.ps1xml` file for **System.Diagnostics.Process** objects. The **StartTime** view converts each processes start time to a short date and then groups the processes by the start date. The `DotNetTypes.format.ps1xml` file contains a **Priority** view for processes. You can create your own `format.ps1xml` files with customized views. ### Example 4: Use a custom view for table output In this example, a custom view displays a directory's contents. The custom view adds the **CreationTime** column to the table output for **System.IO.DirectoryInfo** and **System.IO.FileInfo** objects created by `Get-ChildItem`. The custom view in this example was created from the view defined in PowerShell source code. For more information about views and the code used to create this example's view, see [about_Format.ps1xml](../Microsoft.PowerShell.Core/About/about_Format.ps1xml.md#sample-xml-for-a-format-table-custom-view). ```powershell Get-ChildItem -Path C:\Test | Format-Table -View MyGciView ``` ```Output Directory: C:\Test Mode LastWriteTime CreationTime Length Name ---- ------------- ------------ ------ ---- d----- 11/4/2019 15:54 9/24/2019 15:54 Archives d----- 8/27/2019 14:22 8/27/2019 14:22 Drawings d----- 10/23/2019 09:38 2/25/2019 09:38 Files -a---- 11/7/2019 11:07 11/7/2019 11:07 11345 Alias.txt -a---- 2/27/2019 15:15 2/27/2019 15:15 258 alias_out.txt -a---- 2/27/2019 15:16 2/27/2019 15:16 258 alias_out2.txt ``` `Get-ChildItem` gets the contents of the current directory, `C:\Test`. The **System.IO.DirectoryInfo** and **System.IO.FileInfo** objects are sent down the pipeline. `Format-Table` uses the **View** parameter to specify the custom view **MyGciView** that includes the **CreationTime** column. The default `Format-Table` output for `Get-ChildItem` doesn't include the **CreationTime** column. ### Example 5: Use properties for table output This example uses the **Property** parameter to display all the computer's services in a two-column table that shows the properties **Name** and **DependentServices**. ```powershell Get-Service | Format-Table -Property Name, DependentServices ``` `Get-Service` gets all the services on the computer and sends the **System.ServiceProcess.ServiceController** objects down the pipeline. `Format-Table` uses the **Property** parameter to specify that the **Name** and **DependentServices** properties are displayed in the table. **Name** and **DependentServices** are two of the object type's properties. To view all the properties: `Get-Service | Get-Member -MemberType Properties`. ### Example 6: Format a process and calculate its running time This example displays a table with the process name and total running time for the local computer's **notepad** processes. The total running time is calculated by subtracting the start time of each process from the current time. ```powershell Get-Process notepad | Format-Table ProcessName, @{Label="TotalRunningTime"; Expression={(Get-Date) - $_.StartTime}} ``` ```Output ProcessName TotalRunningTime ----------- ---------------- notepad 03:20:00.2751767 notepad 00:00:16.7710520 ``` `Get-Process` gets all the local computer's **notepad** processes and sends the objects down the pipeline. `Format-Table` displays a table with two columns: **ProcessName**, a `Get-Process` property, and **TotalRunningTime**, a calculated property. The **TotalRunningTime** property is specified by a hash table with two keys, **Label** and **Expression**. The **Label** key specifies the property name. The **Expression** key specifies the calculation. The expression gets the **StartTime** property of each process object and subtracts it from the result of a `Get-Date` command, which gets the current date and time. ### Example 7: Format Notepad processes This example uses `Get-CimInstance` to get the running time for all **notepad** processes on the local computer. You can use `Get-CimInstance` with the **ComputerName** parameter to get information from remote computers. ```powershell $Processes = Get-CimInstance -Class Win32_Process -Filter "name='notepad.exe'" $Processes | Format-Table ProcessName, @{ Label = "Total Running Time" Expression={(Get-Date) - $_.CreationDate} } ``` ```Output ProcessName Total Running Time ----------- ------------------ notepad.exe 03:39:39.6260693 notepad.exe 00:19:56.1376922 ``` `Get-CimInstance` gets instances of the WMI **Win32_Process** class that describes all the local computer's processes named **notepad.exe**. The process objects are stored in the `$Processes` variable. The process objects in the `$Processes` variable are sent down the pipeline to `Format-Table`, which displays the **ProcessName** property and a new calculated property, **Total Running Time**. The command assigns the name of the new calculated property, **Total Running Time**, to the **Label** key. The **Expression** key's script block calculates how long the process has been running by subtracting the processes creation date from the current date. The `Get-Date` cmdlet gets the current date. The creation date is subtracted from the current date. The result is the value of **Total Running Time**. ### Example 8: Troubleshooting format errors The following examples show the results of adding the **DisplayError** or **ShowError** parameters with an expression. ```powershell Get-Date | Format-Table DayOfWeek,{ $_ / $null } -DisplayError ``` ```Output DayOfWeek $_ / $null --------- ------------ Wednesday #ERR ``` ```powershell Get-Date | Format-Table DayOfWeek,{ $_ / $null } -ShowError ``` ```Output DayOfWeek $_ / $null --------- ------------ Wednesday InvalidArgument: Failed to evaluate expression " $_ / $null ". ``` ## PARAMETERS ### -AutoSize Indicates that the cmdlet adjusts the column size and number of columns based on the width of the data. By default, the column size and number are determined by the view. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -DisplayError Indicates that the cmdlet displays errors on the command line. This parameter can be used as a debugging aid when you're formatting expressions in a `Format-Table` command and need to troubleshoot the expressions. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Expand Specifies the format of the collection object and the objects in the collection. This parameter is designed to format objects that support the [ICollection](/dotnet/api/system.collections.icollection) ([System.Collections](/dotnet/api/system.collections)) interface. The default value is **EnumOnly**. The acceptable values for this parameter are as follows: - **EnumOnly**: Displays the properties of the objects in the collection. - **CoreOnly**: Displays the properties of the collection object. - **Both**: Displays the properties of the collection object and the properties of objects in the collection. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: CoreOnly, EnumOnly, Both Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Indicates that the cmdlet directs the cmdlet to display all the error information. Use with the **DisplayError** or **ShowError** parameter. By default, when an error object is written to the error or display streams, only some error information is displayed. Also required when formatting certain .NET types. For more information, see the [Notes](#notes) section. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -GroupBy Specifies sorted output in separate tables based on a property value. For example, you can use **GroupBy** to list services in separate tables based on their status. Enter an expression or a property. The **GroupBy** parameter expects that the objects are sorted. Use the `Sort-Object` cmdlet before using `Format-Table` to group the objects. The value of the **GroupBy** parameter can be a new calculated property. The calculated property can be a script block or a hash table. Valid key-value pairs are: - Name (or Label) - `<string>` - Expression - `<string>` or `<script block>` - FormatString - `<string>` For more information, see [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -HideTableHeaders Omits the column headings from the table. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects to format. Enter a variable that contains the objects, or type a command or expression that gets the objects. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Property Specifies the object properties that appear in the display and the order in which they appear. Type one or more property names, separated by commas, or use a hash table to display a calculated property. Wildcards are permitted. If you omit this parameter, the properties that appear in the display depend on the first object's properties. For example, if the first object has **PropertyA** and **PropertyB** but subsequent objects have **PropertyA**, **PropertyB**, and **PropertyC**, then only the **PropertyA** and **PropertyB** headers are displayed. The **Property** parameter is optional. You can't use the **Property** and **View** parameters in the same command. The value of the **Property** parameter can be a new calculated property. The calculated property can be a script block or a hash table. Valid key-value pairs are: - Name (or Label) `<string>` - Expression - `<string>` or `<script block>` - FormatString - `<string>` - Width - `<int32>` - must be greater than `0` - Alignment - value can be `Left`, `Center`, or `Right` For more information, see [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -RepeatHeader Repeats displaying the header of a table after every screen full. The repeated header is useful when the output is piped to a pager such as `less` or `more` or paging with a screen reader. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ShowError This parameter sends errors through the pipeline. This parameter can be used as a debugging aid when you're formatting expressions in a `Format-Table` command and need to troubleshoot the expressions. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -View Beginning in PowerShell 6, the default views are defined in PowerShell `C#` source code. The `*.format.ps1xml` files from PowerShell 5.1 and earlier versions don't exist in PowerShell 6 and later versions. The **View** parameter lets you specify an alternate format or custom view for the table. You can use the default PowerShell views or create custom views. For more information about how to create a custom view, see [about_Format.ps1xml](../Microsoft.PowerShell.Core/About/about_Format.ps1xml.md). The alternate and custom views for the **View** parameter must use the table format, otherwise, `Format-Table` fails. If the alternate view is a list, use the `Format-List` cmdlet. If the alternate view isn't a list or a table, use the `Format-Custom` cmdlet. You can't use the **Property** and **View** parameters in the same command. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Wrap Displays text that exceeds the column width on the next line. By default, text that exceeds the column width is truncated. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.Internal.Format This cmdlet returns format objects that represent the table. ## NOTES PowerShell includes the following aliases for `Format-Table`: - All platforms: - `ft` PowerShell 7.2 introduced new features to colorize output. The colors can be managed using the `$PSStyle` automatic variable. The `$PSStyle.Formatting.TableHeader` property defines the color used for the header of the table displayed by `Format-Table`. For more information about this setting, see [about_ANSI_Terminals](../microsoft.powershell.core/about/about_ansi_terminals.md). If you want to use `Format-Table` with the **Property** parameter, you need to include the **Force** parameter under any of the following conditions: - The input objects are normally formatted out-of-band using the `ToString()` method. This applies to `[string]` and .NET primitive types, which are a superset of the built-in numeric types such as `[int]`, `[long]`, and others. - The input objects have no public properties. - The input objects are instances of the wrapper types PowerShell uses for output streams other than the Success output stream. This applies only when these wrapper types are sent to the Success output stream that requires either having captured them via common parameters such as **ErrorVariable** first or using a redirection such as `*>&1`. - The wrapper types include: - [System.Management.Automation.ErrorRecord](/dotnet/api/System.Management.Automation.ErrorRecord) - [System.Management.Automation.WarningRecord](/dotnet/api/System.Management.Automation.WarningRecord) - [System.Management.Automation.VerboseRecord](/dotnet/api/System.Management.Automation.VerboseRecord) - [System.Management.Automation.DebugRecord](/dotnet/api/System.Management.Automation.DebugRecord) - [System.Management.Automation.InformationRecord](/dotnet/api/System.Management.Automation.InformationRecord) ## RELATED LINKS [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md) [about_Format.ps1xml](../Microsoft.PowerShell.Core/About/about_Format.ps1xml.md) [about_Hash_Tables](../Microsoft.PowerShell.Core/About/about_Hash_Tables.md) [Export-FormatData](Export-FormatData.md) [Format-Custom](Format-Custom.md) [Format-Hex](Format-Hex.md) [Format-List](Format-List.md) [Format-Wide](Format-Wide.md) [Get-FormatData](Get-FormatData.md) [Get-Member](Get-Member.md) [Get-CimInstance](../CimCmdlets/Get-CimInstance.md) [Update-FormatData](Update-FormatData.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Format-Wide.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/format-wide?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Format-Wide --- # Format-Wide ## SYNOPSIS Formats objects as a wide table that displays only one property of each object. ## SYNTAX ``` Format-Wide [[-Property] <Object>] [-AutoSize] [-Column <int>] [-GroupBy <Object>] [-View <string>] [-ShowError] [-DisplayError] [-Force] [-Expand <string>] [-InputObject <psobject>] [<CommonParameters>] ``` ## DESCRIPTION The `Format-Wide` cmdlet formats objects as a wide table that displays only one property of each object. You can use the **Property** parameter to determine which property is displayed. ## EXAMPLES ### Example 1: Format names of files in the current directory This command displays the names of files in the current directory in three columns across the screen. ```powershell Get-ChildItem | Format-Wide -Column 3 ``` The `Get-ChildItem` cmdlet gets objects representing each file in the directory. The pipeline operator (`|`) passes the file objects through the pipeline to `Format-Wide`, which formats them for output. The **Column** parameter specifies the number of columns. ### Example 2: Format names of registry keys This command displays the names of registry keys in the `HKEY_CURRENT_USER\Software\Microsoft` key. ```powershell Get-ChildItem HKCU:\software\Microsoft | Format-Wide -Property PSChildName -AutoSize ``` The `Get-ChildItem` cmdlet gets objects representing the keys. The path is specified as `HKCU:`, one of the drives exposed by the PowerShell Registry provider, followed by the key path. The pipeline operator (`|`) passes the registry key objects through the pipeline to `Format-Wide`, which formats them for output. The **Property** parameter specifies the name of the property, and the **AutoSize** parameter adjusts the columns for readability. ### Example 3: Troubleshooting format errors The following examples show of the results of adding the **DisplayError** or **ShowError** parameters with an expression. ```powershell PS /> Get-Date | Format-Wide { $_ / $null } -DisplayError #ERR PS /> Get-Date | Format-Wide { $_ / $null } -ShowError Failed to evaluate expression " $_ / $null ". + CategoryInfo : InvalidArgument: (12/21/2018 8:18:01 AM:PSObject) [], RuntimeException + FullyQualifiedErrorId : PSPropertyExpressionError ``` ## PARAMETERS ### -AutoSize Adjusts the column size and number of columns based on the width of the data. By default, the column size and number are determined by the view. You cannot use the **AutoSize** and **Column** parameters in the same command. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Column Specifies the number of columns in the display. You cannot use the **AutoSize** and **Column** parameters in the same command. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DisplayError Displays errors at the command line. This parameter is rarely used, but can be used as a debugging aid when you are formatting expressions in a `Format-Wide` command, and the expressions do not appear to be working. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Expand Formats the collection object, as well as the objects in the collection. This parameter is designed to format objects that support the **System.Collections.ICollection** interface. The default value is `EnumOnly`. Valid values are: - `EnumOnly`: Displays the properties of the objects in the collection. - `CoreOnly`: Displays the properties of the collection object. - `Both`: Displays the properties of the collection object and the properties of objects in the collection. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: CoreOnly, EnumOnly, Both Required: False Position: Named Default value: EnumOnly Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Indicates that this cmdlet overrides restrictions that prevent the command from succeeding, just so the changes do not compromise security. For example, **Force** will override the read-only attribute or create directories to complete a file path, but it will not attempt to change file permissions. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -GroupBy Formats the output in groups based on a shared property or value. Enter an expression or a property of the output. The **GroupBy** parameter expects that the objects are sorted. Use the `Sort-Object` cmdlet before using `Format-Wide` to group the objects. The value of the **GroupBy** parameter can be a new calculated property. The calculated property can be a script block or a hash table. Valid key-value pairs are: - `Name` (or `Label`) - `<string>` - `Expression` - `<string>` or `<script block>` - `FormatString` - `<string>` For more information, see [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects to format. Enter a variable that contains the objects, or type a command or expression that gets the objects. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Property Specifies the object property that appears in the display. Wildcards are permitted. If you omit this parameter, the properties that appear in the display depend on the object being displayed. The parameter name **Property** is optional. You cannot use the **Property** and **View** parameters in the same command. The value of the **Property** parameter can be a new calculated property. The calculated property can be a script block or a hash table. Valid key-value pairs are: - `Expression` - `<string>` or `<script block>` - `FormatString` - `<string>` For more information, see [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -ShowError Sends errors through the pipeline. This parameter is rarely used, but can be used as a debugging aid when you are formatting expressions in a `Format-Wide` command, and the expressions do not appear to be working. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -View Specifies the name of an alternate table format or view. You cannot use the **Property** and **View** parameters in the same command. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.Internal.Format This cmdlet returns format objects that represent the table. ## NOTES PowerShell includes the following aliases for `Format-Wide`: - All platforms: - `fw` The **View** parameter lets you specify an alternate format for the table. You can use the views defined in the `*.format.ps1xml` files in the PowerShell directory or you can create your own views in new PS1XML files and use the `Update-FormatData` cmdlet to include them in PowerShell. The alternate view for the **View** parameter must use table format; if it does not, the command fails. If the alternate view is a list, use `Format-List`. If the alternate view is neither a list nor a table, use `Format-Custom`. ## RELATED LINKS [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md) [Format-Custom](Format-Custom.md) [Format-Hex](Format-Hex.md) [Format-List](Format-List.md) [Format-Table](Format-Table.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-Alias.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-alias?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Alias --- # Get-Alias ## SYNOPSIS Gets the aliases for the current session. ## SYNTAX ### Default (Default) ``` Get-Alias [[-Name] <String[]>] [-Exclude <String[]>] [-Scope <String>] [<CommonParameters>] ``` ### Definition ``` Get-Alias [-Exclude <String[]>] [-Scope <String>] [-Definition <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Alias` cmdlet gets the aliases in the current session. This includes built-in aliases, aliases that you have set or imported, and aliases that you have added to your PowerShell profile. By default, `Get-Alias` takes an alias and returns the command name. When you use the **Definition** parameter, `Get-Alias` takes a command name and returns its aliases. Beginning in Windows PowerShell 3.0, `Get-Alias` displays non-hyphenated alias names in an `<alias> -> <definition>` format to make it even easier to find the information that you need. ## EXAMPLES ### Example 1: Get all aliases in the current session ```powershell Get-Alias ``` ```Output CommandType Name ----------- ---- Alias % -> ForEach-Object Alias ? -> Where-Object Alias ac -> Add-Content Alias asnp -> Add-PSSnapin Alias cat -> Get-Content Alias cd -> Set-Location Alias chdir -> Set-Location Alias clc -> Clear-Content Alias clear -> Clear-Host Alias clhy -> Clear-History ... ``` This command gets all aliases in the current session. The output shows the `<alias> -> <definition>` format that was introduced in Windows PowerShell 3.0. This format is used only for aliases that do not include hyphens, because aliases with hyphens are typically preferred names for cmdlets and functions, rather than nicknames. ### Example 2: Get aliases by name ```powershell Get-Alias -Name gp*, sp* -Exclude *ps ``` This command gets all aliases that begin with gp or sp, except for aliases that end with ps. ### Example 3: Get aliases for a cmdlet ```powershell Get-Alias -Definition Get-ChildItem ``` This command gets the aliases for the `Get-ChildItem` cmdlet. By default, the `Get-Alias` cmdlet gets the item name when you know the alias. The **Definition** parameter gets the alias when you know the item name. ### Example 4: Get aliases by property ```powershell Get-Alias | Where-Object {$_.Options -match "ReadOnly"} ``` This command gets all aliases in which the value of the **Options** property is **ReadOnly**. This command provides a quick way to find the aliases that are built into PowerShell, because they have the **ReadOnly** option. **Options** is just one property of the **AliasInfo** objects that `Get-Alias` gets. To find all properties and methods of **AliasInfo** objects, type `Get-Alias | Get-Member`. ### Example 5: Get aliases by name and filter by beginning letter ```powershell Get-Alias -Definition "*-PSSession" -Exclude e* -Scope Global ``` This example gets aliases for commands that have names that end in "-PSSession", except for those that begin with "e". The command uses the **Scope** parameter to apply the command in the global scope. This is useful in scripts when you want to get the aliases in the session. ## PARAMETERS ### -Definition Gets the aliases for the specified item. Enter the name of a cmdlet, function, script, file, or executable file. This parameter is called **Definition**, because it searches for the item name in the Definition property of the alias object. ```yaml Type: System.String[] Parameter Sets: Definition Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Exclude Omits the specified items. The value of this parameter qualifies the **Name** and **Definition** parameters. Enter a name, a definition, or a pattern, such as "s*". Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Name Specifies the aliases that this cmdlet gets. Wildcards are permitted. By default, `Get-Alias` retrieves all aliases defined for the current session. The parameter name **Name** is optional. You can also pipe alias names to `Get-Alias`. ```yaml Type: System.String[] Parameter Sets: Default Aliases: Required: False Position: 0 Default value: All aliases Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Scope Specifies the scope for which this cmdlet gets aliases. The acceptable values for this parameter are: - `Global` - `Local` - `Script` - A number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent) `Local` is the default. For more information, see [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Local Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string containing an alias name to this cmdlet. ## OUTPUTS ### System.Management.Automation.AliasInfo This cmdlet returns an object that represents each alias. It returns the same type of object for every alias, but PowerShell uses an arrow-based format to display the names of non-hyphenated aliases. ## NOTES PowerShell includes the following aliases for `Get-Alias`: - All platforms: - `gal` - To create a new alias, use `Set-Alias` or `New-Alias`. To delete an alias, use `Remove-Item`. - The arrow-based alias name format is not used for aliases that include a hyphen. These are likely to be preferred substitute names for cmdlets and functions, instead of typical abbreviations or nicknames. ## RELATED LINKS [Export-Alias](Export-Alias.md) [Import-Alias](Import-Alias.md) [New-Alias](New-Alias.md) [Set-Alias](Set-Alias.md) [Alias Provider](../Microsoft.PowerShell.Core/About/about_Alias_Provider.md) [about_Aliases](../Microsoft.PowerShell.Core/About/about_Aliases.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-Culture.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-culture?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Culture --- # Get-Culture ## SYNOPSIS Gets the current culture set in the operating system. ## SYNTAX ### CurrentCulture (Default) ``` Get-Culture [-NoUserOverrides] [<CommonParameters>] ``` ### Name ``` Get-Culture [-Name <String[]>] [-NoUserOverrides] [<CommonParameters>] ``` ### ListAvailable ``` Get-Culture [-ListAvailable] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Culture` cmdlet gets information about the current culture settings. This includes information about the current language settings on the system, such as the keyboard layout, and the display format of items such as numbers, currency, and dates. You can also use the `Get-UICulture` cmdlet, which gets the current user interface culture on the system, and the [Set-Culture](/powershell/module/international/set-culture) cmdlet in the International module. The user-interface (UI) culture determines which text strings are used for user interface elements, such as menus and messages. ## EXAMPLES ### Example 1: Get culture settings ```powershell Get-Culture ``` ```Output LCID Name DisplayName ---- ---- ----------- 1033 en-US English (United States) ``` This command displays information about the regional settings on the computer. ### Example 2: Format the properties of a culture object ```powershell PS C:\> $C = Get-Culture PS C:\> $C | Format-List -Property * Parent : en LCID : 1033 KeyboardLayoutId : 1033 Name : en-US IetfLanguageTag : en-US DisplayName : English (United States) NativeName : English (United States) EnglishName : English (United States) TwoLetterISOLanguageName : en ThreeLetterISOLanguageName : eng ThreeLetterWindowsLanguageName : ENU CompareInfo : CompareInfo - 1033 TextInfo : TextInfo - 1033 IsNeutralCulture : False CultureTypes : SpecificCultures, InstalledWin32Cultures, FrameworkCultures NumberFormat : System.Globalization.NumberFormatInfo DateTimeFormat : System.Globalization.DateTimeFormatInfo Calendar : System.Globalization.GregorianCalendar OptionalCalendars : {System.Globalization.GregorianCalendar, System.Globalization.GregorianCalendar} UseUserOverride : True IsReadOnly : False PS C:\> $C.Calendar MinSupportedDateTime : 1/1/0001 12:00:00 AM MaxSupportedDateTime : 12/31/9999 11:59:59 PM AlgorithmType : SolarCalendar CalendarType : Localized Eras : {1} TwoDigitYearMax : 2029 IsReadOnly : False PS C:\> $C.DateTimeFormat AMDesignator : AM Calendar : System.Globalization.GregorianCalendar DateSeparator : / FirstDayOfWeek : Sunday CalendarWeekRule : FirstDay FullDateTimePattern : dddd, MMMM dd, yyyy h:mm:ss tt LongDatePattern : dddd, MMMM dd, yyyy LongTimePattern : h:mm:ss tt MonthDayPattern : MMMM dd PMDesignator : PM RFC1123Pattern : ddd, dd MMM yyyy HH':'mm':'ss 'GMT' ShortDatePattern : M/d/yyyy ShortTimePattern : h:mm tt SortableDateTimePattern : yyyy'-'MM'-'dd'T'HH':'mm':'ss TimeSeparator : : UniversalSortableDateTimePattern : yyyy'-'MM'-'dd HH':'mm':'ss'Z' YearMonthPattern : MMMM, yyyy AbbreviatedDayNames : {Sun, Mon, Tue, Wed...} ShortestDayNames : {Su, Mo, Tu, We...} DayNames : {Sunday, Monday, Tuesday, Wednesday...} AbbreviatedMonthNames : {Jan, Feb, Mar, Apr...} MonthNames : {January, February, March, April...} IsReadOnly : False NativeCalendarName : Gregorian Calendar AbbreviatedMonthGenitiveNames : {Jan, Feb, Mar, Apr...} MonthGenitiveNames : {January, February, March, April...} PS C:\> $C.DateTimeFormat.FirstDayOfWeek Sunday ``` This example demonstrates the vast amount of data in the culture object. It shows how to display the properties and sub-properties of the object. The first command uses the `Get-Culture` cmdlet to get the current culture settings on the computer. It stores the resulting culture object in the `$C` variable. The second command displays all of the properties of the culture object. It uses a pipeline operator (`|`) to send the culture object in `$C` to the `Format-List` cmdlet. It uses the **Property** parameter to display all (`*`) properties of the object. This command can be abbreviated as `$c | fl *`. The remaining commands explore the properties of the culture object by using dot notation to display the values of the object properties. You can use this notation to display the value of any property of the object. The third command uses dot notation to display the value of the **Calendar** property of the culture object. The fourth command uses dot notation to display the value of the **DataTimeFormat** property of the culture object. Many object properties have properties. The fifth command uses dot notation to display the value of the **FirstDayOfWeek** property of the **DateTimeFormat** property. ### Example 3: Get a specific culture Get the CultureInfo object for French in France. ```powershell Get-Culture -Name fr-FR ``` ```Output LCID Name DisplayName ---- ---- ----------- 1036 fr-FR French (France) ``` ## PARAMETERS ### -ListAvailable Retrieves all cultures supported by the current operating system. This parameter was introduced in PowerShell 6.2. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ListAvailable Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Retrieve a specific culture based on the name. This parameter was introduced in PowerShell 6.2. ```yaml Type: System.String[] Parameter Sets: Name Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -NoUserOverrides Ignore user changes for current culture. This parameter was introduced in PowerShell 6.2. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CurrentCulture, Name Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Globalization.CultureInfo This cmdlet returns a **CultureInfo** object representing the current culture. ## NOTES You can also use the `$PSCulture` and `$PSUICulture` variables. The `$PSCulture` variable stores the name of the current culture and the `$PSUICulture` variable stores the name of the current UI culture. ## RELATED LINKS [Set-Culture](/powershell/module/international/set-culture) [Get-UICulture](Get-UICulture.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-Date.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 03/19/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-date?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Date --- # Get-Date ## SYNOPSIS Gets the current date and time. ## SYNTAX ### DateAndFormat (Default) ``` Get-Date [[-Date] <DateTime>] [-Year <Int32>] [-Month <Int32>] [-Day <Int32>] [-Hour <Int32>] [-Minute <Int32>] [-Second <Int32>] [-Millisecond <Int32>] [-DisplayHint <DisplayHintType>] [-Format <String>] [-AsUTC] [<CommonParameters>] ``` ### DateAndUFormat ``` Get-Date [[-Date] <DateTime>] [-Year <Int32>] [-Month <Int32>] [-Day <Int32>] [-Hour <Int32>] [-Minute <Int32>] [-Second <Int32>] [-Millisecond <Int32>] [-DisplayHint <DisplayHintType>] -UFormat <String> [<CommonParameters>] ``` ### UnixTimeSecondsAndFormat ``` Get-Date -UnixTimeSeconds <Int64> [-Year <Int32>] [-Month <Int32>] [-Day <Int32>] [-Hour <Int32>] [-Minute <Int32>] [-Second <Int32>] [-Millisecond <Int32>] [-DisplayHint <DisplayHintType>] [-Format <String>] [-AsUTC] [<CommonParameters>] ``` ### UnixTimeSecondsAndUFormat ``` Get-Date -UnixTimeSeconds <Int64> [-Year <Int32>] [-Month <Int32>] [-Day <Int32>] [-Hour <Int32>] [-Minute <Int32>] [-Second <Int32>] [-Millisecond <Int32>] [-DisplayHint <DisplayHintType>] -UFormat <String> [<CommonParameters>] ``` ## DESCRIPTION The `Get-Date` cmdlet gets a **DateTime** object that represents the current date or a date that you specify. `Get-Date` can format the date and time in several .NET and Unix formats. You can use `Get-Date` to generate a date or time character string, and then send the string to other cmdlets or programs. `Get-Date` uses the current culture settings of the operating system to determine how the output is formatted. To view your computer's settings, use `(Get-Culture).DateTimeFormat`. ## EXAMPLES ### Example 1: Get the current date and time In this example, `Get-Date` displays the current system date and time. The output is in the long-date and long-time formats. ```powershell Get-Date ``` ```Output Tuesday, June 25, 2019 14:53:32 ``` ### Example 2: Get elements of the current date and time This example shows how to use `Get-Date` to get either the date or time element. The parameter uses the arguments **Date**, **Time**, or **DateTime**. ```powershell Get-Date -DisplayHint Date ``` ```Output Tuesday, June 25, 2019 ``` `Get-Date` uses the **DisplayHint** parameter with the **Date** argument to get only the date. ### Example 3: Get the date and time with a .NET format specifier In this example, a .NET format specifier is used to customize the output's format. The output is a **String** object. ```powershell Get-Date -Format "dddd MM/dd/yyyy HH:mm K" ``` ```Output Tuesday 06/25/2019 16:17 -07:00 ``` `Get-Date` uses the **Format** parameter to specify several format specifiers. The .NET format specifiers used in this example are defined as follows: | Specifier | Definition | | --------- | ----------------------------------------------------- | | `dddd` | Day of the week - full name | | `MM` | Month number | | `dd` | Day of the month - 2 digits | | `yyyy` | Year in 4-digit format | | `HH:mm` | Time in 24-hour format - no seconds | | `K` | Time zone offset from Universal Time Coordinate (UTC) | For more information about .NET format specifiers, see [Custom date and time format strings](/dotnet/standard/base-types/custom-date-and-time-format-strings). ### Example 4: Get the date and time with a UFormat specifier In this example, several **UFormat** format specifiers are used to customize the output's format. The output is a **String** object. ```powershell Get-Date -UFormat "%A %m/%d/%Y %R %Z" ``` ```Output Tuesday 06/25/2019 16:19 -07 ``` `Get-Date` uses the **UFormat** parameter to specify several format specifiers. The **UFormat** format specifiers used in this example are defined as follows: | Specifier | Definition | | --------- | ----------------------------------------------------- | | `%A` | Day of the week - full name | | `%m` | Month number | | `%d` | Day of the month - 2 digits | | `%Y` | Year in 4-digit format | | `%R` | Time in 24-hour format - no seconds | | `%Z` | Time zone offset from Universal Time Coordinate (UTC) | For a list of valid **UFormat** format specifiers, see the [Notes](#notes) section. ### Example 5: Get a date's day of the year In this example, a property is used to get the numeric day of the year. The Gregorian calendar has 365 days, except for leap years that have 366 days. For example, December 31, 2020 is day 366. ```powershell (Get-Date -Year 2020 -Month 12 -Day 31).DayOfYear ``` ```Output 366 ``` `Get-Date` uses three parameters to specify the date: **Year**, **Month**, and **Day**. The command is wrapped with parentheses so that the result is evaluated by the **DayOfYear** property. ### Example 6: Check if a date is adjusted for daylight saving time This example uses a boolean method to verify if a date is adjusted by daylight saving time. ```powershell $DST = Get-Date $DST.IsDaylightSavingTime() ``` ```Output True ``` A variable, `$DST` stores the result of `Get-Date`. `$DST` uses the **IsDaylightSavingTime** method to test if the date is adjusted for daylight saving time. ### Example 7: Convert the current time to UTC time In this example, the current time is converted to UTC time. The UTC offset for the system's locale is used to convert the time. A table in the [Notes](#notes) section lists the valid **UFormat** format specifiers. ```powershell Get-Date -UFormat "%A %B/%d/%Y %T %Z" $Time = Get-Date $Time.ToUniversalTime() ``` ```Output Wednesday June/26/2019 10:45:26 -07 Wednesday, June 26, 2019 17:45:26 ``` `Get-Date` uses the **UFormat** parameter with format specifiers to display the current system date and time. The format specifier **%Z** represents the UTC offset of **-07**. The `$Time` variable stores the current system date and time. `$Time` uses the `ToUniversalTime()` method to convert the time based on the computer's UTC offset. ### Example 8: Create a timestamp In this example, a format specifier creates a timestamp **String** object for a directory name. The timestamp includes the date, time, and UTC offset. ```powershell $timestamp = Get-Date -Format o | ForEach-Object { $_ -replace ":", "." } New-Item -Path C:\Test\$timestamp -Type Directory ``` ```Output Directory: C:\Test Mode LastWriteTime Length Name ---- ------------- ------ ---- d----- 6/27/2019 07:59 2019-06-27T07.59.24.4603750-07.00 ``` The `$timestamp` variable stores the results of a `Get-Date` command. `Get-Date` uses the **Format** parameter with the format specifier of lowercase `o` to create a timestamp **String** object. The object is sent down the pipeline to `ForEach-Object`. A **ScriptBlock** contains the `$_` variable that represents the current pipeline object. The timestamp string is delimited by colons that are replaced by periods. `New-Item` uses the **Path** parameter to specify the location for a new directory. The path includes the `$timestamp` variable as the directory name. The **Type** parameter specifies that a directory is created. ### Example 9: Convert a Unix timestamp This example converts a Unix time (represented by the number of seconds since 1970-01-01 0:00:00) to DateTime. ```powershell Get-Date -UnixTimeSeconds 1577836800 ``` ```Output Wednesday, January 01, 2020 12:00:00 AM ``` ### Example 10: Return a date value interpreted as UTC This example shows how to interpret a date value as its UTC equivalent. For the example, this machine is set to **Pacific Standard Time**. By default, `Get-Date` returns values for that timezone. Use the **AsUTC** parameter to convert the value to the UTC equivalent time. ```powershell PS> Get-TimeZone Id : Pacific Standard Time DisplayName : (UTC-08:00) Pacific Time (US & Canada) StandardName : Pacific Standard Time DaylightName : Pacific Daylight Time BaseUtcOffset : -08:00:00 SupportsDaylightSavingTime : True PS> (Get-Date -Date "2020-01-01T00:00:00").Kind Unspecified PS> Get-Date -Date "2020-01-01T00:00:00" Wednesday, January 1, 2020 12:00:00 AM PS> (Get-Date -Date "2020-01-01T00:00:00" -AsUTC).Kind Utc PS> Get-Date -Date "2020-01-01T00:00:00" -AsUTC Wednesday, January 1, 2020 8:00:00 AM ``` ### Example 11: Show invariant culture The `ToString()` converts a **DateTime** object a **String** using the current culture setting. However, PowerShell expression interpretation always uses the invariant culture setting. For example, on a system with the `en-US` culture in effect, the `ToString()` method formats the date using the `en-US` culture settings. ```powershell # Get date using current culture en-US (Get-Date 2024-03-19).ToString() ``` ```Output 3/19/2024 12:00:00 AM ``` ```powershell # Get date using invariant culture "$(Get-Date 2024-03-19)" ``` ```Output 03/19/2024 00:00:00 ``` ## PARAMETERS ### -AsUTC Converts the date value to the equivalent time in UTC. This parameter was introduced in PowerShell 7.1. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Date Specifies a date and time. Time is optional and if not specified, returns 00:00:00. Enter the date and time in a format that is standard for the currently selected locale. You can change the current locale using the `Set-Culture` cmdlet. For example, in US English: `Get-Date -Date "6/25/2019 12:30:22"` returns **Tuesday, June 25, 2019 12:30:22** ```yaml Type: System.DateTime Parameter Sets: DateAndFormat, DateAndUFormat Aliases: LastWriteTime Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Day Specifies the day of the month that is displayed. Enter a value from 1 to 31. If the specified value is greater than the number of days in a month, PowerShell adds the number of days to the month. For example, `Get-Date -Month 4 -Day 31` displays **May 1**, not **April 31**. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DisplayHint Determines which elements of the date and time are displayed. The accepted values are as follows: - **Date**: displays only the date - **Time**: displays only the time - **DateTime**: displays the date and time ```yaml Type: Microsoft.PowerShell.Commands.DisplayHintType Parameter Sets: (All) Aliases: Accepted values: Date, Time, DateTime Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Format Displays the date and time in the Microsoft .NET Framework format indicated by the format specifier. The **Format** parameter outputs a **String** object. For a list of available .NET format specifiers, see [Custom date and time format strings](/dotnet/standard/base-types/custom-date-and-time-format-strings). When the **Format** parameter is used, `Get-Date` only gets the **DateTime** object's properties necessary to display the date. As a result, some of the properties and methods of **DateTime** objects might not be available. Starting in PowerShell 5.0, you can use the following additional formats as values for the **Format** parameter. - **FileDate**. A file or path-friendly representation of the current date in local time. The format is `yyyyMMdd` (case-sensitive, using a 4-digit year, 2-digit month, and 2-digit day). For example: 20190627. - **FileDateUniversal**. A file or path-friendly representation of the current date in universal time (UTC). The format is `yyyyMMddZ` (case-sensitive, using a 4-digit year, 2-digit month, 2-digit day, and the letter `Z` as the UTC indicator). For example: 20190627Z. - **FileDateTime**. A file or path-friendly representation of the current date and time in local time, in 24-hour format. The format is `yyyyMMddTHHmmssffff` (case-sensitive, using a 4-digit year, 2-digit month, 2-digit day, the letter `T` as a time separator, 2-digit hour, 2-digit minute, 2-digit second, and 4-digit millisecond). For example: 20190627T0840107271. - **FileDateTimeUniversal**. A file or path-friendly representation of the current date and time in universal time (UTC), in 24-hour format. The format is `yyyyMMddTHHmmssffffZ` (case-sensitive, using a 4-digit year, 2-digit month, 2-digit day, the letter `T` as a time separator, 2-digit hour, 2-digit minute, 2-digit second, 4-digit millisecond, and the letter `Z` as the UTC indicator). For example: 20190627T1540500718Z. ```yaml Type: System.String Parameter Sets: DateAndFormat, UnixTimeSecondsAndFormat Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Hour Specifies the hour that is displayed. Enter a value from 0 to 23. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Millisecond Specifies the milliseconds in the date. Enter a value from 0 to 999. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Minute Specifies the minute that is displayed. Enter a value from 0 to 59. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Month Specifies the month that is displayed. Enter a value from 1 to 12. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Second Specifies the second that is displayed. Enter a value from 0 to 59. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UFormat Displays the date and time in Unix format. The **UFormat** parameter outputs a string object. **UFormat** specifiers are preceded by a percent sign (`%`), for example, `%m`, `%d`, and `%Y`. The [Notes](#notes) section contains a table of valid **UFormat specifiers**. When the **UFormat** parameter is used, `Get-Date` only gets the **DateTime** object's properties necessary to display the date. As a result, some of the properties and methods of **DateTime** objects might not be available. ```yaml Type: System.String Parameter Sets: DateAndUFormat, UnixTimeSecondsAndUFormat Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UnixTimeSeconds Date and time represented in seconds since January 1, 1970, 0:00:00. This parameter was introduced in PowerShell 7.1. ```yaml Type: System.Int64 Parameter Sets: UnixTimeSecondsAndFormat, UnixTimeSecondsAndUFormat Aliases: UnixTime Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Year Specifies the year that is displayed. Enter a value from 1 to 9999. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.DateTime You can pipe a **DateTime** object to this cmdlet. ## OUTPUTS ### System.DateTime By default, this cmdlet returns a **DateTime** object. When a **DateTime** object is sent down the pipeline to a cmdlet such as `Add-Content` that expects string input, PowerShell converts the object to a **String** object. The `ToString()` converts a **DateTime** object to a **String** using the current culture setting. However, PowerShell expression interpretation always uses the invariant culture setting. To see how invariant culture is different, see [Example 11](#example-11-show-invariant-culture). To display an object's properties and methods, send the object down the pipeline to `Get-Member`. For example, `Get-Date | Get-Member`. ### System.String When you use the **Format** or **UFormat** parameters, this cmdlet returns **String** objects. ## NOTES The default formats for the output of **DateTime** objects are long-date and long-time formats for the currently selected locale. The valid **UFormat specifiers** are displayed in the following table: > [!IMPORTANT] > **UFormat** specifiers are changed or added in newer versions of PowerShell. For example, `%F` was > added in PowerShell 6.2, so it isn't available in Windows PowerShell 5.1 or older. Keep this in > mind when using **UFormat** specifiers in scripts designed to be run on multiple versions of > PowerShell. | Format specifier | Meaning | Example | | ---- | ----------------------------------------------------------------------- | ------------------------ | | `%A` | Day of the week - full name | Monday | | `%a` | Day of the week - abbreviated name | Mon | | `%B` | Month name - full | January | | `%b` | Month name - abbreviated | Jan | | `%C` | Century | 20 for 2019 | | `%c` | Date and time - abbreviated | Thu Jun 27 08:44:18 2019 | | `%D` | Date in mm/dd/yy format | 06/27/19 | | `%d` | Day of the month - 2 digits | 05 | | `%e` | Day of the month - preceded by a space if only a single digit | \<space\>5 | | `%F` | Date in YYYY-mm-dd format, equal to %Y-%m-%d (the ISO 8601 date format) | 2019-06-27 | | `%G` | ISO week date year (year containing Thursday of the week) | | | `%g` | Same as 'G' - 2 digits | | | `%H` | Hour in 24-hour format | 17 | | `%h` | Same as 'b' | | | `%I` | Hour in 12-hour format | 05 | | `%j` | Day of the year | 1-366 | | `%k` | Same as 'H' | | | `%l` | Same as 'I' (Upper-case I) | 05 | | `%M` | Minutes | 35 | | `%m` | Month number | 06 | | `%n` | newline character | | | `%p` | AM or PM | | | `%R` | Time in 24-hour format -no seconds | 17:45 | | `%r` | Time in 12-hour format | 09:15:36 AM | | `%S` | Seconds | 05 | | `%s` | Seconds elapsed since January 1, 1970 00:00:00 (UTC) | 1150451174 | | `%t` | Horizontal tab character | | | `%T` | Time in 24-hour format | 17:45:52 | | `%U` | Same as 'W' | | | `%u` | Numeric day of the week (1-7) (Changed in PowerShell 7.2) | Monday = 1, Sunday = 7 | | `%V` | Week of the year | 01-53 | | `%w` | Numeric day of the week (0-6) | Sunday = 0, Saturday = 6 | | `%W` | Week of the year | 1-53 | | `%X` | Same as 'T' | | | `%x` | Date in standard format for locale | 06/27/19 for English-US | | `%Y` | Year in 4-digit format | 2019 | | `%y` | Year in 2-digit format | 19 | | `%Z` | Time zone offset from Universal Time Coordinate (UTC) | -07 | > [!NOTE] > The behavior of `-UFormat %s` was changed to fix problems with the behavior in Windows PowerShell. > > - The return value is based on UTC time. > - The value is a whole number of seconds value (no fractional part). ## RELATED LINKS [ForEach-Object](../Microsoft.PowerShell.Core/ForEach-Object.md) [Get-Culture](Get-Culture.md) [Get-Member](Get-Member.md) [New-Item](../Microsoft.PowerShell.Management/New-Item.md) [New-TimeSpan](New-TimeSpan.md) [Set-Date](Set-Date.md) [Set-Culture](xref:International.Set-Culture)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-Error.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/23/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-error?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Error --- # Get-Error ## SYNOPSIS Gets and displays the most recent error messages from the current session. ## SYNTAX ### Newest (Default) ``` Get-Error [[-Newest] <Int32>] [<CommonParameters>] ``` ### Error ``` Get-Error [-InputObject <PSObject>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Error` cmdlet gets a **PSExtendedError** object that represents the current error details from the last error that occurred in the session. You can use `Get-Error` to display a specified number of errors that have occurred in the current session using the **Newest** parameter. The `Get-Error` cmdlet also receives error objects from a collection, such as `$Error`, to display multiple errors from the current session. ## EXAMPLES ### Example 1: Get the most recent error details In this example, `Get-Error` displays the details of the most recent error that occurred in the current session. ```powershell Get-ChildItem -Path /NoRealDirectory Get-Error ``` ``` Get-ChildItem: Cannot find path 'C:\NoRealDirectory' because it does not exist. Exception : ErrorRecord : Exception : Message : Cannot find path 'C:\NoRealDirectory' because it does not exist. HResult : -2146233087 TargetObject : C:\NoRealDirectory CategoryInfo : ObjectNotFound: (C:\NoRealDirectory:String) [], ParentContainsErrorRecordException FullyQualifiedErrorId : PathNotFound ItemName : C:\NoRealDirectory SessionStateCategory : Drive TargetSite : Name : GetChildItems DeclaringType : System.Management.Automation.SessionStateInternal MemberType : Method Module : System.Management.Automation.dll StackTrace : at System.Management.Automation.SessionStateInternal.GetChildItems(String path, Boolean recurse, UInt32 depth, CmdletProviderContext context) at System.Management.Automation.ChildItemCmdletProviderIntrinsics.Get(String path, Boolean recurse, UInt32 depth, CmdletProviderContext context) at Microsoft.PowerShell.Commands.GetChildItemCommand.ProcessRecord() Message : Cannot find path 'C:\NoRealDirectory' because it does not exist. Source : System.Management.Automation HResult : -2146233087 TargetObject : C:\NoRealDirectory CategoryInfo : ObjectNotFound: (C:\NoRealDirectory:String) [Get-ChildItem], ItemNotFoundException FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand InvocationInfo : MyCommand : Get-ChildItem ScriptLineNumber : 1 OffsetInLine : 1 HistoryId : 57 Line : Get-ChildItem -Path C:\NoRealDirectory PositionMessage : At line:1 char:1 + Get-ChildItem -Path C:\NoRealDirectory + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ InvocationName : Get-ChildItem CommandOrigin : Internal ScriptStackTrace : at <ScriptBlock>, <No file>: line 1 PipelineIterationInfo : ``` ### Example 2: Get the specified number of error messages that occurred in the current session This example shows how to use `Get-Error` with the **Newest** parameter. In this example, **Newest** returns the details of the 3 newest errors that occurred in this session. ```powershell Get-Error -Newest 3 ``` ### Example 3: Send a collection of errors to receive detailed messages The `$Error` automatic variable contains an array of error objects in the current session. The array of objects can be piped to `Get-Error` to receive detailed error messages. In this example, `$Error` is piped to the `Get-Error` cmdlet. the result is list of detailed error messages, similar to the result of Example 1. ```powershell $Error | Get-Error ``` ## PARAMETERS ### -InputObject This parameter is used for pipeline input. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: Error Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Newest Specifies the number of errors to display that have occurred in the current session. ```yaml Type: System.Int32 Parameter Sets: Newest Aliases: Last Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### PSObject You can pipe any **PSObject** to this cmdlet, but results vary unless either an **ErrorRecord** or **Exception** object is supplied. ## OUTPUTS ### System.Management.Automation.ErrorRecord#PSExtendedError This cmdlet returns a **PSExtendedError** object. ## NOTES PowerShell includes the following aliases for `Get-Error`: - All platforms: - `gerr` `Get-Error` accepts pipeline input. For example, `$Error | Get-Error`. ## RELATED LINKS [about_Try_Catch_Finally](../Microsoft.PowerShell.Core/About/about_Try_Catch_Finally.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-Event.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-event?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Event --- # Get-Event ## SYNOPSIS Gets the events in the event queue. ## SYNTAX ### BySource (Default) ``` Get-Event [[-SourceIdentifier] <String>] [<CommonParameters>] ``` ### ById ``` Get-Event [-EventIdentifier] <Int32> [<CommonParameters>] ``` ## DESCRIPTION The `Get-Event` cmdlet gets events in the PowerShell event queue for the current session. You can get all events or use the **EventIdentifier** or **SourceIdentifier** parameter to specify the events. When an event occurs, it is added to the event queue. The event queue includes events for which you have registered, events created by using the `New-Event` cmdlet, and the event that is raised when PowerShell exits. You can use `Get-Event` or `Wait-Event` to get the events. This cmdlet does not get events from the Event Viewer logs. To get those events, use `Get-WinEvent` or `Get-EventLog`. ## EXAMPLES ### Example 1: Get all events ``` PS C:\> Get-Event ``` This command gets all events in the event queue. ### Example 2: Get events by source identifier ``` PS C:\> Get-Event -SourceIdentifier "PowerShell.ProcessCreated" ``` This command gets events in which the value of the SourceIdentifier property is PowerShell.ProcessCreated. ### Example 3: Get an event based on the time it was generated ``` PS C:\> $Events = Get-Event PS C:\> $Events[0] | Format-List -Property * ComputerName : RunspaceId : c2153740-256d-46c0-a57c-b805917d1b7b EventIdentifier : 1 Sender : System.Management.ManagementEventWatcher SourceEventArgs : System.Management.EventArrivedEventArgs SourceArgs : {System.Management.ManagementEventWatcher, System.Management.EventArrivedEventArgs} SourceIdentifier : ProcessStarted TimeGenerated : 11/13/2008 12:09:32 PM MessageData : PS C:\> Get-Event | where {$_.TimeGenerated -ge "11/13/2008 12:15:00 PM"} ComputerName : RunspaceId : c2153740-256d-46c0-a57c-b8059325d1a0 EventIdentifier : 1 Sender : System.Management.ManagementEventWatcher SourceEventArgs : System.Management.EventArrivedEventArgs SourceArgs : {System.Management.ManagementEventWatcher, System.Management.EventArrivedEventArgs} SourceIdentifier : ProcessStarted TimeGenerated : 11/13/2008 12:15:00 PM MessageData : ``` This example shows how to get events by using properties other than SourceIdentifier. The first command gets all events in the event queue and saves them in the `$Events` variable. The second command uses array notation to get the first (0-index) event in the array in the `$Events` variable. The command uses a pipeline operator (`|`) to send the event to the `Format-List` command, which displays all properties of the event in a list. This allows you to examine the properties of the event object. The third command shows how to use the `Where-Object` cmdlet to get an event based on the time that it was generated. ### Example 4: Get an event by its identifier ``` PS C:\> Get-Event -EventIdentifier 2 ``` This command gets the event with an event identifier of 2. ## PARAMETERS ### -EventIdentifier Specifies the event identifiers for which this cmdlet gets events. ```yaml Type: System.Int32 Parameter Sets: ById Aliases: Id Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -SourceIdentifier Specifies source identifiers for which this cmdlet gets events. The default is all events in the event queue. Wildcards are not permitted. ```yaml Type: System.String Parameter Sets: BySource Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSEventArgs This cmdlet returns a **PSEventArgs** object for each event. To see a description of this object, type `Get-Help Get-Event -Full` and see the Notes section of the help topic. ## NOTES No event sources available on the Linux or macOS platforms. Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled. The `Get-Event` cmdlet returns a **PSEventArgs** object (**System.Management.Automation.PSEventArgs**) with the following properties: - ComputerName. The name of the computer on which the event occurred. This property value is populated only when the event is forwarded from a remote computer. - RunspaceId. A GUID that uniquely identifies the session in which the event occurred. This property value is populated only when the event is forwarded from a remote computer. - EventIdentifier. An integer (Int32) that uniquely identifies the event notification in the current session. - Sender. The object that generated the event. In the value of the **Action** parameter, the `$Sender` automatic variable contains the sender object. - SourceEventArgs. The first parameter that derives from EventArgs, if it exists. For example, in a timer elapsed event in which the signature has the form Object sender, **Timers.ElapsedEventArgs** e, the **SourceEventArgs** property would contain the **Timers.ElapsedEventArgs**. In the value of the **Action** parameter, the `$EventArgs` automatic variable contains this value. - SourceArgs. All parameters of the original event signature. For a standard event signature, `$args[0]` represents the sender, and `$args[1]` represents the **SourceEventArgs**. In the value of the **Action** parameter, the `$args` automatic variable contains this value. - SourceIdentifier. A string that identifies the event subscription. In the value of the **Action** parameter, the **SourceIdentifier** property of the `$Event` automatic variable contains this value. - TimeGenerated. A **DateTime** object that represents the time at which the event was generated. In the value of the **Action** parameter, the **TimeGenerated** property of the `$Event` automatic variable contains this value. - MessageData. Data associated with the event subscription. Users specify this data when they register an event. In the value of the **Action** parameter, the **MessageData** property of the `$Event` automatic variable contains this value. ## RELATED LINKS [New-Event](New-Event.md) [Register-EngineEvent](Register-EngineEvent.md) [Register-ObjectEvent](Register-ObjectEvent.md) [Remove-Event](Remove-Event.md) [Unregister-Event](Unregister-Event.md) [Wait-Event](Wait-Event.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-EventSubscriber.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 06/20/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-eventsubscriber?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-EventSubscriber --- # Get-EventSubscriber ## SYNOPSIS Gets the event subscribers in the current session. ## SYNTAX ### BySource (Default) ``` Get-EventSubscriber [[-SourceIdentifier] <String>] [-Force] [<CommonParameters>] ``` ### ById ``` Get-EventSubscriber [-SubscriptionId] <Int32> [-Force] [<CommonParameters>] ``` ## DESCRIPTION The `Get-EventSubscriber` cmdlet gets the event subscribers in the current session. When you subscribe to an event by using a Register event cmdlet, an event subscriber is added to your Windows PowerShell session, and the events to which you subscribed are added to your event queue whenever they are raised. To cancel an event subscription, delete the event subscriber by using the `Unregister-Event` cmdlet. ## EXAMPLES ### Example 1: Get the event subscriber for a timer event This example uses a `Get-EventSubscriber` command to get the event subscriber for a timer event. The first command uses the `New-Object` cmdlet to create an instance of a timer object. It saves the new timer object in the `$Timer` variable. The second command uses the `Get-Member` cmdlet to display the events that are available for timer objects. The command uses the Type parameter of the `Get-Member` cmdlet with a value of Event. ```powershell $Timer = New-Object Timers.Timer $Timer | Get-Member -Type Event ``` ```Output TypeName: System.Timers.Timer Name MemberType Definition ---- ---------- ---------- Disposed Event System.EventHandler Disposed(System.Object, System.EventArgs) Elapsed Event System.Timers.ElapsedEventHandler Elapsed(System.Object, System.Timers.ElapsedEventArgs) ``` ```powershell Register-ObjectEvent -InputObject $Timer -EventName Elapsed -SourceIdentifier Timer.Elapsed Get-EventSubscriber ``` ```Output SubscriptionId : 4 SourceObject : System.Timers.Timer EventName : Elapsed SourceIdentifier : Timer.Elapsed Action : HandlerDelegate : SupportEvent : False ForwardEvent : False ``` The third command uses the `Register-ObjectEvent` cmdlet to register for the **Elapsed** event on the timer object. The fourth command uses the `Get-EventSubscriber` cmdlet to get the event subscriber for the **Elapsed** event. ### Example 2: Use the dynamic module in PSEventJob in the Action property of the event subscriber This example shows how to use the dynamic module in the **PSEventJob** object in the **Action** property of the event subscriber. The first command uses the `New-Object` cmdlet to create a timer object. The second command sets the interval of the timer to 500 (milliseconds). ```powershell $Timer = New-Object Timers.Timer $Timer.Interval = 500 $params = @{ InputObject = $Timer EventName = 'Elapsed' SourceIdentifier = 'Timer.Random' Action = { $Random = Get-Random -Min 0 -Max 100 } } Register-ObjectEvent @params ``` ```Output Id Name State HasMoreData Location Command -- ---- ----- ----------- -------- ------- 3 Timer.Random NotStarted False $Random = Get-Random ... ``` ```powershell $Timer.Enabled = $true $Subscriber = Get-EventSubscriber -SourceIdentifier Timer.Random ($Subscriber.Action).GetType().FullName ``` ```Output System.Management.Automation.PSEventJob ``` ```powershell $Subscriber.Action | Format-List -Property * ``` ```Output State : Running Module : __DynamicModule_6b5cbe82-d634-41d1-ae5e-ad7fe8d57fe0 StatusMessage : HasMoreData : True Location : Command : $random = Get-Random -Min 0 -Max 100 JobStateInfo : Running Finished : System.Threading.ManualResetEvent InstanceId : 88944290-133d-4b44-8752-f901bd8012e2 Id : 1 Name : Timer.Random ChildJobs : {} ... ``` ```powershell & $Subscriber.Action.Module {$Random} ``` The third command uses the `Register-ObjectEvent` cmdlet to register the Elapsed event of the timer object. The command includes an action that handles the event. Whenever the timer interval elapses, an event is raised and the commands in the action run. In this case, the `Get-Random` cmdlet generates a random number between 0 and 100 and saves it in the `$Random` variable. The source identifier of the event is Timer.Random. When you use an **Action** parameter in a `Register-ObjectEvent` command, the command returns a **PSEventJob** object that represents the action. The fourth command enables the timer. The fifth command uses the `Get-EventSubscriber` cmdlet to get the event subscriber of the **Timer.Random** event. It saves the event subscriber object in the `$Subscriber` variable. The sixth command shows that the Action property of the event subscriber object contains a **PSEventJob** object. In fact, it contains the same **PSEventJob** object that the `Register-ObjectEvent` command returned. The seventh command uses the `Format-List` cmdlet to display all of the properties of the **PSEventJob** object in the Action property in a list. The result reveals that the **PSEventJob** object has a Module property that contains a dynamic script module that implements the action. The remaining commands use the call operator (`&`) to invoke the command in the module and display the value of the $Random variable. You can use the call operator to invoke any command in a module, including commands that are not exported. In this case, the commands show the random number that is being generated when the Elapsed event occurs. For more information about modules, see [about_Modules](../Microsoft.PowerShell.Core/About/about_Modules.md). ### Example 3: Get hidden event subscribers This example registers an event subscriber for the **PowerShell.Exiting** event. The subscription is registered using the **SupportEvent** parameter, which hides the event subscriber from the default output of the `Get-EventSubscriber` cmdlet. You must use the **Force** parameter to get all event subscribers, including hidden subscribers. ```powershell Register-EngineEvent -SourceIdentifier PowerShell.Exiting -SupportEvent -Action { Get-History | Export-Clixml D:\temp\history.clixml } Get-EventSubscriber # No output - must use -Force Get-EventSubscriber -Force ``` ```Output SubscriptionId : 1 SourceObject : EventName : SourceIdentifier : PowerShell.Exiting Action : System.Management.Automation.PSEventJob HandlerDelegate : SupportEvent : True ForwardEvent : False ``` ## PARAMETERS ### -Force Indicates that this cmdlet gets all event subscribers, including subscribers for events that are hidden by using the **SupportEvent** parameter of `Register-ObjectEvent`, `Register-WmiEvent`, and `Register-EngineEvent`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SourceIdentifier Specifies the **SourceIdentifier** property value that gets only the event subscribers. By default, `Get-EventSubscriber` gets all event subscribers in the session. Wildcards are not permitted. This parameter is case-sensitive. ```yaml Type: System.String Parameter Sets: BySource Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -SubscriptionId Specifies the subscription identifier that this cmdlet gets. By default, `Get-EventSubscriber` gets all event subscribers in the session. ```yaml Type: System.Int32 Parameter Sets: ById Aliases: Id Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSEventSubscriber This cmdlet returns a **PSEventSubscriber** object for each event subscriber. ## NOTES The `New-Event` cmdlet, which creates a custom event, does not generate a subscriber. Therefore, the `Get-EventSubscriber` cmdlet will not find a subscriber object for these events. However, if you use the `Register-EngineEvent` cmdlet to subscribe to a custom event (in order to forward the event or to specify an action), `Get-EventSubscriber` will find the subscriber that `Register-EngineEvent` generates. Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled. ## RELATED LINKS [Get-Event](Get-Event.md) [New-Event](New-Event.md) [Register-EngineEvent](Register-EngineEvent.md) [Register-ObjectEvent](Register-ObjectEvent.md) [Remove-Event](Remove-Event.md) [Unregister-Event](Unregister-Event.md) [Wait-Event](Wait-Event.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-FileHash.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-filehash?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-FileHash --- # Get-FileHash ## SYNOPSIS Computes the hash value for a file by using a specified hash algorithm. ## SYNTAX ### Path (Default) ``` Get-FileHash [-Path] <String[]> [[-Algorithm] <String>] [<CommonParameters>] ``` ### LiteralPath ``` Get-FileHash [-LiteralPath] <String[]> [[-Algorithm] <String>] [<CommonParameters>] ``` ### StreamParameterSet ``` Get-FileHash [-InputStream] <Stream> [[-Algorithm] <String>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-FileHash` cmdlet computes the hash value for a file by using a specified hash algorithm. A hash value is a unique value that corresponds to the content of the file. Rather than identifying the contents of a file by its file name, extension, or other designation, a hash assigns a unique value to the contents of a file. File names and extensions can be changed without altering the content of the file, and without changing the hash value. Similarly, the file's content can be changed without changing the name or extension. However, changing even a single character in the contents of a file changes the hash value of the file. The purpose of hash values is to provide a cryptographically-secure way to verify that the contents of a file have not been changed. While some hash algorithms, including MD5 and SHA1, are no longer considered secure against attack, the goal of a secure hash algorithm is to render it impossible to change the contents of a file -- either by accident, or by malicious or unauthorized attempt -- and maintain the same hash value. You can also use hash values to determine if two different files have exactly the same content. If the hash values of two files are identical, the contents of the files are also identical. By default, the `Get-FileHash` cmdlet uses the SHA256 algorithm, although any hash algorithm that is supported by the target operating system can be used. ## EXAMPLES ### Example 1: Compute the hash value for a file This example uses the `Get-FileHash` cmdlet to compute the hash value for the `/etc/apt/sources.list` file. The hash algorithm used is the default, **SHA256**. The output is piped to the `Format-List` cmdlet to format the output as a list. ```powershell Get-FileHash /etc/apt/sources.list | Format-List ``` ```Output Algorithm : SHA256 Hash : 3CBCFDDEC145E3382D592266BE193E5BE53443138EE6AB6CA09FF20DF609E268 Path : /etc/apt/sources.list ``` ### Example 2: Compute the hash value for an ISO file This example uses the `Get-FileHash` cmdlet and the **SHA384** algorithm to compute the hash value for an ISO file that an administrator has downloaded from the internet. The output is piped to the `Format-List` cmdlet to format the output as a list. ```powershell Get-FileHash C:\Users\user1\Downloads\Contoso8_1_ENT.iso -Algorithm SHA384 | Format-List ``` ```Output Algorithm : SHA384 Hash : 20AB1C2EE19FC96A7C66E33917D191A24E3CE9DAC99DB7C786ACCE31E559144FEAFC695C58E508E2EBBC9D3C96F21FA3 Path : C:\Users\user1\Downloads\Contoso8_1_ENT.iso ``` ### Example 3: Compute the hash value of a stream For this example, we get are using **System.Net.WebClient** to download a package from the [PowerShell release page](https://github.com/PowerShell/PowerShell/releases/tag/v6.2.4). The release page also documents the SHA256 hash of each package file. We can compare the published hash value with the one we calculate with `Get-FileHash`. ```powershell $wc = [System.Net.WebClient]::new() $pkgurl = 'https://github.com/PowerShell/PowerShell/releases/download/v6.2.4/powershell_6.2.4-1.debian.9_amd64.deb' $publishedHash = '8E28E54D601F0751922DE24632C1E716B4684876255CF82304A9B19E89A9CCAC' $FileHash = Get-FileHash -InputStream ($wc.OpenRead($pkgurl)) $FileHash.Hash -eq $publishedHash ``` ```Output True ``` ### Example 4: Compute the hash of a string PowerShell does not provide a cmdlet to compute the hash of a string. However, you can write a string to a stream and use the **InputStream** parameter of `Get-FileHash` to get the hash value. ```powershell $stringAsStream = [System.IO.MemoryStream]::new() $writer = [System.IO.StreamWriter]::new($stringAsStream) $writer.Write("Hello world") $writer.Flush() $stringAsStream.Position = 0 Get-FileHash -InputStream $stringAsStream | Select-Object Hash ``` ```Output Hash ---- 64EC88CA00B268E5BA1A35678A1B5316D212F4F366B2477232534A8AECA37F3C ``` ## PARAMETERS ### -Algorithm Specifies the cryptographic hash function to use for computing the hash value of the contents of the specified file or stream. A cryptographic hash function has the property that it is infeasible to find two different files with the same hash value. Hash functions are commonly used with digital signatures and for data integrity. The acceptable values for this parameter are: - SHA1 - SHA256 - SHA384 - SHA512 - MD5 If no value is specified, or if the parameter is omitted, the default value is SHA256. For security reasons, MD5 and SHA1, which are no longer considered secure, should only be used for simple change validation, and should not be used to generate hash values for files that require protection from attack or tampering. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: SHA1, SHA256, SHA384, SHA512, MD5 Required: False Position: 1 Default value: SHA256 Accept pipeline input: False Accept wildcard characters: False ``` ### -InputStream Specifies the input stream. ```yaml Type: System.IO.Stream Parameter Sets: StreamParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to a file. Unlike the **Path** parameter, the value of the **LiteralPath** parameter is used exactly as it is typed. No characters are interpreted as wildcard characters. If the path includes escape characters, enclose the path in single quotation marks. Single quotation marks instruct PowerShell not to interpret characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the path to one or more files as an array. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string containing a path to a file to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Utility.FileHash This cmdlet returns an object representing the path to the specified file, the value of the computed hash, and the algorithm used to compute the hash. ## NOTES ## RELATED LINKS [Format-List](Format-List.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-FormatData.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-formatdata?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-FormatData --- # Get-FormatData ## SYNOPSIS Gets the formatting data in the current session. ## SYNTAX ``` Get-FormatData [[-TypeName] <String[]>] [-PowerShellVersion <Version>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-FormatData` cmdlet gets the formatting data in the current session. The formatting data in the session includes formatting data from `Format.ps1xml` formatting files, such as those in the `$PSHOME` directory, formatting data for modules that you import into the session, and formatting data for commands that you import into your session by using the `Import-PSSession` cmdlet. You can use this cmdlet to examine the formatting data. Then, you can use the `Export-FormatData` cmdlet to serialize the objects, convert them to XML, and save them in `Format.ps1xml` files. For more information about formatting files in PowerShell, see [about_Format.ps1xml](../Microsoft.PowerShell.Core/About/about_Format.ps1xml.md). ## EXAMPLES ### Example 1: Get all formatting data This example gets all the formatting data in the session. ```powershell Get-FormatData ``` ### Example 2: Get formatting data by type name This example gets the formatting data items whose names begin with `System.Management.Automation.Cmd`. ```powershell Get-FormatData -TypeName 'System.Management.Automation.Cmd*' ``` ### Example 3: Examine a formatting data object This example shows how to get a formatting data object and examine its properties. ```powershell $F = Get-FormatData -TypeName 'System.Management.Automation.Cmd*' $F ``` ```Output TypeName FormatViewDefinition -------- -------------------- HelpInfoShort {help , TableControl} ``` ```powershell $F.FormatViewDefinition[0].Control ``` ```Output Headers : {System.Management.Automation.TableControlColumnHeader, System.Management.Automation.TableControlColumnHeader, System.Management.Automation.TableControlColumnHeader, System.Management.Automation.TableControlColumnHeader} Rows : {System.Management.Automation.TableControlRow} AutoSize : False HideTableHeaders : False GroupBy : OutOfBand : False ``` ```powershell $F.FormatViewDefinition[0].Control.Headers ``` ```Output Label Alignment Width ----- --------- ----- CommandType Undefined 15 Name Undefined 50 Version Undefined 10 Source Undefined 0 ``` ### Example 4: Get formatting data and export it This example shows how to use `Get-FormatData` and `Export-FormatData` to export the formatting data that is added by a module. ```powershell $A = Get-FormatData Import-Module BitsTransfer $B = Get-FormatData Compare-Object $A $B ``` ```Output InputObject SideIndicator ----------- ------------- Microsoft.BackgroundIntelligentTransfer.Management.BitsJob => ``` ```powershell Get-FormatData *bits* | Export-FormatData -FilePath C:\test\Bits.format.ps1xml Get-Content C:\test\Bits.format.ps1xml ``` ```Output <?xml version="1.0" encoding="utf-8"?><Configuration><ViewDefinitions> <View><Name>Microsoft.BackgroundIntelligentTransfer.Management.BitsJob</Name> ... ``` The first four commands use the `Get-FormatData`, `Import-Module`, and `Compare-Object` cmdlets to identify the format type that the **BitsTransfer** module adds to the session. The fifth command uses the `Get-FormatData` cmdlet to get the format type that the **BitsTransfer** module adds. It uses a pipeline operator (`|`) to send the format type object to the `Export-FormatData` cmdlet, which converts it back to XML and saves it in the specified `Bits.format.ps1xml` file. The final command shows an excerpt of the `format.ps1xml` file content. ### Example 5: Get formatting data based on the specified version of PowerShell This example shows how to use `Get-FormatData` to get format data for a specified **TypeName** and PowerShell version. ```powershell Get-FormatData -TypeName 'Microsoft.Powershell.Utility.FileHash' -PowerShellVersion $PSVersionTable.PSVersion TypeNames FormatViewDefinition --------- -------------------- {Microsoft.Powershell.Utility.FileHash} {Microsoft.Powershell.Utility.FileHash} ``` ## PARAMETERS ### -PowerShellVersion Specify the version of PowerShell this cmdlet gets for the formatting data. Enter a two digit number separated by a period. This parameter was added in PowerShell 5.1 to improve compatibility when remoting computers running older versions of PowerShell. ```yaml Type: System.Version Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TypeName Specifies the type names that this cmdlet gets for the formatting data. Enter the type names. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.ExtendedTypeDefinition ## NOTES ## RELATED LINKS [Export-FormatData](Export-FormatData.md) [Update-FormatData](Update-FormatData.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-Host.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 08/02/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-host?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Host --- # Get-Host ## SYNOPSIS Gets an object that represents the current host program. ## SYNTAX ``` Get-Host [<CommonParameters>] ``` ## DESCRIPTION The `Get-Host` cmdlet gets an object that represents the program that is hosting Windows PowerShell. The default display includes the Windows PowerShell version number and the current region and language settings that the host is using, but the host object contains a wealth of information, including detailed information about the version of Windows PowerShell that is currently running and the current culture and UI culture of Windows PowerShell. You can also use this cmdlet to customize features of the host program user interface, such as the text and background colors. ## EXAMPLES ### Example 1: Get information about the PowerShell console host ```powershell Get-Host ``` ```Output Name : ConsoleHost Version : 2.0 InstanceId : e4e0ab54-cc5e-4261-9117-4081f20ce7a2 UI : System.Management.Automation.Internal.Host.InternalHostUserInterface CurrentCulture : en-US CurrentUICulture : en-US PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy IsRunspacePushed : False Runspace : System.Management.Automation.Runspaces.LocalRunspace ``` This command displays information about the PowerShell console, which is the current host program for PowerShell in this example. It includes the name of the host, the version of PowerShell that is running in the host, and current culture and UI culture. The **Version**, **UI**, **CurrentCulture**, **CurrentUICulture**, **PrivateData**, and **Runspace** properties each contain an object with other useful properties. Later examples examine these properties. ### Example 2: Resize the PowerShell window ```powershell $H = Get-Host $Win = $H.UI.RawUI.WindowSize $Win.Height = 10 $Win.Width = 10 $H.UI.RawUI.Set_WindowSize($Win) ``` This command resizes the Windows PowerShell window to 10 lines by 10 characters. ### Example 3: Get the PowerShell version for the host ```powershell (Get-Host).Version ``` ```Output Major Minor Build Revision PSSemVerPreReleaseLabel PSSemVerBuildLabel ----- ----- ----- -------- ----------------------- ------------------ 7 4 0 -1 preview.1 ``` This command gets detailed information about the version of Windows PowerShell running in the host. You can view, but not change, these values. The **Version** property of `Get-Host` contains a **System.Version** object. This command uses a pipeline operator (`|`) to send the version object to the `Format-List` cmdlet. The `Format-List` command uses the **Property** parameter with a value of all (`*`) to display all of the properties and property values of the version object. ### Example 4: Get the current culture for the host ```powershell (Get-Host).CurrentCulture | Format-List ``` ```Output Parent : en LCID : 1033 KeyboardLayoutId : 1033 Name : en-US IetfLanguageTag : en-US DisplayName : English (United States) NativeName : English (United States) EnglishName : English (United States) TwoLetterISOLanguageName : en ThreeLetterISOLanguageName : eng ThreeLetterWindowsLanguageName : ENU CompareInfo : CompareInfo - en-US TextInfo : TextInfo - en-US IsNeutralCulture : False CultureTypes : SpecificCultures, InstalledWin32Cultures NumberFormat : System.Globalization.NumberFormatInfo DateTimeFormat : System.Globalization.DateTimeFormatInfo Calendar : System.Globalization.GregorianCalendar OptionalCalendars : {System.Globalization.GregorianCalendar} UseUserOverride : True IsReadOnly : True ``` This command gets detailed information about the current culture set for Windows PowerShell running in the host. This is the same information that is returned by the `Get-Culture` cmdlet. Similarly, the **CurrentUICulture** property returns the same object that `Get-UICulture` returns. The **CurrentCulture** property of the host object contains a **System.Globalization.CultureInfo** object. This command uses a pipeline operator (`|`) to send the **CultureInfo** object to the `Format-List` cmdlet. The `Format-List` command uses the **Property** parameter with a value of all (`*`) to display all of the properties and property values of the **CultureInfo** object. ### Example 5: Get the DateTimeFormat for the current culture ```powershell (Get-Host).CurrentCulture.DateTimeFormat | Format-List ``` ```Output AMDesignator : AM Calendar : System.Globalization.GregorianCalendar DateSeparator : / FirstDayOfWeek : Sunday CalendarWeekRule : FirstDay FullDateTimePattern : dddd, MMMM dd, yyyy h:mm:ss tt LongDatePattern : dddd, MMMM dd, yyyy LongTimePattern : h:mm:ss tt MonthDayPattern : MMMM dd PMDesignator : PM RFC1123Pattern : ddd, dd MMM yyyy HH':'mm':'ss 'GMT' ShortDatePattern : M/d/yyyy ShortTimePattern : h:mm tt SortableDateTimePattern : yyyy'-'MM'-'dd'T'HH':'mm':'ss TimeSeparator : : UniversalSortableDateTimePattern : yyyy'-'MM'-'dd HH':'mm':'ss'Z' YearMonthPattern : MMMM, yyyy AbbreviatedDayNames : {Sun, Mon, Tue, Wed...} ShortestDayNames : {Su, Mo, Tu, We...} DayNames : {Sunday, Monday, Tuesday, Wednesday...} AbbreviatedMonthNames : {Jan, Feb, Mar, Apr...} MonthNames : {January, February, March, April...} IsReadOnly : False NativeCalendarName : Gregorian Calendar AbbreviatedMonthGenitiveNames : {Jan, Feb, Mar, Apr...} MonthGenitiveNames : {January, February, March, April...} ``` This command returns detailed information about the DateTimeFormat of the current culture that is being used for Windows PowerShell. The **CurrentCulture** property of the host object contains a **CultureInfo** object that, in turn, has many useful properties. Among them, the **DateTimeFormat** property contains a **DateTimeFormatInfo** object with many useful properties. To find the type of an object that is stored in an object property, use the `Get-Member` cmdlet. To display the property values of the object, use the `Format-List` cmdlet. ### Example 6: Get the RawUI property for the host This command displays the properties of the **RawUI** property of the host object. By changing these values, you can change the appearance of the host program. ```powershell (Get-Host).UI.RawUI ``` ```Output ForegroundColor : Gray BackgroundColor : Black CursorPosition : 0,28 WindowPosition : 0,0 CursorSize : 25 BufferSize : 120,29 WindowSize : 120,29 MaxWindowSize : 120,29 MaxPhysicalWindowSize : 1904,69 KeyAvailable : True WindowTitle : PowerShell 7.3.3 ``` > [!NOTE] > On non-Windows platforms, **ForegroundColor** and **BackgroundColor** default to `-1` because > there is no consistent way to get these on non-Windows platforms. ## PARAMETERS ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.Internal.Host.InternalHost This cmdlet returns an **InternalHost** object. ## NOTES The `$Host` automatic variable contains the same object that `Get-Host` returns, and you can use it in the same way. Similarly, the `$PSCulture` and `$PSUICulture` automatic variables contain the same objects that the CurrentCulture and CurrentUICulture properties of the host object contain. You can use these features interchangeably. > [!NOTE] > The color settings in `$Host.PrivateData` have been replaced by the `$PSStyle` preference > variable. For more information, see > [about_ANSI_Terminals](../Microsoft.PowerShell.Core/About/about_ANSI_Terminals.md). For more information, see [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md). ## RELATED LINKS [Clear-Host](../Microsoft.PowerShell.Core/Clear-Host.md) [Read-Host](Read-Host.md) [Write-Host](Write-Host.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-MarkdownOption.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/Microsoft.PowerShell.Utility/Get-MarkdownOption?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-MarkdownOption --- # Get-MarkdownOption ## SYNOPSIS Returns the current colors and styles used for rendering Markdown content in the console. ## SYNTAX ``` Get-MarkdownOption [<CommonParameters>] ``` ## DESCRIPTION Returns the current colors and styles used for rendering Markdown content in the console. The strings displayed in the output of this cmdlet contain the ANSI escape codes used to change the color and style of the Markdown text being rendered. For more information about Markdown, see the [CommonMark](https://commonmark.org/) website. ## EXAMPLES ### Example 1 - Get the current colors and style ```powershell Get-MarkdownOption ``` ```Output Header1 : [7m Header2 : [4;93m Header3 : [4;94m Header4 : [4;95m Header5 : [4;96m Header6 : [4;97m Code : [48;2;155;155;155;38;2;30;30;30m Link : [4;38;5;117m Image : [33m EmphasisBold : [1m EmphasisItalics : [36m ``` > [!NOTE] > The string values shown in the output are the characters that follow the **Escape** character > (`[char]0x1B`) for the ANSI escape sequence. For more information about ANSI escape codes work, > see [ANSI_escape_code](https://en.wikipedia.org/wiki/ANSI_escape_code). ## PARAMETERS ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.MarkdownRender.PSMarkdownOptionInfo ## NOTES ## RELATED LINKS [Set-MarkdownOption](Set-MarkdownOption.md) [ConvertFrom-Markdown](ConvertFrom-Markdown.md) [Show-Markdown](Show-Markdown.md) [ANSI_escape_code](https://en.wikipedia.org/wiki/ANSI_escape_code) [CommonMark](https://commonmark.org/)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-Member.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/10/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-member?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Member --- # Get-Member ## SYNOPSIS Gets the properties and methods of objects. ## SYNTAX ``` Get-Member [-InputObject <PSObject>] [[-Name] <String[]>] [-MemberType <PSMemberTypes>] [-View <PSMemberViewTypes>] [-Static] [-Force] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Member` cmdlet gets the members, the properties and methods, of objects. To specify the object, use the **InputObject** parameter or pipe an object to `Get-Member`. To get information about static members, the members of the class, not of the instance, use the **Static** parameter. To get only certain types of members, such as **NoteProperties**, use the **MemberType** parameter. `Get-Member` returns a list of members that's sorted alphabetically. Methods are listed first, followed by the properties. ## EXAMPLES ### Example 1: Get the members of process objects This command displays the properties and methods of the service objects generated by the `Get-Service` cmdlet. Because the `Get-Member` part of the command doesn't have any parameters, it uses default values for the parameters. By default, `Get-Member` doesn't get static or intrinsic members. ```powershell Get-Service | Get-Member ``` ```Output TypeName: System.Service.ServiceController#StartupType Name MemberType Definition ---- ---------- ---------- Name AliasProperty Name = ServiceName RequiredServices AliasProperty RequiredServices = ServicesDependedOn Disposed Event System.EventHandler Disposed(System.Object, System.EventArgs) Close Method void Close() Continue Method void Continue() Dispose Method void Dispose(), void IDisposable.Dispose() Equals Method bool Equals(System.Object obj) ExecuteCommand Method void ExecuteCommand(int command) GetHashCode Method int GetHashCode() GetLifetimeService Method System.Object GetLifetimeService() GetType Method type GetType() InitializeLifetimeService Method System.Object InitializeLifetimeService() Pause Method void Pause() Refresh Method void Refresh() Start Method void Start(), void Start(string[] args) Stop Method void Stop() WaitForStatus Method void WaitForStatus(System.ServiceProcess.ServiceControllerSt... BinaryPathName Property System.String {get;set;} CanPauseAndContinue Property bool CanPauseAndContinue {get;} CanShutdown Property bool CanShutdown {get;} CanStop Property bool CanStop {get;} Container Property System.ComponentModel.IContainer Container {get;} DelayedAutoStart Property System.Boolean {get;set;} DependentServices Property System.ServiceProcess.ServiceController[] DependentServices {get;} Description Property System.String {get;set;} DisplayName Property string DisplayName {get;set;} MachineName Property string MachineName {get;set;} ServiceHandle Property System.Runtime.InteropServices.SafeHandle ServiceHandle {get;} ServiceName Property string ServiceName {get;set;} ServicesDependedOn Property System.ServiceProcess.ServiceController[] ServicesDependedOn {get;} ServiceType Property System.ServiceProcess.ServiceType ServiceType {get;} Site Property System.ComponentModel.ISite Site {get;set;} StartType Property System.ServiceProcess.ServiceStartMode StartType {get;} StartupType Property Microsoft.PowerShell.Commands.ServiceStartupType {get;set;} Status Property System.ServiceProcess.ServiceControllerStatus Status {get;} UserName Property System.String {get;set;} ToString ScriptMethod System.Object ToString(); ``` ### Example 2: Get members of service objects This example gets all the members (properties and methods) of service objects retrieved by the `Get-Service` cmdlet, including the intrinsic members, such as **psbase**, **psobject**, and the **get_** and **set_** methods. ```powershell Get-Service | Get-Member -Force (Get-Service Schedule).psbase ``` The `Get-Member` command uses the **Force** parameter to add the intrinsic members and compiler-generated members of the objects to the display. You can use these properties and methods in the same way that you would use an adapted method of the object. The second command shows how to display the value of the **psbase** property of the Schedule service. For more information on intrinsic members, see [about_Intrinsic_Members](../Microsoft.PowerShell.Core/About/about_Intrinsic_Members.md) ### Example 3: Get extended members of service objects This example gets the methods and properties of service objects that were extended using a `Types.ps1xml` file or the `Add-Member` cmdlet. ```powershell Get-Service | Get-Member -View Extended ``` ```Output TypeName: System.Service.ServiceController#StartupType Name MemberType Definition ---- ---------- ---------- Name AliasProperty Name = ServiceName RequiredServices AliasProperty RequiredServices = ServicesDependedOn ToString ScriptMethod System.Object ToString(); ``` The `Get-Member` command uses the **View** parameter to get only the extended members of the service objects. In this case, the extended member is the **Name** property, which is an alias property of the **ServiceName** property. ### Example 4: Get script properties of event log objects This example gets the script properties of event log objects in the System log in Event Viewer. ```powershell Get-WinEvent -LogName System -MaxEvents 1 | Get-Member -MemberType NoteProperty ``` ```Output TypeName: System.Diagnostics.Eventing.Reader.EventLogRecord Name MemberType Definition ---- ---------- ---------- Message NoteProperty string Message=The machine-default permission settings do not grant Local ... ``` The **MemberType** parameter gets only objects with a value of `NoteProperty` for their **MemberType** property. The command returns the **Message** property of the **EventLogRecord** object. ### Example 5: Get objects with a specified property This example gets objects that have a **MachineName** property in the output from a list of cmdlets. The `$list` variable contains a list of cmdlets to be evaluated. The `foreach` statement invokes each command and sends the results to `Get-Member`. The **Name** parameter limits the results from `Get-Member` to members that have the name **MachineName**. ```powershell $list = "Get-Process", "Get-Service", "Get-Culture", "Get-PSDrive", "Get-ExecutionPolicy" foreach ($cmdlet in $list) {& $cmdlet | Get-Member -Name MachineName} ``` ```Output TypeName: System.Diagnostics.Process Name MemberType Definition ---- ---------- ---------- MachineName Property string MachineName {get;} TypeName: System.Service.ServiceController#StartupType Name MemberType Definition ---- ---------- ---------- MachineName Property string MachineName {get;set;} ``` The results show that only process objects and service objects have a **MachineName** property. ### Example 6: Get members for an array This example demonstrates how to find the members of an array of objects. When you pipe and array of objects to `Get-Member`, the cmdlet returns a member list for each unique object type in the array. If you pass the array using the **InputObject** parameter, the array is treated as a single object. ```powershell $array = @(1,'hello') $array | Get-Member ``` ```Output TypeName: System.Int32 Name MemberType Definition ---- ---------- ---------- CompareTo Method int CompareTo(System.Object value), int CompareTo(int value), int ICompar... Equals Method bool Equals(System.Object obj), bool Equals(int obj), bool IEquatable[int... GetHashCode Method int GetHashCode() GetType Method type GetType() GetTypeCode Method System.TypeCode GetTypeCode(), System.TypeCode IConvertible.GetTypeCode() ToBoolean Method bool IConvertible.ToBoolean(System.IFormatProvider provider) ToByte Method byte IConvertible.ToByte(System.IFormatProvider provider) ... TypeName: System.String Name MemberType Definition ---- ---------- ---------- Clone Method System.Object Clone(), System.Object ICloneable.Clone() CompareTo Method int CompareTo(System.Object value), int CompareTo(str... Contains Method bool Contains(string value), bool Contains(string val... CopyTo Method void CopyTo(int sourceIndex, char[] destination, int ... EndsWith Method bool EndsWith(string value), bool EndsWith(string val... EnumerateRunes Method System.Text.StringRuneEnumerator EnumerateRunes() Equals Method bool Equals(System.Object obj), bool Equals(string va... GetEnumerator Method System.CharEnumerator GetEnumerator(), System.Collect... GetHashCode Method int GetHashCode(), int GetHashCode(System.StringCompa... ... ``` ```powershell Get-Member -InputObject $array ``` ```Output TypeName: System.Object[] Name MemberType Definition ---- ---------- ---------- Add Method int IList.Add(System.Object value) Address Method System.Object&, System.Private.CoreLib, Version=4.0.0.0, Cu... Clear Method void IList.Clear() Clone Method System.Object Clone(), System.Object ICloneable.Clone() CompareTo Method int IStructuralComparable.CompareTo(System.Object other, Sy... ... ``` The `$array` variable contains an **Int32** object and a **string** object, as seen when the array is piped to `Get-Member`. When `$array` is passed using the **InputObject** parameter `Get-Member` returns the members of the **Object[]** type. ### Example 7: Determine which object properties you can set This example shows how to determine which properties of an object can be changed. ```powershell $File = Get-Item C:\test\textFile.txt $File.psobject.Properties | Where-Object IsSettable | Select-Object -Property Name ``` ```Output Name ---- PSPath PSParentPath PSChildName PSDrive PSProvider PSIsContainer IsReadOnly CreationTime CreationTimeUtc LastAccessTime LastAccessTimeUtc LastWriteTime LastWriteTimeUtc Attributes ``` ### Example 8: List the properties of an object in the order they were created This example creates a new **PSObject** and adds properties to it. `Get-Member` lists the properties in alphabetic order. To see the properties in the order they were added to the object you must use the **psobject** intrinsic member. ```powershell $Asset = New-Object -TypeName psobject $d = [ordered]@{Name="Server30";System="Server Core";PSVersion="4.0"} $Asset | Add-Member -NotePropertyMembers $d -TypeName Asset $Asset.psobject.Properties | Select-Object Name, Value ``` ```Output Name Value ---- ----- Name Server30 System Server Core PSVersion 4.0 ``` ## PARAMETERS ### -Force Adds the intrinsic members and the compiler-generated **get_** and **set_** methods to the display. The following list describes the properties that are added when you use the **Force** parameter: - `psbase`: The original properties of the .NET object without extension or adaptation. These are the properties defined for the object class. - `psadapted`: The properties and methods defined in the PowerShell extended type system. - `psextended`: The properties and methods that were added in the `Types.ps1xml` files or using the `Add-Member` cmdlet. - `psobject`: The adapter that converts the base object to a PowerShell **PSObject** object. - `pstypenames`: A list of object types that describe the object, in order of specificity. When formatting the object, PowerShell searches for the types in the `Format.ps1xml` files in the PowerShell installation directory (`$PSHOME`). It uses the formatting definition for the first type that it finds. By default, `Get-Member` gets these properties in all views except **Base** and **Adapted**, but doesn't display them. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the object whose members are retrieved. Using the **InputObject** parameter isn't the same as piping an object to `Get-Member`. The differences are as follows: - When you pipe a collection of objects to `Get-Member`, `Get-Member` gets the members of the individual objects in the collection, such as the properties of each string in an array of strings. - When you use **InputObject** to submit a collection of objects, `Get-Member` gets the members of the collection, such as the properties of the array in an array of strings. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -MemberType Specifies the member type that this cmdlet gets. The default is `All`. The acceptable values for this parameter are: - `AliasProperty` - `CodeProperty` - `Property` - `NoteProperty` - `ScriptProperty` - `Properties` - `PropertySet` - `Method` - `CodeMethod` - `ScriptMethod` - `Methods` - `ParameterizedProperty` - `MemberSet` - `Event` - `Dynamic` - `All` These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **MemberType** parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. For information about these values, see [PSMemberTypes Enumeration](/dotnet/api/system.management.automation.psmembertypes). Not all objects have every type of member. If you specify a member type that the object doesn't have, PowerShell returns a null value. To get related types of members, such as all extended members, use the **View** parameter. If you use the **MemberType** parameter with the **Static** or **View** parameters, `Get-Member` gets the members that belong to both sets. ```yaml Type: System.Management.Automation.PSMemberTypes Parameter Sets: (All) Aliases: Type Accepted values: AliasProperty, CodeProperty, Property, NoteProperty, ScriptProperty, Properties, PropertySet, Method, CodeMethod, ScriptMethod, Methods, ParameterizedProperty, MemberSet, Event, Dynamic, All Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies the names of one or more properties or methods of the object. `Get-Member` gets only the specified properties and methods. If you use the **Name** parameter with the **MemberType**, **View**, or **Static** parameter, `Get-Member` gets only the members that satisfy the criteria of all parameters. To get a static member by name, use the **Static** parameter with the **Name** parameter. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Static Indicates that this cmdlet gets only the static properties and methods of the object. Static properties and methods are defined on the class of objects, not on any particular instance of the class. If you use the **Static** parameter with the **View** or **Force** parameters, the cmdlet ignores those parameters. If you use the **Static** parameter with the **MemberType** parameter, `Get-Member` gets only the members that belong to both sets. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -View Specifies that this cmdlet gets only particular types properties and methods. Specify one or more of the values. The default is **Adapted**, **Extended**. The acceptable values for this parameter are: - Base. Gets only the original properties and methods of the .NET object (without extension or adaptation). - Adapted. Gets only the properties and methods defined in the PowerShell extended type system. - Extended. Gets only the properties and methods that were added in a `Types.ps1xml` files or by using the `Add-Member` cmdlet. - All. Gets the members in the Base, Adapted, and Extended views. The **View** parameter determines the members retrieved, not just the display of those members. To get particular member types, such as script properties, use the **MemberType** parameter. If you use the **MemberType** and **View** parameters in the same command, `Get-Member` gets the members that belong to both sets. If you use the **Static** and **View** parameters in the same command, the **View** parameter is ignored. ```yaml Type: System.Management.Automation.PSMemberViewTypes Parameter Sets: (All) Aliases: Accepted values: Extended, Adapted, Base, All Required: False Position: Named Default value: Adapted, Extended Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.MemberDefinition This cmdlet returns a **MemberDefinition** for each property or method that its gets. ## NOTES PowerShell includes the following aliases for `Get-Member`: - All platforms: - `gm` You can get information about a collection object either using the **InputObject** parameter or by piping the object, preceded by a comma, to `Get-Member`. You can use the `$this` automatic variable in script blocks that define the values of new properties and methods. The `$this` variable refers to the instance of the object to which the properties and methods are being added. For more information about the `$this` variable, see [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md). If you pass an object representing a _type_, like a type literal such as `[int]`, `Get-Member` return information about the `[System.RuntimeType]` type. However, when you use the **Static** parameter, `Get-Member` returns the static members of the specific type represented by the `System.RuntimeType` instance. ## RELATED LINKS [Add-Member](Add-Member.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-PSBreakpoint.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/20/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-psbreakpoint?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-PSBreakpoint --- # Get-PSBreakpoint ## SYNOPSIS Gets the breakpoints that are set in the current session. ## SYNTAX ### Line (Default) ``` Get-PSBreakpoint [[-Script] <String[]>] [-Runspace <Runspace>] [<CommonParameters>] ``` ### Command ``` Get-PSBreakpoint [[-Script] <String[]>] -Command <String[]> [-Runspace <Runspace>] [<CommonParameters>] ``` ### Variable ``` Get-PSBreakpoint [[-Script] <String[]>] -Variable <String[]> [-Runspace <Runspace>] [<CommonParameters>] ``` ### Type ``` Get-PSBreakpoint [[-Script] <String[]>] [-Type] <BreakpointType[]> [-Runspace <Runspace>] [<CommonParameters>] ``` ### Id ``` Get-PSBreakpoint [-Id] <Int32[]> [-Runspace <Runspace>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-PSBreakpoint` cmdlet gets the breakpoints that are set in the current session. You can use the cmdlet parameters to get particular breakpoints. A breakpoint is a point in a command or script where execution stops temporarily so that you can examine the instructions. `Get-PSBreakpoint` is one of several cmdlets designed for debugging PowerShell scripts and commands. For more information about the PowerShell debugger, see [about_Debuggers](../microsoft.powershell.core/about/about_debuggers.md). ## EXAMPLES ### Example 1: Get all breakpoints for all scripts and functions This command gets all breakpoints set on all scripts and functions in the current session. ```powershell Get-PSBreakpoint ``` ### Example 2: Get breakpoints by ID This command gets the breakpoint with breakpoint ID 2. ```powershell Get-PSBreakpoint -Id 2 ``` ```Output Function : IncrementAction : Enabled : TrueHitCount : 0 Id : 2 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 ``` ### Example 3: Pipe an ID to `Get-PSBreakpoint` These commands show how to get a breakpoint by piping a breakpoint ID to `Get-PSBreakpoint`. ```powershell $B = `Set-PSBreakpoint` -Script "sample.ps1" -Command "Increment" $B.Id | Get-PSBreakpoint ``` The `Set-PSBreakpoint` cmdlet creates a breakpoint on the Increment function in the `Sample.ps1` script and saves the breakpoint object in the `$B` variable. The **Id** property of the breakpoint object in the `$B` variable is piped to the `Get-PSBreakpoint` cmdlet to display the breakpoint information. ### Example 4: Get breakpoints in specified script files This command gets all of the breakpoints in the `Sample.ps1` and `SupportScript.ps1` files. ```powershell Get-PSBreakpoint -Script "Sample.ps1, SupportScript.ps1" ``` This command does not get other breakpoints that might be set in other scripts or on functions in the session. ### Example 5: Get breakpoints in specified cmdlets This command gets all Command breakpoints that are set on `Read-Host` or `Write-Host` commands in the `Sample.ps1` file. ```powershell Get-PSBreakpoint -Command "Read-Host, Write-Host" -Script "Sample.ps1" ``` ### Example 6: Get Command breakpoints in a specified file ```powershell Get-PSBreakpoint -Type Command -Script "Sample.ps1" ``` This command gets all Command breakpoints in the Sample.ps1 file. ### Example 7: Get breakpoints by variable This command gets breakpoints that are set on the `$Index` and `$Swap` variables in the current session. ```powershell Get-PSBreakpoint -Variable "Index, Swap" ``` ### Example 8: Get all Line and Variable breakpoints in a file This command gets all line and variable breakpoints in the `Sample.ps1` script. ```powershell Get-PSBreakpoint -Type Line, Variable -Script "Sample.ps1" ``` ### Example 9: Get the breakpoints set in a specific runspace In this example, a job is started and a breakpoint is set to break when the `Set-PSBreakpoint` is run. The runspace is stored in a variable and passed to the `Get-PSBreakpoint` command with the **Runspace** parameter. You can then inspect the breakpoint in the `$breakpoint` variable. ```powershell Start-Job -ScriptBlock { Set-PSBreakpoint -Command Start-Sleep Start-Sleep -Seconds 10 } $runspace = Get-Runspace -Id 1 $breakpoint = Get-PSBreakpoint -Runspace $runspace ``` ## PARAMETERS ### -Command Specifies an array of command breakpoints that are set on the specified command names. Enter the command names, such as the name of a cmdlet or function. ```yaml Type: System.String[] Parameter Sets: Command Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies the breakpoint IDs that this cmdlet gets. Enter the IDs in a comma-separated list. You can also pipe breakpoint IDs to `Get-PSBreakpoint`. ```yaml Type: System.Int32[] Parameter Sets: Id Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Runspace Specifies the Id of a **Runspace** object so you can interact with breakpoints in the specified runspace. This parameter was added in PowerShell 7.2. ```yaml Type: Runspace Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Script Specifies an array of scripts that contain the breakpoints. Enter the path (optional) and names of one or more script files. If you omit the path, the default location is the current directory. ```yaml Type: System.String[] Parameter Sets: Script, Variable, Command, Type Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Type Specifies an array of breakpoint types that this cmdlet gets. Enter one or more types. The acceptable values for this parameter are: - Line - Command - Variable You can also pipe breakpoint types to `Get-PSBreakpoint`. ```yaml Type: Microsoft.PowerShell.Commands.BreakpointType[] Parameter Sets: Type Aliases: Accepted values: Line, Variable, Command Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Variable Specifies an array of variable breakpoints that are set on the specified variable names. Enter the variable names without dollar signs. ```yaml Type: System.String[] Parameter Sets: Variable Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Int32 You can pipe breakpoint IDs to this cmdlet. ### Microsoft.PowerShell.Commands.BreakpointType You can pipe breakpoint types to this cmdlet. ## OUTPUTS ### System.Management.Automation.CommandBreakpoint ### System.Management.Automation.LineBreakpoint ### System.Management.Automation.VariableBreakpoint ### System.Management.Automation.Breakpoint This cmdlet returns objects that represent the breakpoints in the session. ## NOTES PowerShell includes the following aliases for `Get-PSBreakpoint`: - All platforms: - `gbp` ## RELATED LINKS [Disable-PSBreakpoint](Disable-PSBreakpoint.md) [Enable-PSBreakpoint](Enable-PSBreakpoint.md) [Get-PSCallStack](Get-PSCallStack.md) [Remove-PSBreakpoint](Remove-PSBreakpoint.md) [Set-PSBreakpoint](Set-PSBreakpoint.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-PSCallStack.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 06/28/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-pscallstack?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-PSCallStack --- # Get-PSCallStack ## SYNOPSIS Displays the current call stack. ## SYNTAX ``` Get-PSCallStack [<CommonParameters>] ``` ## DESCRIPTION The `Get-PSCallStack` cmdlet displays the current call stack. Although it is designed to be used with the Windows PowerShell debugger, you can use this cmdlet to display the call stack in a script or function outside of the debugger. To run a `Get-PSCallStack` command while in the debugger, type `k` or `Get-PSCallStack`. ## EXAMPLES ### Example 1: Get the call stack for a function ```powershell PS C:\> function My-Alias { $p = $args[0] Get-Alias | where {$_.Definition -like "*$p"} | Format-Table Definition, Name -Auto } PS C:\ps-test> Set-PSBreakpoint -Command My-Alias Command : My-Alias Action : Enabled : True HitCount : 0 Id : 0 Script : prompt PS C:\> My-Alias Get-Content Entering debug mode. Use h or ? for help. Hit Command breakpoint on 'prompt:My-Alias' My-Alias Get-Content [DBG]: PS C:\ps-test> s $p = $args[0] DEBUG: Stepped to ': $p = $args[0] ' [DBG]: PS C:\ps-test> s Get-Alias | where {$_.Definition -like "*$p*"} | Format-Table Definition, [DBG]: PS C:\ps-test>Get-PSCallStack Name CommandLineParameters UnboundArguments Location ---- --------------------- ---------------- -------- prompt {} {} prompt My-Alias {} {Get-Content} prompt prompt {} {} prompt PS C:\> [DBG]: PS C:\ps-test> o Definition Name ---------- ---- Get-Content gc Get-Content cat Get-Content type ``` This command uses the `Get-PSCallStack` cmdlet to display the call stack for `My-Alias`, a simple function that gets the aliases for a cmdlet name. The first command enters the function at the Windows PowerShell prompt. The second command uses the `Set-PSBreakpoint` cmdlet to set a breakpoint on the `My-Alias` function. The third command uses the `My-Alias` function to get all of the aliases in the current session for the `Get-Content` cmdlet. The debugger breaks in at the function call. Two consecutive `step-into` (`s`) commands begin executing the function line by line. Then, a `Get-PSCallStack` command is used to retrieve the call stack. The final command is a `Step-Out` command (`o`) that exits the debugger and continues executing the script to completion. ## PARAMETERS ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.CallStackFrame This cmdlet returns an object representing the items in the call stack. ## NOTES PowerShell includes the following aliases for `Get-PSCallStack`: - All platforms: - `gcs` ## RELATED LINKS [Disable-PSBreakpoint](Disable-PSBreakpoint.md) [Enable-PSBreakpoint](Enable-PSBreakpoint.md) [Format-Table](Format-Table.md) [Get-PSBreakpoint](Get-PSBreakpoint.md) [Remove-PSBreakpoint](Remove-PSBreakpoint.md) [Set-PSBreakpoint](Set-PSBreakpoint.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-Random.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/11/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-random?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Random --- # Get-Random ## SYNOPSIS Gets a random number, or selects objects randomly from a collection. ## SYNTAX ### RandomNumberParameterSet (Default) ``` Get-Random [-SetSeed <Int32>] [[-Maximum] <Object>] [-Minimum <Object>] [-Count <Int32>] [<CommonParameters>] ``` ### RandomListItemParameterSet ``` Get-Random [-SetSeed <Int32>] [-InputObject] <Object[]> [-Count <Int32>] [<CommonParameters>] ``` ### ShuffleParameterSet ``` Get-Random [-SetSeed <Int32>] [-InputObject] <Object[]> [-Shuffle] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Random` cmdlet gets a randomly selected number. If you submit a collection of objects to `Get-Random`, it gets one or more randomly selected objects from the collection. Without parameters or input, a `Get-Random` command returns a randomly selected 32-bit unsigned integer between 0 (zero) and `[int32]::MaxValue`. You can use the parameters of `Get-Random` to specify the minimum and maximum values, the number of objects returned from a collection, or a seed number. > [!CAUTION] > `Get-Random` doesn't ensure cryptographically secure randomness. The seed value is used for the > current command and for all subsequent `Get-Random` commands in the current session until you use > **SetSeed** again or close the session. You can't reset the seed to its default value. > > Deliberately setting the seed results in non-random, repeatable behavior. It should only be used > when trying to reproduce behavior, such as when debugging or analyzing a script that includes > `Get-Random` commands. Be aware that the seed value could be set by other code in the same > session, such as an imported module. > > PowerShell 7.4 includes [Get-SecureRandom](Get-SecureRandom.md), which ensures cryptographically > secure randomness. ## EXAMPLES ### Example 1: Get a random integer This command gets a random integer between 0 (zero) and **Int32.MaxValue**. ```powershell Get-Random ``` ```Output 3951433 ``` ### Example 2: Get a random integer between 0 and 99 ```powershell Get-Random -Maximum 100 ``` ```Output 47 ``` ### Example 3: Get a random integer between -100 and 99 ```powershell Get-Random -Minimum -100 -Maximum 100 ``` ```Output 56 ``` ### Example 4: Get a random floating-point number This command gets a random floating-point number greater than or equal to 10.7 and less than 20.93. ```powershell Get-Random -Minimum 10.7 -Maximum 20.93 ``` ```Output 18.08467273887 ``` ### Example 5: Get a random integer from an array This command gets a randomly selected number from the specified array. ```powershell 1, 2, 3, 5, 8, 13 | Get-Random ``` ```Output 8 ``` ### Example 6: Get several random integers from an array This command gets three randomly selected numbers in random order from an array. ```powershell 1, 2, 3, 5, 8, 13 | Get-Random -Count 3 ``` ```Output 3 1 13 ``` ### Example 7: Randomize an entire collection Starting in PowerShell 7.1, you can use the **Shuffle** parameter to return the entire collection in a random order. ```powershell 1, 2, 3, 5, 8, 13 | Get-Random -Shuffle ``` ```Output 2 3 5 1 8 13 ``` ### Example 8: Get a random non-numeric value This command returns a random value from a non-numeric collection. ```powershell "red", "yellow", "blue" | Get-Random ``` ```Output yellow ``` ### Example 9: Use the SetSeed parameter This example shows the effect of using the **SetSeed** parameter. Because **SetSeed** produces non-random behavior, it's typically used only to reproduce results, such as when debugging or analyzing a script. ```powershell # Commands with the default seed are pseudorandom Get-Random -Maximum 100 -SetSeed 23 Get-Random -Maximum 100 Get-Random -Maximum 100 Get-Random -Maximum 100 ``` ```Output 32 25 93 95 ``` ```powershell # Commands with the same seed aren't random Get-Random -Maximum 100 -SetSeed 23 Get-Random -Maximum 100 -SetSeed 23 Get-Random -Maximum 100 -SetSeed 23 ``` ```Output 32 32 32 ``` ```powershell # SetSeed results in a repeatable series Get-Random -Maximum 100 -SetSeed 23 Get-Random -Maximum 100 Get-Random -Maximum 100 Get-Random -Maximum 100 ``` ```Output 32 25 93 95 ``` ### Example 10: Get random files These commands get a randomly selected sample of 50 files from the `C:` drive of the local computer. ```powershell $Files = Get-ChildItem -Path C:\* -Recurse $Sample = $Files | Get-Random -Count 50 ``` ### Example 11: Roll fair dice This example rolls a fair die 1200 times and counts the outcomes. The first command, `ForEach-Object` repeats the call to `Get-Random` from the piped in numbers (1-6). The results are grouped by their value with `Group-Object` and formatted as a table with `Select-Object`. ```powershell 1..1200 | ForEach-Object { 1..6 | Get-Random } | Group-Object | Select-Object Name,Count ``` ```Output Name Count ---- ----- 1 206 2 199 3 196 4 226 5 185 6 188 ``` ### Example 12: Use the Count parameter You can now use the **Count** parameter without piping objects to `Get-Random`. The following example gets three random numbers less than 10. ```powershell Get-Random -Count 3 -Maximum 10 ``` ```Output 9 0 8 ``` ### Example 13: Use the InputObject parameter with an empty string or $null In this example, the **InputObject** parameter specifies an array that contains an empty string (`''`) and `$null`. ```powershell Get-Random -InputObject @('a','',$null) ``` `Get-Random` returns either `a`, empty string, or `$null`. The empty string displays as a blank line and `$null` returns to a PowerShell prompt. ## PARAMETERS ### -Count Specifies the number of random objects to return. The default is 1. When used with `InputObject` containing a collection: - Each randomly selected item is returned only once. - If the value of **Count** exceeds the number of objects in the collection, all objects in the collection are returned in random order. ```yaml Type: System.Int32 Parameter Sets: RandomNumberParameterSet, RandomListItemParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies a collection of objects. `Get-Random` gets randomly selected objects in random order from the collection up to the number specified by **Count**. Enter the objects, a variable that contains the objects, or a command or expression that gets the objects. You can also pipe a collection of objects to `Get-Random`. Beginning in PowerShell 7, the **InputObject** parameter accepts arrays that can contain an empty string or `$null`. The array can be sent down the pipeline or as an **InputObject** parameter value. ```yaml Type: System.Object[] Parameter Sets: RandomListItemParameterSet, ShuffleParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Maximum Specifies a maximum value for the random number. `Get-Random` returns a value that's less than the maximum (not equal). Enter an integer, a double-precision floating-point number, or an object that can be converted to an integer or double, such as a numeric string ("100"). The value of **Maximum** must be greater than (not equal to) the value of **Minimum**. If the value of **Maximum** or **Minimum** is a floating-point number, `Get-Random` returns a randomly selected floating-point number. On a 64-bit computer, if the value of **Minimum** is a 32-bit integer, the default value of **Maximum** is **Int32.MaxValue**. If the value of **Minimum** is a double (a floating-point number), the default value of **Maximum** is **Double.MaxValue**. Otherwise, the default value is **Int32.MaxValue**. ```yaml Type: System.Object Parameter Sets: RandomNumberParameterSet Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Minimum Specifies a minimum value for the random number. Enter an integer, a double-precision floating-point number, or an object that can be converted to an integer or double, such as a numeric string ("100"). The default value is 0 (zero). The value of **Minimum** must be less than (not equal to) the value of **Maximum**. If the value of **Maximum** or **Minimum** is a floating-point number, `Get-Random` returns a randomly selected floating-point number. ```yaml Type: System.Object Parameter Sets: RandomNumberParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SetSeed Specifies a seed value for the random number generator. When you use **SetSeed**, the cmdlet generates pseudorandom numbers, which isn't cryptographically secure. > [!CAUTION] > Setting the seed results in non-random behavior. It should only be used when trying to reproduce > behavior, such as when debugging or analyzing a script that includes `Get-Random` commands. > > This seed value is used for the current command and for all subsequent `Get-Random` commands in > the current session until you use **SetSeed** again or close the session. You can't reset the seed > to its default value. ```yaml Type: System.Nullable`1[System.Int32] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Shuffle Returns the entire collection in a randomized order. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ShuffleParameterSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Object You can pipe any object to this cmdlet. It selects values randomly from the piped objects. ## OUTPUTS ### System.Int32 ### System.Int64 ### System.Double ### System.Management.Automation.PSObject This cmdlet returns an integer or floating-point number, or an object selected randomly from a submitted collection. ## NOTES `Get-Random` doesn't always return the same data type as the input value. The following table shows the output type for each of the numeric input types. | Input Type | Output Type | | :--------: | :---------: | | SByte | Double | | Byte | Double | | Int16 | Double | | UInt16 | Double | | Int32 | Int32 | | UInt32 | Double | | Int64 | Int64 | | UInt64 | Double | | Double | Double | | Single | Double | Beginning in Windows PowerShell 3.0, `Get-Random` supports 64-bit integers. In Windows PowerShell 2.0, all values are cast to **System.Int32**. Beginning in PowerShell 7, the **InputObject** parameter in the **RandomListItemParameterSet** parameter set accepts arrays that contain an empty string or `$null`. In earlier PowerShell versions, only the **Maximum** parameter in the **RandomNumberParameterSet** parameter set accepted an empty string or `$null`. ## RELATED LINKS [Get-SecureRandom](Get-SecureRandom.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-Runspace.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-runspace?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Runspace --- # Get-Runspace ## SYNOPSIS Gets active runspaces within a PowerShell host process. ## SYNTAX ### NameParameterSet (Default) ``` Get-Runspace [[-Name] <String[]>] [<CommonParameters>] ``` ### IdParameterSet ``` Get-Runspace [-Id] <Int32[]> [<CommonParameters>] ``` ### InstanceIdParameterSet ``` Get-Runspace [-InstanceId] <Guid[]> [<CommonParameters>] ``` ## DESCRIPTION The `Get-Runspace` cmdlet gets active runspaces in a PowerShell host process. ## EXAMPLES ### Example 1: Get runspaces ```powershell Get-Runspace ``` ```Output Id Name ComputerName Type State Availability -- ---- ------------ ---- ----- ------------ 1 Runspace1 localhost Local Opened Busy 2 Runspace2 localhost Local Opened Available 3 Runspace3 localhost Local Opened Available ``` ### Example 2: Get runspace by Id ```powershell Get-Runspace -Id 2 ``` ```Output Id Name ComputerName Type State Availability -- ---- ------------ ---- ----- ------------ 2 Runspace2 localhost Local Opened Available ``` ### Example 3: Get runspace by Name ```powershell Get-Runspace -Name Runspace1 ``` ```Output Id Name ComputerName Type State Availability -- ---- ------------ ---- ----- ------------ 1 Runspace1 localhost Local Opened Busy ``` ### Example 4: Get runspace by InstanceId In this example, we identify an available runspace using the `Name` parameter and store the return object to the variable `$activeRunspace`. This allows you to use the properties of the **Runspace** in subsequent runs of `Get-Runspace`. ```powershell $activeRunspace = Get-Runspace -Name Runspace1 Get-Runspace -InstanceId $activeRunspace.InstanceId ``` ```Output Id Name ComputerName Type State Availability -- ---- ------------ ---- ----- ------------ 1 Runspace1 localhost Local Opened Busy ``` ## PARAMETERS ### -Id Specifies the Id of a runspace ```yaml Type: System.Int32[] Parameter Sets: IdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InstanceId Specifies the instance ID GUID of a running job. ```yaml Type: System.Guid[] Parameter Sets: InstanceIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies the Name of a runspace ```yaml Type: System.String[] Parameter Sets: NameParameterSet Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ### System.Management.Automation.Runspaces.Runspace This cmdlet returns a **Runspace**. You can pipe the results of a `Get-Runspace` command to `Debug-Runspace`. ## NOTES ## RELATED LINKS [Debug-Runspace](Debug-Runspace.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-RunspaceDebug.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 03/19/2020 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-runspacedebug?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-RunspaceDebug --- # Get-RunspaceDebug ## SYNOPSIS Shows runspace debugging options. ## SYNTAX ### RunspaceNameParameterSet (Default) ``` Get-RunspaceDebug [[-RunspaceName] <String[]>] [<CommonParameters>] ``` ### RunspaceParameterSet ``` Get-RunspaceDebug [-Runspace] <Runspace[]> [<CommonParameters>] ``` ### RunspaceIdParameterSet ``` Get-RunspaceDebug [-RunspaceId] <Int32[]> [<CommonParameters>] ``` ### RunspaceInstanceIdParameterSet ``` Get-RunspaceDebug [-RunspaceInstanceId] <Guid[]> [<CommonParameters>] ``` ### ProcessNameParameterSet ``` Get-RunspaceDebug [[-ProcessName] <String>] [[-AppDomainName] <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-RunspaceDebug` cmdlet shows runspace debugging options. ## EXAMPLES ### 1: Show the state of the default runspace debugger ```powershell Get-RunspaceDebug ``` ```Output Id Name Enabled BreakAll -- ---- ------- -------- 1 Runspace1 False False ``` ## PARAMETERS ### -AppDomainName The name of the application domain that hosts the PowerShell runspace. ```yaml Type: System.String[] Parameter Sets: ProcessNameParameterSet Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProcessName The name of the process that hosts the PowerShell runspace. ```yaml Type: System.String Parameter Sets: ProcessNameParameterSet Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Runspace One or more **Runspace** objects to be disabled. ```yaml Type: System.Management.Automation.Runspaces.Runspace[] Parameter Sets: RunspaceParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -RunspaceId One or more **Runspace** Id numbers to be disabled. ```yaml Type: System.Int32[] Parameter Sets: RunspaceIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RunspaceInstanceId One or more **Runspace** GUIDs to be disabled. ```yaml Type: System.Guid[] Parameter Sets: RunspaceInstanceIdParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RunspaceName One or more **Runspace** names to be disabled. ```yaml Type: System.String[] Parameter Sets: RunspaceNameParameterSet Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ## NOTES ## RELATED LINKS [Disable-RunspaceDebug](Disable-RunspaceDebug.md) [Enable-RunspaceDebug](Enable-RunspaceDebug.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-SecureRandom.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 06/25/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-securerandom?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-SecureRandom --- # Get-SecureRandom ## SYNOPSIS Gets a random number, or selects objects randomly from a collection. ## SYNTAX ### RandomNumberParameterSet (Default) ``` Get-SecureRandom [[-Maximum] <Object>] [-Minimum <Object>] [-Count <Int32>] [<CommonParameters>] ``` ### RandomListItemParameterSet ``` Get-SecureRandom [-InputObject] <Object[]> [-Count <Int32>] [<CommonParameters>] ``` ### ShuffleParameterSet ``` Get-SecureRandom [-InputObject] <Object[]> [-Shuffle] [<CommonParameters>] ``` ## DESCRIPTION The `Get-SecureRandom` cmdlet gets a randomly selected number. If you submit a collection of objects to `Get-SecureRandom`, it gets one or more randomly selected objects from the collection. Without parameters or input, a `Get-SecureRandom` command returns a randomly selected 32-bit unsigned integer between 0 (zero) and `[int32]::MaxValue`. You can use the parameters of `Get-SecureRandom` to specify the minimum and maximum values and the number of objects returned from a collection. `Get-SecureRandom` generates cryptographically secure randomness using the [RandomNumberGenerator](/dotnet/api/system.security.cryptography.randomnumbergenerator) class. ## EXAMPLES ### Example 1: Get a random integer This command gets a random integer between 0 (zero) and **Int32.MaxValue**. ```powershell Get-SecureRandom ``` ```Output 3951433 ``` ### Example 2: Get a random integer between 0 and 99 ```powershell Get-SecureRandom -Maximum 100 ``` ```Output 47 ``` ### Example 3: Get a random integer between -100 and 99 ```powershell Get-SecureRandom -Minimum -100 -Maximum 100 ``` ```Output 56 ``` ### Example 4: Get a random floating-point number This command gets a random floating-point number greater than or equal to 10.7 and less than 20.93. ```powershell Get-SecureRandom -Minimum 10.7 -Maximum 20.93 ``` ```Output 18.08467273887 ``` ### Example 5: Get a random integer from an array This command gets a randomly selected number from the specified array. ```powershell 1, 2, 3, 5, 8, 13 | Get-SecureRandom ``` ```Output 8 ``` ### Example 6: Get several random integers from an array This command gets three randomly selected numbers in random order from an array. ```powershell 1, 2, 3, 5, 8, 13 | Get-SecureRandom -Count 3 ``` ```Output 3 1 13 ``` ### Example 7: Randomize an entire collection You can use the **Shuffle** parameter to return the entire collection in a random order. ```powershell 1, 2, 3, 5, 8, 13 | Get-SecureRandom -Shuffle ``` ```Output 2 3 5 1 8 13 ``` ### Example 8: Get a random non-numeric value This command returns a random value from a non-numeric collection. ```powershell "red", "yellow", "blue" | Get-SecureRandom ``` ```Output yellow ``` ### Example 9: Get random files These commands get a randomly selected sample of 50 files from the `C:` drive of the local computer. ```powershell $Files = Get-ChildItem -Path C:\* -Recurse $Sample = $Files | Get-SecureRandom -Count 50 ``` ### Example 10: Roll fair dice This example rolls a fair die 1200 times and counts the outcomes. The first command, `ForEach-Object` repeats the call to `Get-SecureRandom` from the piped in numbers (1-6). The results are grouped by their value with `Group-Object` and formatted as a table with `Select-Object`. ```powershell 1..1200 | ForEach-Object { 1..6 | Get-SecureRandom } | Group-Object | Select-Object Name,Count ``` ```Output Name Count ---- ----- 1 206 2 199 3 196 4 226 5 185 6 188 ``` ### Example 11: Use the Count parameter You can use the **Count** parameter without piping objects to `Get-SecureRandom`. The following example gets three random numbers less than 10. ```powershell Get-SecureRandom -Count 3 -Maximum 10 ``` ```Output 9 0 8 ``` ### Example 12: Use the InputObject parameter with an empty string or $null In this example, the **InputObject** parameter specifies an array that contains an empty string (`''`) and `$null`. ```powershell Get-SecureRandom -InputObject @('a','',$null) ``` `Get-SecureRandom` returns either `a`, empty string, or `$null`. The empty string displays as a blank line and `$null` returns to a PowerShell prompt. ## PARAMETERS ### -Count Specifies the number of random objects to return. The default is 1. When used with `InputObject` containing a collection: - Each randomly selected item is returned only once. - If the value of **Count** exceeds the number of objects in the collection, all objects in the collection are returned in random order. ```yaml Type: System.Int32 Parameter Sets: RandomNumberParameterSet, RandomListItemParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies a collection of objects. `Get-SecureRandom` gets randomly selected objects in random order from the collection up to the number specified by **Count**. Enter the objects, a variable that contains the objects, or a command or expression that gets the objects. You can also pipe a collection of objects to `Get-SecureRandom`. The **InputObject** parameter accepts arrays that can contain an empty string or `$null`. The array can be sent down the pipeline or as an **InputObject** parameter value. ```yaml Type: System.Object[] Parameter Sets: RandomListItemParameterSet, ShuffleParameterSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Maximum Specifies a maximum value for the random number. `Get-SecureRandom` returns a value that's less than the maximum (not equal). Enter an integer, a double-precision floating-point number, or an object that can be converted to an integer or double, such as a numeric string ("100"). The value of **Maximum** must be greater than (not equal to) the value of **Minimum**. If the value of **Maximum** or **Minimum** is a floating-point number, `Get-SecureRandom` returns a randomly selected floating-point number. On a 64-bit computer, if the value of **Minimum** is a 32-bit integer, the default value of **Maximum** is **Int32.MaxValue**. If the value of **Minimum** is a double (a floating-point number), the default value of **Maximum** is **Double.MaxValue**. Otherwise, the default value is **Int32.MaxValue**. ```yaml Type: System.Object Parameter Sets: RandomNumberParameterSet Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Minimum Specifies a minimum value for the random number. Enter an integer, a double-precision floating-point number, or an object that can be converted to an integer or double, such as a numeric string ("100"). The default value is 0 (zero). The value of **Minimum** must be less than (not equal to) the value of **Maximum**. If the value of **Maximum** or **Minimum** is a floating-point number, `Get-SecureRandom` returns a randomly selected floating-point number. ```yaml Type: System.Object Parameter Sets: RandomNumberParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Shuffle Returns the entire collection in a randomized order. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ShuffleParameterSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Object You can pipe any object to this cmdlet. It selects values randomly from the piped objects. ## OUTPUTS ### System.Int32 ### System.Int64 ### System.Double ### System.Management.Automation.PSObject This cmdlet returns an integer or floating-point number, or an object selected randomly from a submitted collection. ## NOTES `Get-SecureRandom` doesn't always return the same data type as the input value. The following table shows the output type for each of the numeric input types. | Input Type | Output Type | | :--------: | :---------: | | SByte | Double | | Byte | Double | | Int16 | Double | | UInt16 | Double | | Int32 | Int32 | | UInt32 | Double | | Int64 | Int64 | | UInt64 | Double | | Double | Double | | Single | Double | ## RELATED LINKS [Get-Random](Get-Random.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-TraceSource.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-tracesource?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-TraceSource --- # Get-TraceSource ## SYNOPSIS Gets PowerShell components that are instrumented for tracing. ## SYNTAX ``` Get-TraceSource [[-Name] <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-TraceSource` cmdlet gets the trace sources for PowerShell components that are currently in use. You can use the data to determine which PowerShell components you can trace. When tracing, the component generates detailed messages about each step in its internal processing. Developers use the trace data to monitor data flow, program execution, and errors. The tracing cmdlets were designed for PowerShell developers, but they are available to all users. ## EXAMPLES ### Example 1: Get trace sources by name ```powershell Get-TraceSource -Name "*Provider*" ``` This command gets all of the trace sources that have names that include provider. ### Example 2: Get all trace sources ```powershell Get-TraceSource ``` This command gets all of the PowerShell components that can be traced. ## PARAMETERS ### -Name Specifies the trace sources to get. Wildcards are permitted. The parameter name **Name** is optional. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains the name of a trace source to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSTraceSource This cmdlet returns objects representing the trace sources. ## NOTES ## RELATED LINKS [Set-TraceSource](Set-TraceSource.md) [Trace-Command](Trace-Command.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-TypeData.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-typedata?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-TypeData --- # Get-TypeData ## SYNOPSIS Gets the extended type data in the current session. ## SYNTAX ``` Get-TypeData [[-TypeName] <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-TypeData` cmdlet gets the extended type data in the current session. This includes type data that was added to the session by `Types.ps1xml` file and dynamic type data that was added by using the parameter of the `Update-TypeData` cmdlet. You can use the extended type data that `Get-TypeData` returns to examine the type data in the session and send it to the `Update-TypeData` and `Remove-TypeData` cmdlets. Extended type data adds properties and methods to objects in PowerShell. You can use the added properties and methods in the same ways that you would use the properties and methods that are defined in the object type. However, when writing scripts, be aware that the added properties and methods might not be present in every PowerShell session. For more information about `Types.ps1xml` files, see [about_Types.ps1xml](../Microsoft.PowerShell.Core/About/about_Types.ps1xml.md). For more information about dynamic type data that the `Update-TypeData` cmdlet adds, see `Update-TypeData`. This cmdlet was introduced in Windows PowerShell 3.0. ## EXAMPLES ### Example 1: Get all extended type data This example gets all extended type data in the current session. ```powershell Get-TypeData ``` ### Example 2: Get type data by name This example gets all type data in the current session whose name is qualified with "System.IO". ```powershell Get-TypeData -TypeName System.IO.* ``` ```Output TypeName Members -------- ------- System.IO.DirectoryInfo {[Mode, System.Management.Automation.Runspaces.CodePropert System.IO.FileInfo {[Mode, System.Management.Automation.Runspaces.CodePropert ``` ### Example 3: Get the script block that creates a property value This example gets the script block that creates the value of the **EventID** property of **EventLogEntry** objects. ```powershell (Get-TypeData *EventLogEntry*).Members.EventID ``` ```Output GetScriptBlock SetScriptBlock IsHidden Name -------------- -------------- -------- ---- $this.get_EventID() -band 0xFFFF False EventID ``` ### Example 4: Get the script block that defines a property for a specified object This example gets the script block that defines the **DateTime** property of **System.DateTime** objects in PowerShell. ```powershell (Get-TypeData -TypeName System.DateTime).Members["DateTime"].GetScriptBlock if ((& { Set-StrictMode -Version 1; $this.DisplayHint }) -ieq "Date") { "{0}" -f $this.ToLongDateString() } elseif ((& { Set-StrictMode -Version 1; $this.DisplayHint }) -ieq "Time") { "{0}" -f $this.ToLongTimeString() } else { "{0} {1}" -f $this.ToLongDateString(), $this.ToLongTimeString() } ``` The command uses the `Get-TypeData` cmdlet to get the extended type data for the **System.DataTime** type. The command gets the **Members** property of the **TypeData** object. The **Members** property contains a hash table of properties and methods that are defined by extended type data. Each key in the Members hash table is a property or method name and each value is the definition of the property or method value. The command gets the **DateTime** key in **Members** and its **GetScriptBlock** property value. The output shows the script block that creates the value of the **DateTime** property of every **System.DateTime** object in PowerShell. ## PARAMETERS ### -TypeName Specifies type data as an array only for the types with the specified names. By default, `Get-TypeData` gets all types in the session. Enter type names or a name patterns. Full names, or name patterns with wildcard characters are required, even for types in the System namespace. Wildcards are supported and the parameter name **TypeName** is optional. You can also pipe type names to `Get-TypeData`. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe strings containing type names to this cmdlet. ## OUTPUTS ### System.Management.Automation.Runspaces.TypeData ## NOTES `Get-TypeData` gets only the extended type data in the current session. It does not get extended type data that is on the computer, but has not been added to the current session, such as extended types that are defined in modules that have not been imported into the current session. ## RELATED LINKS [about_Types.ps1xml](../Microsoft.PowerShell.Core/About/about_Types.ps1xml.md) [Remove-TypeData](Remove-TypeData.md) [Update-TypeData](Update-TypeData.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-UICulture.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-uiculture?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-UICulture --- # Get-UICulture ## SYNOPSIS Gets the current UI culture settings in the operating system. ## SYNTAX ``` Get-UICulture [<CommonParameters>] ``` ## DESCRIPTION The `Get-UICulture` cmdlet gets information about the current user interface (UI) culture settings for Windows. The UI culture determines which text strings are used for user interface elements, such as menus and messages. You can also use the `Get-Culture` cmdlet, which gets the current culture on the system. The culture determines the display format of items such as numbers, currency, and dates. ## EXAMPLES ### Example 1: Get the UI culture ```powershell Get-UICulture ``` This command gets the current UI culture information. ### Example 2: Get the UI culture and format the results ```powershell Get-UICulture | Format-List * ``` This command displays the values of all of the properties of the current UI culture in a list. ### Example 3: Get the value of the Calendar property ```powershell (Get-UICulture).Calendar ``` This command displays the current values for the Calendar property of the current UI culture. Calendar is just one property of UI culture. To see all of the properties, type `Get-UICulture | Get-Member`. ### Example 4: Get the short date pattern ```powershell (Get-UICulture).DateTimeFormat.ShortDatePattern ``` This command displays the short date pattern for the current UI culture. To see all of the subproperties of the **DateTimeFormat** property of the UI culture, type `(Get-UICulture).DateTimeFormat | Get-Member`. ## PARAMETERS ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Globalization.CultureInfo This cmdlet returns an object representing the current UI culture. In PowerShell 3.0 and later, it returns a **CultureInfo** object. ### Microsoft.PowerShell.VistaCultureInfo In Windows PowerShell 2.0 and earlier, this cmdlet returns a **VistaCultureInfo** object. ## NOTES You can also use the `$PSCulture` and `$PSUICulture` variables. The `$PSCulture` variable stores the name of the current culture, and the `$PSUICulture` variable stores the name of the current UI culture. ## RELATED LINKS

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-Unique.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 08/18/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-unique?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Unique --- # Get-Unique ## SYNOPSIS Returns unique items from a sorted list. ## SYNTAX ### AsString (Default) ``` Get-Unique [-InputObject <PSObject>] [-AsString] [-CaseInsensitive] [<CommonParameters>] ``` ### UniqueByType ``` Get-Unique [-InputObject <PSObject>] [-OnType] [-CaseInsensitive] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Unique` cmdlet compares each item in a sorted list to the next item, eliminates duplicates, and returns only one instance of each item. The list must be sorted for the cmdlet to work properly. By default, `Get-Unique` is case-sensitive. As a result, strings that differ only in character casing are considered to be unique. ## EXAMPLES ### Example 1: Get unique words in a text file These commands find the number of unique words in a text file. ```powershell $A = $( foreach ($line in Get-Content C:\Test1\File1.txt) { $line.ToLower().Split(" ") }) | Sort-Object | Get-Unique $A.Count ``` The first command gets the content of the `File.txt` file. It converts each line of text to lowercase letters and then splits each word onto a separate line at the space (`" "`). Then, it sorts the resulting list alphabetically (the default) and uses the `Get-Unique` cmdlet to eliminate any duplicate words. The results are stored in the `$A` variable. The second command uses the **Count** property of the collection of strings in `$A` to determine how many items are in `$A`. ### Example 2: Get unique integers in an array This command finds the unique members of the set of integers. ```powershell 1,1,1,1,12,23,4,5,4643,5,3,3,3,3,3,3,3 | Sort-Object | Get-Unique ``` ```Output 1 3 4 5 12 23 4643 ``` The first command takes an array of integers typed at the command line, pipes them to the `Sort-Object` cmdlet to be sorted, and then pipes them to `Get-Unique`, which eliminates duplicate entries. ### Example 3: Get unique object types in a directory This command uses the `Get-ChildItem` cmdlet to retrieve the contents of the local directory, which includes files and directories. ```powershell Get-ChildItem | Sort-Object {$_.GetType()} | Get-Unique -OnType ``` The pipeline operator (`|`) sends the results to the `Sort-Object` cmdlet. The `$_.GetType()` statement applies the **GetType** method to each file or directory. Then, `Sort-Object` sorts the items by type. Another pipeline operator sends the results to `Get-Unique`. The **OnType** parameter directs `Get-Unique` to return only one object of each type. ### Example 4: Get unique processes This command gets the names of processes running on the computer with duplicates eliminated. ```powershell Get-Process | Sort-Object | Select-Object ProcessName | Get-Unique -AsString ``` The `Get-Process` command gets all of the processes on the computer. The pipeline operator (`|`) passes the result to `Sort-Object`, which, by default, sorts the processes alphabetically by **ProcessName**. The results are piped to the `Select-Object` cmdlet, which selects only the values of the **ProcessName** property of each object. The results are then piped to `Get-Unique` to eliminate duplicates. The **AsString** parameter tells `Get-Unique` to treat the **ProcessName** values as strings. Without this parameter, `Get-Unique` treats the **ProcessName** values as objects and returns only one instance of the object, that is, the first process name in the list. ### Example 5: Use case-sensitive comparisons to get unique strings This example uses case-insensitive comparisons to get unique strings from an array of strings. ```powershell "aa", "Aa", "Bb", "bb", "aa" | Sort-Object -CaseSensitive | Get-Unique ``` ```Output aa Aa bb Bb ``` ### Example 6: Use case-insensitive comparisons to get unique strings This example uses case-insensitive comparisons to get unique strings from an array of strings. ```powershell "aa", "Aa", "Bb", "bb", "aa" | Sort-Object | Get-Unique -CaseInsensitive ``` ```Output aa Bb ``` ## PARAMETERS ### -AsString Indicates that this cmdlet uses the data as a string. Without this parameter, data is treated as an object, so when you submit a collection of objects of the same type to `Get-Unique`, such as a collection of files, it returns just one (the first). You can use this parameter to find the unique values of object properties, such as the file names. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: AsString Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -CaseInsensitive By default, `Get-Unique` is case-sensitive. When you use this parameter, the cmdlet uses case-insensitive comparisons. This parameter was added in PowerShell 7.4. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies input for `Get-Unique`. Enter a variable that contains the objects or type a command or expression that gets the objects. This cmdlet treats the input submitted using **InputObject** as a collection. It doesn't enumerate individual items in the collection. Because the collection is a single item, input submitted using **InputObject** is always returned unchanged. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -OnType Indicates that this cmdlet returns only one object of each type. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: UniqueByType Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any type of object to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSObject This cmdlet returns its input objects without duplicates. ## NOTES PowerShell includes the following aliases for `Get-Unique`: - All platforms: - `gu` For more information, see [about_Aliases](../Microsoft.PowerShell.Core/About/about_Aliases.md). To sort a list, use `Sort-Object`. You can also use the **Unique** parameter of `Sort-Object` to find the unique items in a list. ## RELATED LINKS [Select-Object](Select-Object.md) [Sort-Object](Sort-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-Uptime.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-uptime?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Uptime --- # Get-Uptime ## SYNOPSIS Get the **TimeSpan** since last boot. ## SYNTAX ### Timespan (Default) ``` Get-Uptime [<CommonParameters>] ``` ### Since ``` Get-Uptime [-Since] [<CommonParameters>] ``` ## DESCRIPTION This cmdlet returns the time elapsed since the last boot of the operating system. The `Get-Uptime` cmdlet was introduced in PowerShell 6.0. ## EXAMPLES ### Example 1 - Show time since last boot ```powershell Get-Uptime ``` ```Output Days : 9 Hours : 0 Minutes : 9 Seconds : 45 Milliseconds : 0 Ticks : 7781850000000 TotalDays : 9.00677083333333 TotalHours : 216.1625 TotalMinutes : 12969.75 TotalSeconds : 778185 TotalMilliseconds : 778185000 ``` ### Example 2 - Show the time of the last boot ```powershell Get-Uptime -Since ``` ```Output Tuesday, June 18, 2019 2:34:56 PM ``` ## PARAMETERS ### -Since Cause the cmdlet to return a **DateTime** object representing the last time that the operating system was booted. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Since Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.TimeSpan By default, this cmdlet returns a **TimeSpan** object representing the elapsed time. ### System.DateTime When you use the **Since** parameter, this cmdlet returns a **DateTime** object representing the last boot time. > [!NOTE] > If Windows fast startup is enabled, Windows does not update the value stored in > **LastBootUpTime**. To disable fast startup, run the following command: `Powercfg -h off`. > > For more information about Windows fast startup, see > [Distinguishing Fast Startup from Wake-from-Hibernation](/windows-hardware/drivers/kernel/distinguishing-fast-startup-from-wake-from-hibernation). ## NOTES On Windows, the value returned is the same as the **LastBootUpTime** property of the **Win32_OperatingSystem** class in WMI. ## RELATED LINKS [Win32_OperatingSystem](/windows/win32/cimwin32prov/win32-operatingsystem#properties)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-Variable.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-variable?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Variable --- # Get-Variable ## SYNOPSIS Gets the variables in the current console. ## SYNTAX ``` Get-Variable [[-Name] <String[]>] [-ValueOnly] [-Include <String[]>] [-Exclude <String[]>] [-Scope <String>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Variable` cmdlet gets the PowerShell variables in the current console. You can retrieve just the values of the variables by specifying the **ValueOnly** parameter, and you can filter the variables returned by name. ## EXAMPLES ### Example 1: Get variables by letter This command gets variables with names that begin with the letter m. The command also gets the value of the variables. ```powershell Get-Variable m* ``` ### Example 2: Get variable values by letter This command gets only the values of the variables that have names that begin with m. ```powershell Get-Variable m* -ValueOnly ``` ### Example 3: Get variables by two letters This command gets information about the variables that begin with either the letter M or the letter P. ```powershell Get-Variable -Include M*,P* ``` ### Example 4: Get variables by scope The first command gets only the variables that are defined in the local scope. It is equivalent to `Get-Variable -Scope Local` and can be abbreviated as `gv -s 0`. The second command uses the `Compare-Object` cmdlet to find the variables that are defined in the parent scope (Scope 1) but are visible only in the local scope (Scope 0). ```powershell Get-Variable -Scope 0 Compare-Object (Get-Variable -Scope 0) (Get-Variable -Scope 1) ``` ## PARAMETERS ### -Exclude Specifies an array of items that this cmdlet excludes from the operation. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Include Specifies an array of items upon which the cmdlet will act, excluding all others. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Name Specifies the name of the variable. Wildcards are permitted. You can also pipe a variable name to `Get-Variable`. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Scope Specifies the variables in the scope.The acceptable values for this parameter are: - **Global** - **Local** - **Script** - A number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent) **Local** is the default. For more information, see [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ValueOnly Indicates that this cmdlet gets only the value of the variable. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string that contains the variable name to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSVariable By default, this cmdlet returns an **AutomationPSVariable** object for each variable that it gets. The object type depends on the variable. ### System.Object[] When you specify the **ValueOnly** parameter and the specified variable's value is a collection, this cmdlet returns a `[System.Object[]]`. This behavior prevents normal pipeline operation from processing the variable's values one at a time. A workaround to force collection enumeration is to enclose the `Get-Variable` command in parentheses. ## NOTES PowerShell includes the following aliases for `Get-Variable`: - All platforms: - `gv` - This cmdlet does not manage environment variables. To manage environment variables, you can use the Environment provider. ## RELATED LINKS [Clear-Variable](Clear-Variable.md) [New-Variable](New-Variable.md) [Remove-Variable](Remove-Variable.md) [Set-Variable](Set-Variable.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Get-Verb.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/get-verb?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-Verb --- # Get-Verb ## SYNOPSIS Gets approved PowerShell verbs. ## SYNTAX ``` Get-Verb [[-Verb] <String[]>] [[-Group] <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-Verb` function gets verbs that are approved for use in PowerShell commands. It's recommended that PowerShell cmdlet and function names have the `Verb-Noun` format and include an approved verb. This practice makes command names more consistent, predictable, and easier to use. Commands that use unapproved verbs, still run in PowerShell. However, when you import a module that includes a command with an unapproved verb in its name, the `Import-Module` command displays a warning message. > [!NOTE] > The verb list that `Get-Verb` returns might not be complete. For an updated list of approved > PowerShell verbs with descriptions, see > [Approved Verbs](/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands). ## EXAMPLES ### Example 1 - Get a list of all verbs ```powershell Get-Verb ``` ### Example 2 - Get a list of approved verbs that begin with "un" ```powershell Get-Verb un* ``` ```Output Verb AliasPrefix Group Description ---- ----------- ----- ----------- Undo un Common Sets a resource to its previous state Unlock uk Common Releases a resource that was locked Unpublish ub Data Makes a resource unavailable to others Uninstall us Lifecycle Removes a resource from an indicated location Unregister ur Lifecycle Removes the entry for a resource from a repository Unblock ul Security Removes restrictions to a resource Unprotect up Security Removes safeguards from a resource that were added to prevent it from attack or loss ``` ### Example 3 - Get all approved verbs in the Security group ```powershell Get-Verb -Group Security ``` ```Output Verb AliasPrefix Group Description ---- ----------- ----- ----------- Block bl Security Restricts access to a resource Grant gr Security Allows access to a resource Protect pt Security Safeguards a resource from attack or loss Revoke rk Security Specifies an action that does not allow access to a resource Unblock ul Security Removes restrictions to a resource Unprotect up Security Removes safeguards from a resource that were added to prevent it from attack or loss ``` ### Example 4 - Finds all commands in a module that have unapproved verbs ```powershell Get-Command -Module Microsoft.PowerShell.Utility | Where-Object Verb -NotIn (Get-Verb).Verb ``` ```Output CommandType Name Version Source ----------- ---- ------- ------ Cmdlet Sort-Object 3.1.0.0 Microsoft.PowerShell.Utility Cmdlet Tee-Object 3.1.0.0 Microsoft.PowerShell.Utility ``` ## PARAMETERS ### -Group Gets only the specified groups. Enter the name of a group. Wildcards aren't allowed. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Accepted values: Common, Communications, Data, Diagnostic, Lifecycle, Other, Security Required: False Position: 1 Default value: All groups Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Verb Gets only the specified verbs. Enter the name of a verb or a name pattern. Wildcards are allowed. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: All verbs Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.VerbInfo ## NOTES PowerShell verbs are assigned to a group based on their most common use. The groups are designed to make the verbs easy to find and compare, not to restrict their use. You can use any approved verb for any type of command. Each PowerShell verb is assigned to one of the following groups. - Common: Define generic actions that can apply to almost any cmdlet, such as Add. - Communications: Define actions that apply to communications, such as Connect. - Data: Define actions that apply to data handling, such as Backup. - Diagnostic: Define actions that apply to diagnostics, such as Debug. - Lifecycle: Define actions that apply to the lifecycle of a cmdlet, such as Complete. - Security: Define actions that apply to security, such as Revoke. - Other: Define other types of actions. Some of the cmdlets installed with PowerShell, such as `Tee-Object` and `Where-Object`, use unapproved verbs. These cmdlets are historic exceptions and their verbs are classified as **reserved**. ## RELATED LINKS [Import-Module](../microsoft.powershell.core/import-module.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Group-Object.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 03/10/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/group-object?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Group-Object --- # Group-Object ## SYNOPSIS Groups objects that contain the same value for specified properties. ## SYNTAX ### HashTable ``` Group-Object [-NoElement] [-AsHashTable] [-AsString] [-InputObject <PSObject>] [[-Property] <Object[]>] [-Culture <String>] [-CaseSensitive] [<CommonParameters>] ``` ## DESCRIPTION The `Group-Object` cmdlet displays objects in groups based on the value of a specified property. `Group-Object` returns a table with one row for each property value and a column that displays the number of items with that value. If you specify more than one property, `Group-Object` first groups them by the values of the first property, and then, within each property group, it groups by the value of the next property. Beginning in PowerShell 7, `Group-Object` can combine the **CaseSensitive** and **AsHashtable** parameters to create a case-sensitive hash table. The hash table keys use case-sensitive comparisons and output a **System.Collections.Hashtable** object. ## EXAMPLES ### Example 1: Group files by extension This example recursively gets the files under `$PSHOME` and groups them by filename extension. The output is sent to the `Sort-Object` cmdlet, which sorts them by the count files found for the given extension. The empty **Name** represents directories. This example uses the **NoElement** parameter to omit the members of the group. ```powershell $files = Get-ChildItem -Path $PSHOME -Recurse $files | Group-Object -Property Extension -NoElement | Sort-Object -Property Count -Descending ``` ```Output Count Name ----- ---- 365 .xml 231 .cdxml 197 169 .ps1xml 142 .txt 114 .psd1 63 .psm1 49 .xsd 36 .dll 15 .mfl 15 .mof ... ``` ### Example 2: Group integers by odds and evens This example shows how to use script blocks as the value of the **Property** parameter. This command displays the integers from 1 to 20, grouped by odds and even. ```powershell 1..20 | Group-Object -Property {$_ % 2} ``` ```Output Count Name Group ----- ---- ----- 10 0 {2, 4, 6, 8...} 10 1 {1, 3, 5, 7...} ``` ### Example 3: Group hashtables by key value Beginning in PowerShell 6, `Group-Object` supports sorting of **hashtable** input by key values. The following example groups an array of hashtables by the value of each hashtable's `weight` key. This example uses the **NoElement** parameter to omit the members of the group. ```powershell @( @{ name = 'a' ; weight = 7 } @{ name = 'b' ; weight = 1 } @{ name = 'c' ; weight = 3 } @{ name = 'd' ; weight = 7 } ) | Group-Object -Property weight -NoElement ``` ```output Count Name ----- ---- 1 1 1 3 2 7 ``` ### Example 4: Group event log events by EntryType This example displays the 1,000 most recent entries in the System event log, grouped by **EntryType**. In the output, the **Count** column represents the number of entries in each group. The **Name** column represents the **EventType** values that define a group. The **Group** column represents the objects in each group. ```powershell Get-WinEvent -LogName System -MaxEvents 1000 | Group-Object -Property LevelDisplayName ``` ```Output Count Name Group ----- ---- ----- 153 Error {System.Diagnostics.Eventing.Reader.EventLogRecord, System.Diag...} 722 Information {System.Diagnostics.Eventing.Reader.EventLogRecord, System.Diag...} 125 Warning {System.Diagnostics.Eventing.Reader.EventLogRecord, System.Diag...} ``` ### Example 5: Group processes by priority class This example demonstrates the effect of the **NoElement** parameter. These commands group the processes on the computer by priority class. The first command uses the `Get-Process` cmdlet to get the processes on the computer and sends the objects down the pipeline. `Group-Object`groups the objects by the value of the **PriorityClass** property of the process. The second example uses the **NoElement** parameter to remove the members of the group from the output. The result is a table with only the **Count** and **Name** property value. The results are shown in the following sample output. ```powershell Get-Process | Group-Object -Property PriorityClass ``` ```Output Count Name Group ----- ---- ----- 55 Normal {System.Diagnostics.Process (AdtAgent), System.Diagnosti... 1 {System.Diagnostics.Process (Idle)} 3 High {System.Diagnostics.Process (Newproc), System.Diagnostic... 2 BelowNormal {System.Diagnostics.Process (winperf), ``` ```powershell Get-Process | Group-Object -Property PriorityClass -NoElement ``` ```Output Count Name ----- ---- 55 Normal 1 3 High 2 BelowNormal ``` ### Example 6: Group processes by name The following example uses `Group-Object` to group multiple instances of processes running on the local computer. `Where-Object` displays processes with more than one instance. ```powershell Get-Process | Group-Object -Property Name -NoElement | Where-Object {$_.Count -gt 1} ``` ```Output Count Name ----- ---- 2 csrss 5 svchost 2 winlogon 2 wmiprvse ``` ### Example 7: Group objects in a hash table This example uses the **AsHashTable** and **AsString** parameters to return the groups in a hash table, as a collection of key-value pairs. In the resulting hash table, each property value is a key, and the group elements are the values. Because each key is a property of the hash table object, you can use dot notation to display the values. The first command gets the `Get` and `Set` cmdlets in the session, groups them by verb, returns the groups as a hash table, and saves the hash table in the `$A` variable. The second command displays the hash table in `$A`. There are two key-value pairs, one for the `Get` cmdlets and one for the `Set` cmdlets. The third command uses dot notation, `$A.Get` to display the values of the **Get** key in `$A`. The values are **CmdletInfo** object. The **AsString** parameter doesn't convert the objects in the groups to strings. ```powershell $A = Get-Command Get-*, Set-* -CommandType Cmdlet | Group-Object -Property Verb -AsHashTable -AsString $A ``` ```Output Name Value ---- ----- Get {Get-Acl, Get-Alias, Get-AppLockerFileInformation, Get-AppLockerPolicy...} Set {Set-Acl, Set-Alias, Set-AppBackgroundTaskResourcePolicy, Set-AppLockerPolicy...} ``` ```powershell $A.Get ``` ```Output CommandType Name Version Source ----------- ---- ------- ------ Cmdlet Get-Acl 7.0.0.0 Microsoft.PowerShell.Security Cmdlet Get-Alias 7.0.0.0 Microsoft.PowerShell.Utility Cmdlet Get-AppLockerFileInformation 2.0.0.0 AppLocker Cmdlet Get-AppLockerPolicy 2.0.0.0 AppLocker ... ``` ### Example 8: Create a case-sensitive hash table This example combines the **CaseSensitive** and **AsHashTable** parameters to create a case-sensitive hash table. The files in the example have extensions of `.txt` and `.TXT`. ```powershell $hash = Get-ChildItem -Path C:\Files | Group-Object -Property Extension -CaseSensitive -AsHashTable $hash ``` ```Output Name Value ---- ----- .TXT {C:\Files\File7.TXT, C:\Files\File8.TXT, C:\Files\File9.TXT} .txt {C:\Files\file1.txt, C:\Files\file2.txt, C:\Files\file3.txt} ``` The `$hash` variable stores the **System.Collections.Hashtable** object. `Get-ChildItem` gets the file names from the `C:\Files` directory and sends the **System.IO.FileInfo** objects down the pipeline. `Group-Object` groups the objects using the **Property** value **Extension**. The **CaseSensitive** and **AsHashTable** parameters create the hash table and the keys are grouped using the case-sensitive keys `.txt` and `.TXT`. ## PARAMETERS ### -AsHashTable Indicates that this cmdlet returns the group as a hash table. The keys of the hash table are the property values by which the objects are grouped. The values of the hash table are the objects that have that property value. By itself, the **AsHashTable** parameter returns each hash table in which each key is an instance of the grouped object. When used with the **AsString** parameter, the keys in the hash table are strings. Beginning in PowerShell 7, to create case-sensitive hash tables, include **CaseSensitive** and **AsHashtable** in your command. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: AHT Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -AsString Indicates that this cmdlet converts the hash table keys to strings. By default, the hash table keys are instances of the grouped object. This parameter is valid only when used with the **AsHashTable** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -CaseSensitive Indicates that this cmdlet makes the grouping case-sensitive. Without this parameter, the property values of objects in a group might have different cases. Beginning in PowerShell 7, to create case-sensitive hash tables, include **CaseSensitive** and **AsHashtable** in your command. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Culture Specifies the culture to use when comparing strings. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects to group. Enter a variable that contains the objects, or type a command or expression that gets the objects. When you use the **InputObject** parameter to submit a collection of objects to `Group-Object`, `Group-Object` receives one object that represents the collection. As a result, it creates a single group with that object as its member. To group the objects in a collection, pipe the objects to `Group-Object`. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -NoElement Indicates that this cmdlet omits the members of a group from the results. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Property Specifies the properties for grouping. The objects are arranged into named groups based on the value of the specified properties. When no property is specified, objects are grouped by their value or the `ToString()` representation of their value. The output is sorted in ascending order by the group names. The value of the **Property** parameter can be a new calculated property. The calculated property can be a script block or a hash table. Valid key-value pairs are: - Expression - `<string>` or `<script block>` For more information, see [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.GroupInfo By default, this cmdlet returns a **GroupInfo** object. ### System.Collections.Hashtable When you use the **AsHashTable** parameter, this cmdlet returns a **Hashtable** object. ## NOTES PowerShell includes the following aliases for `Group-Object`: - All platforms: - `group` You can use the **GroupBy** parameter of the formatting cmdlets, such as `Format-Table` and `Format-List`, to group objects. Unlike `Group-Object`, which creates a single table with a row for each property value, the **GroupBy** parameters create a table for each property value with a row for each item that has the property value. `Group-Object` doesn't require that the objects being grouped are of the same Microsoft .NET type. When grouping objects of different .NET types, `Group-Object` uses the following rules: - Same Property Names and Types. If the objects have a property with the specified name, and the property values have the same .NET type, the property values are grouped by the same rules that would be used for objects of the same type. - Same Property Names, Different Types. If the objects have a property with the specified name, but the property values have a different .NET type in different objects, `Group-Object` uses the .NET type of the first occurrence of the property as the .NET type for that property group. When an object has a property with a different type, the property value is converted to the type for that group. If the type conversion fails, the object isn't included in the group. - Missing Properties. Objects that don't have a specified property can't be grouped. Objects that aren't grouped appear in the final **GroupInfo** object output in a group named `AutomationNull.Value`. The output is sorted in ascending order by the group names. The items belonging to each group are not sorted. They are listed in the order in which they were received. ## RELATED LINKS [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md) [about_Hash_Tables](../Microsoft.PowerShell.Core/About/about_Hash_Tables.md) [Compare-Object](Compare-Object.md) [ForEach-Object](../Microsoft.PowerShell.Core/ForEach-Object.md) [Measure-Object](Measure-Object.md) [New-Object](New-Object.md) [Select-Object](Select-Object.md) [Sort-Object](Sort-Object.md) [Tee-Object](Tee-Object.md) [Where-Object](../Microsoft.PowerShell.Core/Where-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Import-Alias.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/import-alias?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Import-Alias --- # Import-Alias ## SYNOPSIS Imports an alias list from a file. ## SYNTAX ### ByPath (Default) ``` Import-Alias [-Path] <String> [-Scope <String>] [-PassThru] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ByLiteralPath ``` Import-Alias -LiteralPath <String> [-Scope <String>] [-PassThru] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Import-Alias` cmdlet imports an alias list from a file. Beginning in Windows PowerShell 3.0, as a security feature, `Import-Alias` does not overwrite existing aliases by default. To overwrite an existing alias, after assuring that the contents of the alias file is safe, use the **Force** parameter. ## EXAMPLES ### Example 1: Import aliases from a file ```powershell Import-Alias test.txt ``` This command imports alias information from a file named test.txt. ## PARAMETERS ### -Force Allows the cmdlet to import an alias that is already defined or is read only. You can use the following command to display information about the currently-defined aliases: `Get-Alias | Select-Object Name, Options` If the corresponding alias is read-only, it will be displayed in the value of the **Options** property. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to a file that includes exported alias information. Unlike the **Path** parameter, the value of the **LiteralPath** parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String Parameter Sets: ByLiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to a file that includes exported alias information. Wildcards are allowed but they must resolve to a single name. ```yaml Type: System.String Parameter Sets: ByPath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Scope Specifies the scope into which the aliases are imported. The acceptable values for this parameter are: - Global - Local - Script - A number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent) The default is Local. For more information, see [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.AliasInfo When you use the **PassThru** parameter, this cmdlet returns an **AliasInfo** object representing the alias. ## NOTES PowerShell includes the following aliases for `Import-Alias`: - All platforms: - `ipal` ## RELATED LINKS [Export-Alias](Export-Alias.md) [Get-Alias](Get-Alias.md) [New-Alias](New-Alias.md) [Set-Alias](Set-Alias.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Import-Clixml.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/31/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/import-clixml?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Import-Clixml --- # Import-Clixml ## SYNOPSIS Imports a CLIXML file and creates corresponding objects in PowerShell. ## SYNTAX ### ByPath (Default) ``` Import-Clixml [-Path] <String[]> [-IncludeTotalCount] [-Skip <UInt64>] [-First <UInt64>] [<CommonParameters>] ``` ### ByLiteralPath ``` Import-Clixml -LiteralPath <String[]> [-IncludeTotalCount] [-Skip <UInt64>] [-First <UInt64>] [<CommonParameters>] ``` ## DESCRIPTION The `Import-Clixml` cmdlet imports objects that have been serialized into a Common Language Infrastructure (CLI) XML file. A valuable use of `Import-Clixml` on Windows computers is to import credentials and secure strings that were exported as secure XML using `Export-Clixml`. [Example #2](#example-2-import-a-secure-credential-object) shows how to use `Import-Clixml` to import a secure credential object. The CLIXML data is deserialized back into PowerShell objects. However, the deserialized objects aren't a live objects. They are a snapshot of the objects at the time of serialization. The deserialized objects include properties but no methods. The **TypeNames** property contains the original type name prefixed with `Deserialized`. [Example #3](#example-3-inspect-the-typenames-property-of-a-deserialized-object) show the **TypeNames** property of a deserialized object. `Import-Clixml` uses the byte-order-mark (BOM) to detect the encoding format of the file. If the file has no BOM, it assumes the encoding is UTF8. For more information about CLI, see [Language independence](/dotnet/standard/language-independence). ## EXAMPLES ### Example 1: Import a serialized file and recreate an object This example uses the `Export-Clixml` cmdlet to save a serialized copy of the process information returned by `Get-Process`. `Import-Clixml` retrieves the serialized file's contents and recreates an object that is stored in the `$Processes` variable. ```powershell Get-Process | Export-Clixml -Path .\pi.xml $Processes = Import-Clixml -Path .\pi.xml ``` ### Example 2: Import a secure credential object In this example, given a credential that you've stored in the `$Credential` variable by running the `Get-Credential` cmdlet, you can run the `Export-Clixml` cmdlet to save the credential to disk. > [!IMPORTANT] > `Export-Clixml` only exports encrypted credentials on Windows. On non-Windows operating systems > such as macOS and Linux, credentials are exported in plain text. ```powershell $Credxmlpath = Join-Path (Split-Path $PROFILE) TestScript.ps1.credential $Credential | Export-Clixml $Credxmlpath $Credxmlpath = Join-Path (Split-Path $PROFILE) TestScript.ps1.credential $Credential = Import-Clixml $Credxmlpath ``` The `Export-Clixml` cmdlet encrypts credential objects by using the Windows [Data Protection API](/previous-versions/windows/apps/hh464970(v=win.10)). The encryption ensures that only your user account can decrypt the contents of the credential object. The exported `CLIXML` file can't be used on a different computer or by a different user. In the example, the file in which the credential is stored is represented by `TestScript.ps1.credential`. Replace **TestScript** with the name of the script with which you're loading the credential. You send the credential object down the pipeline to `Export-Clixml`, and save it to the path, `$Credxmlpath`, that you specified in the first command. To import the credential automatically into your script, run the final two commands. Run `Import-Clixml` to import the secured credential object into your script. This import eliminates the risk of exposing plain-text passwords in your script. ### Example 3: Inspect the TypeNames property of a deserialized object This example shows importing an object stored as CLIXML data. The data is deserialized back into a PowerShell object. However, the deserialized object aren't a live objects. They are a snapshot of the objects at the time of serialization. The deserialized objects include properties but no methods. ```powershell $original = [pscustomobject] @{ Timestamp = Get-Date Label = 'Meeting event' } $original | Add-Member -MemberType ScriptMethod -Name GetDisplay -Value { '{0:yyyy-MM-dd HH:mm} {1}' -f $this.Timestamp, $this.Label } $original | Get-Member -MemberType ScriptMethod ``` ```Output 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() Label NoteProperty string Label=Meeting event Timestamp NoteProperty System.DateTime Timestamp=1/31/2024 2:27:59 PM GetDisplay ScriptMethod System.Object GetDisplay(); ``` ```powershell $original | Export-Clixml -Path event.clixml $deserialized = Import-CliXml -Path event.clixml $deserialized | Get-Member ``` ```Output TypeName: Deserialized.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() Label NoteProperty string Label=Meeting event Timestamp NoteProperty System.DateTime Timestamp=1/31/2024 2:27:59 PM ``` Note that the type of the object in `$original` is **System.Management.Automation.PSCustomObject**, but the type of the object in `$deserialized` is **Deserialized.System.Management.Automation.PSCustomObject**. Also, the `GetDisplay()` method is missing from the deserialized object. ## PARAMETERS ### -First Gets only the specified number of objects. Enter the number of objects to get. ```yaml Type: System.UInt64 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -IncludeTotalCount Reports the total number of objects in the data set followed by the selected objects. If the cmdlet can't determine the total count, it displays **Unknown total count**. The integer has an **Accuracy** property that indicates the reliability of the total count value. The value of **Accuracy** ranges from `0.0` to `1.0` where `0.0` means that the cmdlet couldn't count the objects, `1.0` means that the count is exact, and a value between `0.0` and `1.0` indicates an increasingly reliable estimate. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to the XML files. Unlike **Path**, the value of the **LiteralPath** parameter is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: ByLiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the path to the XML files. ```yaml Type: System.String[] Parameter Sets: ByPath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Skip Ignores the specified number of objects and then gets the remaining objects. Enter the number of objects to skip. ```yaml Type: System.UInt64 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string containing a path to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSObject This cmdlet returns objects that were deserialized from the stored XML files. ## NOTES When specifying multiple values for a parameter, use commas to separate the values. For example, `<parameter-name> <value1>, <value2>`. ## RELATED LINKS [Export-Clixml](Export-Clixml.md) [Introducing XML Serialization](/dotnet/standard/serialization/introducing-xml-serialization) [Join-Path](../Microsoft.PowerShell.Management/Join-Path.md) [Securely Store Credentials on Disk](https://powershellcookbook.com/recipe/PukO/securely-store-credentials-on-disk) [Use PowerShell to Pass Credentials to Legacy Systems](https://devblogs.microsoft.com/scripting/use-powershell-to-pass-credentials-to-legacy-systems/)

#File: reference/7.6/Microsoft.PowerShell.Utility/Import-Csv.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/09/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/import-csv?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Import-Csv --- # Import-Csv ## SYNOPSIS Creates table-like custom objects from the items in a character-separated value (CSV) file. ## SYNTAX ### DelimiterPath (Default) ``` Import-Csv [[-Delimiter] <Char>] [-Path] <String[]> [-Header <String[]>] [-Encoding <Encoding>] [<CommonParameters>] ``` ### DelimiterLiteralPath ``` Import-Csv [[-Delimiter] <Char>] -LiteralPath <String[]> [-Header <String[]>] [-Encoding <Encoding>] [<CommonParameters>] ``` ### CulturePath ``` Import-Csv [-Path] <String[]> -UseCulture [-Header <String[]>] [-Encoding <Encoding>] [<CommonParameters>] ``` ### CultureLiteralPath ``` Import-Csv -LiteralPath <String[]> -UseCulture [-Header <String[]>] [-Encoding <Encoding>] [<CommonParameters>] ``` ## DESCRIPTION The `Import-Csv` cmdlet creates table-like custom objects from the items in CSV files. Each column in the CSV file becomes a property of the custom object and the items in rows become the property values. `Import-Csv` works on any CSV file, including files that are generated by the `Export-Csv` cmdlet. You can use the parameters of the `Import-Csv` cmdlet to specify the column header row and the item delimiter, or direct `Import-Csv` to use the list separator for the current culture as the item delimiter. You can also use the `ConvertTo-Csv` and `ConvertFrom-Csv` cmdlets to convert objects to CSV strings (and back). These cmdlets are the same as the `Export-Csv` and `Import-Csv` cmdlets, except that they work with data from the pipeline instead of from files. If a header row entry in a CSV file contains an empty or null value, PowerShell inserts a default header row name and displays a warning message. Starting with PowerShell 6.0, `Import-Csv` now supports the W3C Extended Log File Format. ## EXAMPLES ### Example 1: Import process objects This example shows how to export and then import a CSV file of process objects. ```powershell Get-Process | Export-Csv -Path .\Processes.csv $P = Import-Csv -Path .\Processes.csv $P | Get-Member ``` ```Output 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() BasePriority NoteProperty string BasePriority=8 Company NoteProperty string Company=Microsoft Corporation ... ``` ```powershell $P | Format-Table ``` ```Output Name SI Handles VM WS PM NPM Path ---- -- ------- -- -- -- --- ---- ApplicationFrameHost 4 407 2199293489152 15884288 15151104 23792 C:\WINDOWS\system32\ApplicationFrameHost.exe ... wininit 0 157 2199112204288 4591616 1630208 10376 winlogon 4 233 2199125549056 7659520 2826240 10992 C:\WINDOWS\System32\WinLogon.exe WinStore.App 4 846 873435136 33652736 26607616 55432 C:\Program Files\WindowsApps\Microsoft.WindowsStore_11712.1001.13.0_x64__8weky... WmiPrvSE 0 201 2199100219392 8830976 3297280 10632 C:\WINDOWS\system32\wbem\wmiprvse.exe WmiPrvSE 0 407 2199157727232 18509824 12922880 16624 C:\WINDOWS\system32\wbem\wmiprvse.exe WUDFHost 0 834 2199310204928 51945472 87441408 24984 C:\Windows\System32\WUDFHost.exe ``` The `Get-Process` cmdlet sends process objects down the pipeline to the `Export-Csv`. The `Export-Csv` cmdlet converts the process objects to CSV strings and saves the strings in the Processes.csv file. The `Import-Csv` cmdlet imports the CSV strings from the Processes.csv file. The strings are saved in the `$P` variable. The `$P` variable is sent down the pipeline to the `Get-Member` cmdlet that displays the properties of the imported CSV strings. The `$P` variable is sent down the pipeline to the `Format-Table` cmdlet and displays the objects. ### Example 2: Specify the delimiter This example shows how to use the **Delimiter** parameter of the `Import-Csv` cmdlet. ```powershell Get-Process | Export-Csv -Path .\Processes.csv -Delimiter : $P = Import-Csv -Path .\Processes.csv -Delimiter : $P | Format-Table ``` The `Get-Process` cmdlet sends process objects down the pipeline to `Export-Csv`. The `Export-Csv` cmdlet converts the process objects to CSV strings and saves the strings in the Processes.csv file. The **Delimiter** parameter is used to specify a colon delimiter. The `Import-Csv` cmdlet imports the CSV strings from the Processes.csv file. The strings are saved in the `$P` variable. To `$P` variable is sent down the pipeline to the `Format-Table` cmdlet. ### Example 3: Specify the current culture for the delimiter This example shows how to use the `Import-Csv` cmdlet with the **UseCulture** parameter. ```powershell (Get-Culture).TextInfo.ListSeparator Get-Process | Export-Csv -Path .\Processes.csv -UseCulture Import-Csv -Path .\Processes.csv -UseCulture ``` The `Get-Culture` cmdlet uses the nested properties **TextInfo** and **ListSeparator** to get the current culture's default list separator. The `Get-Process` cmdlet sends process objects down the pipeline to `Export-Csv`. The `Export-Csv` cmdlet converts the process objects to CSV strings and saves the strings in the Processes.csv file. The **UseCulture** parameter uses the current culture's default list separator. The `Import-Csv` cmdlet imports the CSV strings from the Processes.csv file. ### Example 4: Change property names in an imported object This example shows how to use the **Header** parameter of `Import-Csv` to change the names of properties in the resulting imported object. ```powershell Start-Job -ScriptBlock { Get-Process } | Export-Csv -Path .\Jobs.csv -NoTypeInformation $Header = 'State', 'MoreData', 'StatusMessage', 'Location', 'Command', 'StateInfo', 'Finished', 'InstanceId', 'Id', 'Name', 'ChildJobs', 'BeginTime', 'EndTime', 'JobType', 'Output', 'Error', 'Progress', 'Verbose', 'Debug', 'Warning', 'Information' # Delete the default header from file $A = Get-Content -Path .\Jobs.csv $A = $A[1..($A.Count - 1)] $A | Out-File -FilePath .\Jobs.csv $J = Import-Csv -Path .\Jobs.csv -Header $Header $J ``` ```Output State : Running MoreData : True StatusMessage : Location : localhost Command : Get-Process StateInfo : Running Finished : System.Threading.ManualResetEvent InstanceId : a259eb63-6824-4b97-a033-305108ae1c2e Id : 1 Name : Job1 ChildJobs : System.Collections.Generic.List`1[System.Management.Automation.Job] BeginTime : 12/20/2018 18:59:57 EndTime : JobType : BackgroundJob Output : System.Management.Automation.PSDataCollection`1[System.Management.Automation.PSObject] Error : System.Management.Automation.PSDataCollection`1[System.Management.Automation.ErrorRecord] Progress : System.Management.Automation.PSDataCollection`1[System.Management.Automation.ProgressRecord] Verbose : System.Management.Automation.PSDataCollection`1[System.Management.Automation.VerboseRecord] Debug : System.Management.Automation.PSDataCollection`1[System.Management.Automation.DebugRecord] Warning : System.Management.Automation.PSDataCollection`1[System.Management.Automation.WarningRecord] Information : System.Management.Automation.PSDataCollection`1[System.Management.Automation.InformationRecord] ``` The `Start-Job` cmdlet starts a background job that runs `Get-Process`. A job object is sent down the pipeline to the `Export-Csv` cmdlet and converted to a CSV string. The **NoTypeInformation** parameter removes the type information header from CSV output and is optional in PowerShell v6 and higher. The `$Header` variable contains a custom header that replaces the following default values: **HasMoreData**, **JobStateInfo**, **PSBeginTime**, **PSEndTime**, and **PSJobTypeName**. The `$A` variable uses the `Get-Content` cmdlet to get the CSV string from the Jobs.csv file. The `$A` variable is used to remove the default header from the file. The `Out-File` cmdlet saves the new version of the Jobs.csv file in the `$A` variable. The `Import-Csv` cmdlet imports the Jobs.csv file and uses the **Header** parameter to apply the `$Header` variable. The `$J` variable contains the imported **PSCustomObject** and displays the object in the PowerShell console. ### Example 5: Create a custom object using a CSV file This example shows how to create a custom object in PowerShell by using a CSV file. ```powershell Get-Content -Path .\Links.csv ``` ```Output 113207,about_Aliases 113208,about_Arithmetic_Operators 113209,about_Arrays 113210,about_Assignment_Operators 113212,about_Automatic_Variables 113213,about_Break 113214,about_Command_Precedence 113215,about_Command_Syntax 144309,about_Comment_Based_Help 113216,about_CommonParameters 113217,about_Comparison_Operators 113218,about_Continue 113219,about_Core_Commands 113220,about_Data_Section ``` ```powershell $A = Import-Csv -Path .\Links.csv -Header 'LinkID', 'TopicTitle' $A | Get-Member ``` ```Output 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() LinkID NoteProperty string LinkID=113207 TopicTitle NoteProperty string TopicTitle=about_Aliases ``` ```powershell $A | Where-Object -Property TopicTitle -Like '*alias*' ``` ```Output LinkID TopicTitle ------ ---------- 113207 about_Aliases ``` To create your Links.csv file, use the values shown in the `Get-Content` output. The `Get-Content` cmdlet displays the Links.csv file. The `Import-Csv` cmdlet imports the Links.csv file. The **Header** parameter specifies the property names **LinkId** and **TopicTitle**. The objects are stored in the `$A` variable. The `Get-Member` cmdlet shows the property names from the **Header** parameter. The `Where-Object` cmdlet selects objects with the **TopicTitle** property that includes **alias**. ### Example 6: Import a CSV that's missing a value This example shows how the `Import-Csv` cmdlet in PowerShell responds when the header row in a CSV file includes a null or empty value. `Import-Csv` substitutes a default name for the missing header row that becomes the property name of the object that `Import-Csv` returns. ```powershell Get-Content -Path .\Projects.csv ``` ```Output ProjectID,ProjectName,,Completed 13,Inventory,Redmond,True 440,,FarEast,True 469,Marketing,Europe,False ``` ```powershell Import-Csv -Path .\Projects.csv ``` ```Output WARNING: One or more headers weren't specified. Default names starting with "H" have been used in place of any missing headers. ProjectID ProjectName H1 Completed --------- ----------- -- --------- 13 Inventory Redmond True 440 FarEast True 469 Marketing Europe False ``` The `Get-Content` cmdlet displays the `Projects.csv` file. The header row is missing a value between **ProjectName** and **Completed**. The `Import-Csv` cmdlet imports the `Projects.csv` file and displays a warning message because **H1** is a default header name. ## PARAMETERS ### -Delimiter Specifies the delimiter that separates the property values in the CSV file. The default is a comma (`,`). Enter a character, such as a colon (`:`). To specify a semicolon (`;`) enclose it in single quotation marks. To specify escaped special characters such as tab (`` `t ``), enclose it in double quotation marks. If you specify a character other than the actual string delimiter in the file, `Import-Csv` can't create the objects from the CSV strings and returns the full CSV strings. ```yaml Type: System.Char Parameter Sets: DelimiterPath, DelimiterLiteralPath Aliases: Required: False Position: 1 Default value: comma (,) Accept pipeline input: False Accept wildcard characters: False ``` ### -Encoding Specifies the encoding for the imported CSV file. The default value is `utf8NoBOM`. The acceptable values for this parameter are as follows: - `ascii`: Uses the encoding for the ASCII (7-bit) character set. - `ansi`: Uses the encoding for the for the current culture's ANSI code page. This option was added in PowerShell 7.4. - `bigendianunicode`: Encodes in UTF-16 format using the big-endian byte order. - `bigendianutf32`: Encodes in UTF-32 format using the big-endian byte order. - `oem`: Uses the default encoding for MS-DOS and console programs. - `unicode`: Encodes in UTF-16 format using the little-endian byte order. - `utf7`: Encodes in UTF-7 format. - `utf8`: Encodes in UTF-8 format. - `utf8BOM`: Encodes in UTF-8 format with Byte Order Mark (BOM) - `utf8NoBOM`: Encodes in UTF-8 format without Byte Order Mark (BOM) - `utf32`: Encodes in UTF-32 format. Beginning with PowerShell 6.2, the **Encoding** parameter also allows numeric IDs of registered code pages (like `-Encoding 1251`) or string names of registered code pages (like `-Encoding "windows-1251"`). For more information, see the .NET documentation for [Encoding.CodePage](/dotnet/api/system.text.encoding.codepage?view=netcore-2.2). Starting with PowerShell 7.4, you can use the `Ansi` value for the **Encoding** parameter to pass the numeric ID for the current culture's ANSI code page without having to specify it manually. > [!NOTE] > **UTF-7*** is no longer recommended to use. As of PowerShell 7.1, a warning is written if you > specify `utf7` for the **Encoding** parameter. ```yaml Type: System.Text.Encoding Parameter Sets: (All) Aliases: Accepted values: ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 Required: False Position: Named Default value: UTF8NoBOM Accept pipeline input: False Accept wildcard characters: False ``` ### -Header Specifies an alternate column header row for the imported file. The column header determines the property names of the objects created by `Import-Csv`. Enter column headers as a character-separated list. Don't enclose the header string in quotation marks. Enclose each column header in single quotation marks. If you enter fewer column headers than there are data columns, the remaining data columns are discarded. If you enter more column headers than there are data columns, the additional column headers are created with empty data columns. When using the **Header** parameter, delete the original header row from the CSV file. Otherwise, `Import-Csv` creates an extra object from the items in the header row. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to the CSV file to import. Unlike **Path**, the value of the **LiteralPath** parameter is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: DelimiterLiteralPath, CultureLiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the path to the CSV file to import. You can also pipe a path to `Import-Csv`. ```yaml Type: System.String[] Parameter Sets: DelimiterPath, CulturePath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -UseCulture Uses the list separator for the current culture as the item delimiter. To find the list separator for a culture, use the following command: `(Get-Culture).TextInfo.ListSeparator`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: CulturePath, CultureLiteralPath Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a path to this cmdlet. ## OUTPUTS ### System.Object This cmdlet returns the objects described by the content in the CSV file. ## NOTES PowerShell includes the following aliases for `Import-Csv`: - All platforms: - `ipcsv` Because the imported objects are CSV versions of the object type, they're not recognized and formatted by the PowerShell type formatting entries that format the non-CSV versions of the object type. The result of an `Import-Csv` command is a collection of strings that form a table-like custom object. Each row is a separate string, so you can use the **Count** property of the object to count the table rows. The columns are the properties of the object and items in the rows are the property values. The column header row determines the number of columns and the column names. The column names are also the names of the properties of the objects. The first row is interpreted to be the column headers, unless you use the **Header** parameter to specify column headers. If any row has more values than the header row, the additional values are ignored. If the column header row is missing a value or contains a null or empty value, `Import-Csv` uses **H** followed by a number for the missing column header and property name. In the CSV file, each object is represented by a character-separated list of the property values of the object. The property values are converted to strings by using the **ToString()** method of the object, so they're represented by the name of the property value. `Export-Csv` doesn't export the methods of the object. `Import-Csv` also supports the W3C Extended Log format. Lines starting with the hash character (`#`) are treated as comments and ignored unless the comment starts with `#Fields:` and contains delimited list of column names. In that case, the cmdlet uses those column names. This is the standard format for Windows IIS and other web server logs. For more information, see [Extended Log File Format](https://www.w3.org/TR/WD-logfile.html). ## RELATED LINKS [ConvertFrom-Csv](ConvertFrom-Csv.md) [ConvertTo-Csv](ConvertTo-Csv.md) [Export-Csv](Export-Csv.md) [Get-Culture](Get-Culture.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Import-LocalizedData.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/19/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/import-localizeddata?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Import-LocalizedData --- # Import-LocalizedData ## SYNOPSIS Imports language-specific data into scripts and functions based on the UI culture that's selected for the operating system. ## SYNTAX ``` Import-LocalizedData [[-BindingVariable] <String>] [[-UICulture] <String>] [-BaseDirectory <String>] [-FileName <String>] [-SupportedCommand <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Import-LocalizedData` cmdlet dynamically retrieves strings from a subdirectory whose name matches the UI language set for the current user of the operating system. It's designed to enable scripts to display user messages in the UI language selected by the current user. `Import-LocalizedData` imports data from `.psd1` files in language-specific subdirectories of the script directory and saves them in a local variable that's specified in the command. The cmdlet selects the subdirectory and file based on the value of the `$PSUICulture` automatic variable. When you use the local variable in the script to display a user message, the message appears in the user's UI language. You can use the parameters of `Import-LocalizedData` to specify an alternate UI culture, path, and filename, to add supported commands, and to suppress the error message that appears if the `.psd1` files aren't found. The `Import-LocalizedData` cmdlet supports the script internationalization initiative that was introduced in Windows PowerShell 2.0. This initiative aims to better serve users worldwide by making it easy for scripts to display user messages in the UI language of the current user. For more information about this and about the format of the `.psd1` files, see [about_Script_Internationalization](../Microsoft.PowerShell.Core/About/about_Script_Internationalization.md). ## EXAMPLES ### Example 1: Import text strings This example imports text strings into the `$Messages` variable. It uses the default values of all other cmdlet parameters. ```powershell Import-LocalizedData -BindingVariable "Messages" ``` If the command is included in the Archives.ps1 script in the `C:\Test` directory, and the value of the `$PSUICulture` automatic variable is zh-CN, `Import-LocalizedData` imports the `Archives.psd1` file in the `C:\test\zh-CN` directory into the `$Messages` variable. ### Example 2: Import localized data strings This example is run at the command line not in a script. It gets localized data strings from the `Test.psd1` file and displays them at the command line. Because the command isn't used in a script, the **FileName** parameter is required. The command uses the **UICulture** parameter to specify the en-US culture. ```powershell Import-LocalizedData -FileName "Test.psd1" -UICulture "en-US" ``` ```Output Name Value ---- ----- Msg3 "Use $_ to represent the object that's being processed." Msg2 "This command requires the credentials of a member of the Administrators group on the... Msg1 "The Name parameter is missing from the command." ``` `Import-LocalizedData` returns a hashtable that contains the localized data strings. ### Example 3: Import UI culture strings ```powershell Import-LocalizedData -BindingVariable "MsgTbl" -UICulture "ar-SA" -FileName "Simple" -BaseDirectory "C:\Data\Localized" ``` This command imports text strings into the `$MsgTbl` variable of a script. It uses the **UICulture** parameter to direct the cmdlet to import data from the `Simple.psd1` file in the `ar-SA` subdirectory of `C:\Data\Localized`. ### Example 4: Import localized data into a script This example shows how to use localized data in a simple script. ```powershell PS C:\> # In C:\Test\en-US\Test.psd1: ConvertFrom-StringData @' # English strings Msg1 = "The Name parameter is missing from the command." Msg2 = "This command requires the credentials of a member of the Administrators group on the computer." Msg3 = "Use $_ to represent the object that's being processed." '@ # In C:\Test\Test.ps1 Import-LocalizedData -BindingVariable "Messages" Write-Host $Messages.Msg2 # In Windows PowerShell PS C:\> .\Test.ps1 This command requires the credentials of a member of the Administrators group on the computer. ``` The first part of the example shows the contents of the `Test.psd1` file. It contains a `ConvertFrom-StringData` command that converts a series of named text strings into a hashtable. The `Test.psd1` file is located in the en-US subdirectory of the `C:\Test` directory that contains the script. The second part of the example shows the contents of the `Test.ps1` script. It contains an `Import-LocalizedData` command that imports the data from the matching `.psd1` file into the `$Messages` variable and a `Write-Host` command that writes one of the messages in the `$Messages` variable to the host program. The last part of the example runs the script. The output shows that it displays the correct user message in the UI language set for the current user of the operating system. ### Example 5: Replace default text strings in a script This example shows how to use `Import-LocalizedData` to replace default text strings defined in the DATA section of a script. ```powershell PS C:\> # In TestScript.ps1 $UserMessages = DATA { ConvertFrom-StringData @' # English strings Msg1 = "Enter a name." Msg2 = "Enter your employee ID." Msg3 = "Enter your building number." '@ } Import-LocalizedData -BindingVariable "UserMessages" $UserMessages.Msg1... ``` In this example, the DATA section of the `TestScript.ps1` script contains a `ConvertFrom-StringData` command that converts the contents of the DATA section to a hashtable and stores in the value of the `$UserMessages` variable. The script also includes an `Import-LocalizedData` command, which imports a hashtable of translated text strings from the `TestScript.psd1` file in the subdirectory specified by the value of the `$PSUICulture` variable. If the command finds the `.psd1` file, it saves the translated strings from the file in the value of the same `$UserMessages` variable, overwriting the hashtable saved by the DATA section logic. The third command displays the first message in the `$UserMessages` variable. If the `Import-LocalizedData` command finds a `.psd1` file for the `$PSUICulture` language, the value of the `$UserMessages` variable contains the translated text strings. If the command fails for any reason, the command displays the default text strings defined in the DATA section of the script. ### Example 6: Suppress error messages if the UI culture isn't found This example shows how to suppress the error messages that appear when `Import-LocalizedData` can't find the directories that match the user's UI culture or can't find a `.psd1` file for the script in those directories. ```powershell PS C:\> # In Day1.ps1 Import-LocalizedData -BindingVariable "Day" # In Day2.ps1 Import-LocalizedData -BindingVariable "Day" -ErrorAction:SilentlyContinue PS C:\> .\Day1.ps1 Import-LocalizedData : Can't find PowerShell data file 'Day1.psd1' in directory 'C:\ps-test\fr-BE\' or any parent culture directories. At C:\ps-test\Day1.ps1:17 char:21+ Import-LocalizedData <<<< Day Today is Tuesday PS C:\> .\Day2.ps1 Today is Tuesday ``` You can use the **ErrorAction** common parameter with a value of SilentlyContinue to suppress the error message. This is especially useful when you have provided user messages in a default or fallback language, and no error message is needed. This example compares two scripts, `Day1.ps1` and Day2.ps1, that include an `Import-LocalizedData` command. The scripts are identical, except that Day2 uses the **ErrorAction** common parameter with a value of `SilentlyContinue`. The sample output shows the results of running both scripts when the UI culture is set to `fr-BE` and there are no matching files or directories for that UI culture. `Day1.ps1` displays an error message and English output. `Day2.ps1` just displays the English output. ## PARAMETERS ### -BaseDirectory Specifies the base directory where the `.psd1` files are located. The default is the directory where the script is located. `Import-LocalizedData` searches for the `.psd1` file for the script in a language-specific subdirectory of the base directory. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -BindingVariable Specifies the variable into which the text strings are imported. Enter a variable name without a dollar sign (`$`). In Windows PowerShell 2.0, this parameter is required. In Windows PowerShell 3.0, this parameter is optional. If you omit this parameter, `Import-LocalizedData` returns a hashtable of the text strings. The hashtable is passed down the pipeline or displayed at the command line. When using `Import-LocalizedData` to replace default text strings specified in the DATA section of a script, assign the DATA section to a variable and enter the name of the DATA section variable in the value of the **BindingVariable** parameter. Then, when `Import-LocalizedData` saves the imported content in the **BindingVariable**, the imported data will replace the default text strings. If you aren't specifying default text strings, you can select any variable name. ```yaml Type: System.String Parameter Sets: (All) Aliases: Variable Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FileName Specifies the name of the data file (`.psd1`) to be imported. Enter a filename. You can specify a filename that doesn't include its `.psd1` filename extension, or you can specify the filename including the `.psd1` filename extension. Data files should be saved as Unicode or UTF-8. The **FileName** parameter is required when `Import-LocalizedData` isn't used in a script. Otherwise, the parameter is optional and the default value is the base name of the script. You can use this parameter to direct `Import-LocalizedData` to search for a different `.psd1` file. For example, if the **FileName** is omitted and the script name is `FindFiles.ps1`, `Import-LocalizedData` searches for the `FindFiles.psd1` data file. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SupportedCommand Specifies cmdlets and functions that generate only data. Use this parameter to include cmdlets and functions that you have written or tested. For more information, see [about_Script_Internationalization](../Microsoft.PowerShell.Core/About/about_Script_Internationalization.md). ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UICulture Specifies an alternate UI culture. The default is the value of the `$PSUICulture` automatic variable. Enter a UI culture in `<language>-<region>` format, such as `en-US`, `de-DE`, or `ar-SA`. The value of the **UICulture** parameter determines the language-specific subdirectory (within the base directory) from which `Import-LocalizedData` gets the `.psd1` file for the script. The cmdlet searches for a subdirectory with the same name as the value of the **UICulture** parameter or the `$PSUICulture` automatic variable, such as `de-DE` or `ar-SA`. If it can't find the directory, or the directory doesn't contain a `.psd1` file for the script, it searches for a subdirectory with the name of the language code, such as de or ar. If it can't find the subdirectory or `.psd1` file, the command fails and the data is displayed in the default language specified in the script. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Collections.Hashtable This cmdlet saves the hashtable in the variable specified by the value of the **BindingVariable** parameter. ## NOTES - Before using `Import-LocalizedData`, localize your user messages. Format the messages for each locale (UI culture) in a hashtable of key-value pairs, and save the hashtable in a file with the same name as the script and a `.psd1` filename extension. Create a directory under the script directory for each supported UI culture, and then save the `.psd1` file for each UI culture in the directory with the UI culture name. For example, localize your user messages for the de-DE locale and format them in a hashtable. Save the hashtable in a `<ScriptName>.psd1` file. Then create a `de-DE` subdirectory under the script directory, and save the German `<ScriptName>.psd1` file in the `de-DE` subdirectory. Repeat this method for each locale that you support. - `Import-LocalizedData` performs a structured search for the localized user messages for a script. `Import-LocalizedData` begins the search in the directory where the script file is located (or the value of the **BaseDirectory** parameter). It then searches within the base directory for a subdirectory with the same name as the value of the `$PSUICulture` variable (or the value of the **UICulture** parameter), such as `de-DE` or `ar-SA`. Then, it searches in that subdirectory for a `.psd1` file with the same name as the script (or the value of the **FileName** parameter). If `Import-LocalizedData` can't find a subdirectory with the name of the UI culture, or the subdirectory doesn't contain a `.psd1` file for the script, it searches for a `.psd1` file for the script in a subdirectory with the name of the language code, such as de or ar. If it can't find the subdirectory or `.psd1` file, the command fails, the data is displayed in the default language in the script, and an error message is displayed explaining that the data could not be imported. To suppress the message and fail gracefully, use the **ErrorAction** common parameter with a value of SilentlyContinue. If `Import-LocalizedData` finds the subdirectory and the `.psd1` file, it imports the hashtable of user messages into the value of the **BindingVariable** parameter in the command. Then, when you display a message from the hashtable in the variable, the localized message is displayed. For more information, see [about_Script_Internationalization](../Microsoft.Powershell.Core/About/about_Script_Internationalization.md). ## RELATED LINKS [Write-Host](Write-Host.md) [Import-PowerShellDataFile](Import-PowerShellDataFile.md) [about_Data_Files](../Microsoft.PowerShell.Core/About/about_Data_Files.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Import-PowerShellDataFile.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/19/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/import-powershelldatafile?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Import-PowerShellDataFile --- # Import-PowerShellDataFile ## SYNOPSIS Imports values from a `.psd1` file without invoking its contents. ## SYNTAX ### ByPath (Default) ``` Import-PowerShellDataFile [-Path] <String[]> [-SkipLimitCheck] [<CommonParameters>] ``` ### ByLiteralPath ``` Import-PowerShellDataFile [-LiteralPath] <String[]> [-SkipLimitCheck] [<CommonParameters>] ``` ## DESCRIPTION The `Import-PowerShellDataFile` cmdlet safely imports key-value pairs from hashtables defined in a `.psd1` file. The values could be imported using `Invoke-Expression` on the contents of the file. However, `Invoke-Expression` runs any code contained in the file. This could produce unwanted results or execute unsafe code. `Import-PowerShellDataFile` imports the data without invoking the code. By default there is a 500 key limit, but this can be bypassed with the **SkipLimitCheck** switch. ## EXAMPLES ### Example 1: Retrieve values from PSD1 This example retrieves the key-value pairs stored in the hashtable kept inside the `Configuration.psd1` file. `Get-Content` is used to show the contents of the `Configuration.psd1` file. ```powershell Get-Content .\Configuration.psd1 $config = Import-PowerShellDataFile .\Configuration.psd1 $config.AllNodes ``` ```Output @{ AllNodes = @( @{ NodeName = 'DSC-01' } @{ NodeName = 'DSC-02' } ) } Name Value ---- ----- NodeName DSC-01 NodeName DSC-02 ``` ## PARAMETERS ### -LiteralPath The path to the file being imported. All characters in the path are treated as literal values. Wildcard characters aren't processed. ```yaml Type: System.String[] Parameter Sets: ByLiteralPath Aliases: PSPath, LP Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path The path to the file being imported. Wildcards are allowed but only the first matching file is imported. ```yaml Type: System.String[] Parameter Sets: ByPath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -SkipLimitCheck By default `Import-PowerShellDataFile` imports only 500 keys from a `.psd1` file. Use **SkipLimitCheck** to import more than 500 keys. ```yaml Type: Switch Parameter Sets: All Aliases: Required: False Position: 0 Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ### System.Collections.Hashtable This cmdlet returns the data from the file as a hash table. ## NOTES ## RELATED LINKS [Invoke-Expression](Invoke-Expression.md) [Import-LocalizedData](Import-LocalizedData.md) [about_Data_Files](../Microsoft.PowerShell.Core/About/about_Data_Files.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Import-PSSession.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/import-pssession?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Import-PSSession --- # Import-PSSession ## SYNOPSIS Imports commands from another session into the current session. ## SYNTAX ``` Import-PSSession [-Prefix <String>] [-DisableNameChecking] [[-CommandName] <String[]>] [-AllowClobber] [-ArgumentList <Object[]>] [-CommandType <CommandTypes>] [-Module <String[]>] [-FullyQualifiedModule <ModuleSpecification[]>] [[-FormatTypeName] <String[]>] [-Certificate <X509Certificate2>] [-Session] <PSSession> [<CommonParameters>] ``` ## DESCRIPTION The `Import-PSSession` cmdlet imports commands , such as cmdlets, functions, and aliases, from a PSSession on a local or remote computer into the current session. You can import any command that the `Get-Command` cmdlet can find in the PSSession. Use an `Import-PSSession` command to import commands from a customized shell, such as a Microsoft Exchange Server shell, or from a session that includes Windows PowerShell modules and snap-ins or other elements that are not in the current session. To import commands, first use the `New-PSSession` cmdlet to create a PSSession. Then, use the `Import-PSSession` cmdlet to import the commands. By default, `Import-PSSession` imports all commands except for commands that have the same names as commands in the current session. To import all the commands, use the **AllowClobber** parameter. You can use imported commands just as you would use any command in the session. When you use an imported command, the imported part of the command runs implicitly in the session from which it was imported. However, the remote operations are handled entirely by Windows PowerShell. You need not even be aware of them, except that you must keep the connection to the other session (PSSession) open. If you close it, the imported commands are no longer available. Because imported commands might take longer to run than local commands, `Import-PSSession` adds an **AsJob** parameter to every imported command. This parameter allows you to run the command as a Windows PowerShell background job. For more information, see [about_Jobs](../Microsoft.PowerShell.Core/about/about_Jobs.md). When you use `Import-PSSession`, Windows PowerShell adds the imported commands to a temporary module that exists only in your session and returns an object that represents the module. To create a persistent module that you can use in future sessions, use the `Export-PSSession` cmdlet. The `Import-PSSession` cmdlet uses the implicit remoting feature of Windows PowerShell. When you import commands into the current session, they run implicitly in the original session or in a similar session on the originating computer. Beginning in Windows PowerShell 3.0, you can use the `Import-Module` cmdlet to import modules from a remote session into the current session. This feature uses implicit remoting. It is equivalent to using `Import-PSSession` to import selected modules from a remote session into the current session. ## EXAMPLES ### Example 1: Import all commands from a PSSession ``` $S = New-PSSession -ComputerName Server01 Import-PSSession -Session $S ``` This command imports all commands from a PSSession on the Server01 computer into the current session, except for commands that have the same names as commands in the current session. Because this command does not use the **CommandName** parameter, it also imports all of the formatting data required for the imported commands. ### Example 2: Import commands that end with a specific string ``` $S = New-PSSession https://ps.testlabs.com/powershell Import-PSSession -Session $S -CommandName *-test -FormatTypeName * New-Test -Name Test1 Get-Test test1 | Run-Test ``` These commands import the commands with names that end in "-test" from a PSSession into the local session, and then they show how to use an imported cmdlet. The first command uses the `New-PSSession` cmdlet to create a PSSession. It saves the PSSession in the `$S` variable. The second command uses the `Import-PSSession` cmdlet to import commands from the PSSession in `$S` into the current session. It uses the **CommandName** parameter to specify commands with the Test noun and the **FormatTypeName** parameter to import the formatting data for the Test commands. The third and fourth commands use the imported commands in the current session. Because imported commands are actually added to the current session, you use the local syntax to run them. You do not need to use the `Invoke-Command` cmdlet to run an imported command. ### Example 3: Import cmdlets from a PSSession ``` $S1 = New-PSSession -ComputerName s1 $S2 = New-PSSession -ComputerName s2 Import-PSSession -Session s1 -Type Cmdlet -Name New-Test, Get-Test -FormatTypeName * Import-PSSession -Session s2 -Type Cmdlet -Name Set-Test -FormatTypeName * New-Test Test1 | Set-Test -RunType Full ``` This example shows that you can use imported cmdlets just as you would use local cmdlets. These commands import the `New-Test` and `Get-Test` cmdlets from a PSSession on the Server01 computer and the `Set-Test` cmdlet from a PSSession on the Server02 computer. Even though the cmdlets were imported from different PSSessions, you can pipe an object from one cmdlet to another without error. ### Example 4: Run an imported command as a background job ``` $S = New-PSSession -ComputerName Server01 Import-PSSession -Session $S -CommandName *-test* -FormatTypeName * $batch = New-Test -Name Batch -AsJob Receive-Job $batch ``` This example shows how to run an imported command as a background job. Because imported commands might take longer to run than local commands, `Import-PSSession` adds an **AsJob** parameter to every imported command. The **AsJob** parameter lets you run the command as a background job. The first command creates a PSSession on the Server01 computer and saves the PSSession object in the `$S` variable. The second command uses `Import-PSSession` to import the Test cmdlets from the PSSession in `$S` into the current session. The third command uses the **AsJob** parameter of the imported `New-Test` cmdlet to run a `New-Test` command as a background job. The command saves the job object that `New-Test` returns in the `$batch` variable. The fourth command uses the `Receive-Job` cmdlet to get the results of the job in the `$batch` variable. ### Example 5: Import cmdlets and functions from a Windows PowerShell module ``` $S = New-PSSession -ComputerName Server01 Invoke-Command -Session $S {Import-Module TestManagement} Import-PSSession -Session $S -Module TestManagement ``` This example shows how to import the cmdlets and functions from a Windows PowerShell module on a remote computer into the current session. The first command creates a PSSession on the Server01 computer and saves it in the `$S` variable. The second command uses the `Invoke-Command` cmdlet to run an `Import-Module` command in the PSSession in `$S`. Typically, the module would be added to all sessions by an `Import-Module` command in a Windows PowerShell profile, but profiles are not run in PSSessions. The third command uses the **Module** parameter of `Import-PSSession` to import the cmdlets and functions in the module into the current session. ### Example 6: Create a module in a temporary file ``` PS C:\> Import-PSSession $S -CommandName Get-Date, SearchHelp -FormatTypeName * -AllowClobber Name : tmp_79468106-4e1d-4d90-af97-1154f9317239_tcw1zunz.ttf Path : C:\Users\User01\AppData\Local\Temp\tmp_79468106-4e1d-4d90-af97-1154f9317239_tcw1 zunz.ttf\tmp_79468106-4e1d-4d90-af97-1154f9317239_ tcw1zunz.ttf.psm1 Description : Implicit remoting for http://server01.corp.fabrikam.com/wsman Guid : 79468106-4e1d-4d90-af97-1154f9317239 Version : 1.0 ModuleBase : C:\Users\User01\AppData\Local\Temp\tmp_79468106-4e1d-4d90-af97-1154f9317239_tcw1 zunz.ttf ModuleType : Script PrivateData : {ImplicitRemoting} AccessMode : ReadWrite ExportedAliases : {} ExportedCmdlets : {} ExportedFunctions : {[Get-Date, Get-Date], [SearchHelp, SearchHelp]} ExportedVariables : {} NestedModules : {} ``` This example shows that `Import-PSSession` creates a module in a temporary file on disk. It also shows that all commands are converted into functions before they are imported into the current session. The command uses the `Import-PSSession` cmdlet to import a `Get-Date` cmdlet and a SearchHelp function into the current session. The `Import-PSSession` cmdlet returns a **PSModuleInfo** object that represents the temporary module. The value of the **Path** property shows that `Import-PSSession` created a script module (`.psm1`) file in a temporary location. The **ExportedFunctions** property shows that the `Get-Date` cmdlet and the SearchHelp function were both imported as functions. ### Example 7: Run a command that is hidden by an imported command ``` PS C:\> Import-PSSession $S -CommandName Get-Date -FormatTypeName * -AllowClobber PS C:\> Get-Command Get-Date -All CommandType Name Definition ----------- ---- ---------- Function Get-Date ... Cmdlet Get-Date Get-Date [[-Date] <DateTime>] [-Year <Int32>] [-Month <Int32>] PS C:\> Get-Date 09074 PS C:\> (Get-Command -Type Cmdlet -Name Get-Date).PSSnapin.Name Microsoft.PowerShell.Utility PS C:\> Microsoft.PowerShell.Utility\Get-Date Sunday, March 15, 2009 2:08:26 PM ``` This example shows how to run a command that is hidden by an imported command. The first command imports a `Get-Date` cmdlet from the PSSession in the `$S` variable. Because the current session includes a `Get-Date` cmdlet, the **AllowClobber** parameter is required in the command. The second command uses the **All** parameter of the `Get-Command` cmdlet to get all `Get-Date` commands in the current session. The output shows that the session includes the original `Get-Date` cmdlet and a `Get-Date` function. The `Get-Date` function runs the imported `Get-Date` cmdlet in the PSSession in `$S`. The third command runs a `Get-Date` command. Because functions take precedence over cmdlets, Windows PowerShell runs the imported `Get-Date` function, which returns a Julian date. The fourth and fifth commands show how to use a qualified name to run a command that is hidden by an imported command. The fourth command gets the name of the Windows PowerShell snap-in that added the original `Get-Date` cmdlet to the current session. The fifth command uses the snap-in-qualified name of the `Get-Date` cmdlet to run a `Get-Date` command. For more information about command precedence and hidden commands, see [about_Command_Precedence](../Microsoft.PowerShell.Core/about/about_Command_Precedence.md). ### Example 8: Import commands that have a specific string in their names ``` PS C:\> Import-PSSession -Session $S -CommandName **Item** -AllowClobber ``` This command imports commands whose names include Item from the PSSession in `$S`. Because the command includes the **CommandName** parameter but not the **FormatTypeData** parameter, only the command is imported. Use this command when you are using `Import-PSSession` to run a command on a remote computer and you already have the formatting data for the command in the current session. ### Example 9: Use the Module parameter to discover which commands were imported into the session ``` PS C:\> $M = Import-PSSession -Session $S -CommandName *bits* -FormatTypeName *bits* PS C:\> Get-Command -Module $M CommandType Name ----------- ---- Function Add-BitsFile Function Complete-BitsTransfer Function Get-BitsTransfer Function Remove-BitsTransfer Function Resume-BitsTransfer Function Set-BitsTransfer Function Start-BitsTransfer Function Suspend-BitsTransfer ``` This command shows how to use the **Module** parameter of `Get-Command` to find out which commands were imported into the session by an `Import-PSSession` command. The first command uses the `Import-PSSession` cmdlet to import commands whose names include "bits" from the PSSession in the `$S` variable. The `Import-PSSession` command returns a temporary module, and the command saves the module in the `$m` variable. The second command uses the `Get-Command` cmdlet to get the commands that are exported by the module in the `$M` variable. The **Module** parameter takes a string value, which is designed for the module name. However, when you submit a module object, Windows PowerShell uses the **ToString** method on the module object, which returns the module name. The `Get-Command` command is the equivalent of `Get-Command $M.Name`". ## PARAMETERS ### -AllowClobber Indicates that this cmdlet imports the specified commands, even if they have the same names as commands in the current session. If you import a command with the same name as a command in the current session, the imported command hides or replaces the original commands. For more information, see [about_Command_Precedence](../Microsoft.PowerShell.Core/about/about_Command_Precedence.md). By default, `Import-PSSession` does not import commands that have the same name as commands in the current session. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ArgumentList Specifies an array of commands that results from using the specified arguments (parameter values). For instance, to import the variant of the `Get-Item` command in the certificate (Cert:) drive in the PSSession in `$S`, type `Import-PSSession -Session $S -Command Get-Item -ArgumentList Cert:`. ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Args Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Certificate Specifies the client certificate that is used to sign the format files (*.Format.ps1xml) or script module files (`.psm1`) in the temporary module that `Import-PSSession` creates. Enter a variable that contains a certificate or a command or expression that gets the certificate. To find a certificate, use the `Get-PfxCertificate` cmdlet or use the `Get-ChildItem` cmdlet in the Certificate (Cert:) drive. If the certificate is not valid or does not have sufficient authority, the command fails. ```yaml Type: System.Security.Cryptography.X509Certificates.X509Certificate2 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CommandName Specifies commands with the specified names or name patterns. Wildcards are permitted. Use **CommandName** or its alias, **Name**. By default, `Import-PSSession` imports all commands from the session, except for commands that have the same names as commands in the current session. This prevents imported commands from hiding or replacing commands in the session. To import all commands, even those that hide or replace other commands, use the **AllowClobber** parameter. If you use the **CommandName** parameter, the formatting files for the commands are not imported unless you use the **FormatTypeName** parameter. Similarly, if you use the **FormatTypeName** parameter, no commands are imported unless you use the **CommandName** parameter. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Name Required: False Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CommandType Specifies the type of command objects. The default value is Cmdlet. Use **CommandType** or its alias, **Type**. The acceptable values for this parameter are: - `Alias`: The Windows PowerShell aliases in the remote session. - `All`: The cmdlets and functions in the remote session. - `Application`: All the files other than Windows-PowerShell files in the paths that are listed in the PATH environment variable (`$Env:PATH`) in the remote session, including .txt, .exe, and .dll files. - `Cmdlet`: The cmdlets in the remote session. "Cmdlet" is the default. - `ExternalScript`: The `.ps1` files in the paths listed in the PATH environment variable (`$Env:PATH`) in the remote session. - `Filter` and `Function`: The Windows PowerShell functions in the remote session. - `Script`: The script blocks in the remote session. These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **CommandType** parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. ```yaml Type: System.Management.Automation.CommandTypes Parameter Sets: (All) Aliases: Type Accepted values: Alias, Function, Filter, Cmdlet, ExternalScript, Application, Script, Workflow, Configuration, All Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DisableNameChecking Indicates that this cmdlet suppresses the message that warns you when you import a cmdlet or function whose name includes an unapproved verb or a prohibited character. By default, when a module that you import exports cmdlets or functions that have unapproved verbs in their names, the Windows PowerShell displays the following warning message: "WARNING: Some imported command names include unapproved verbs which might make them less discoverable. Use the Verbose parameter for more detail or type `Get-Verb` to see the list of approved verbs." This message is only a warning. The complete module is still imported, including the non-conforming commands. Although the message is displayed to module users, the naming problem should be fixed by the module author. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FormatTypeName Specifies formatting instructions for the specified Microsoft .NET Framework types. Enter the type names. Wildcards are permitted. The value of this parameter must be the name of a type that is returned by a `Get-FormatData` command in the session from which the commands are being imported. To get all of the formatting data in the remote session, type `*`. If the command does not include either the **CommandName** or **FormatTypeName** parameter, `Import-PSSession` imports formatting instructions for all .NET Framework types returned by a `Get-FormatData` command in the remote session. If you use the **FormatTypeName** parameter, no commands are imported unless you use the **CommandName** parameter. Similarly, if you use the **CommandName** parameter, the formatting files for the commands are not imported unless you use the **FormatTypeName** parameter. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FullyQualifiedModule The value can be a module name, a full module specification, or a path to a module file. When the value is a path, the path can be fully qualified or relative. A relative path is resolved relative to the script that contains the using statement. When the value is a name or module specification, PowerShell searches the **PSModulePath** for the specified module. A module specification is a hashtable that has the following keys. - `ModuleName` - **Required** Specifies the module name. - `GUID` - **Optional** Specifies the GUID of the module. - It's also **Required** to specify at least one of the three below keys. - `ModuleVersion` - Specifies a minimum acceptable version of the module. - `MaximumVersion` - Specifies the maximum acceptable version of the module. - `RequiredVersion` - Specifies an exact, required version of the module. This can't be used with the other Version keys. You can't specify the **FullyQualifiedModule** parameter in the same command as a **Module** parameter. The two parameters are mutually exclusive. ```yaml Type: Microsoft.PowerShell.Commands.ModuleSpecification[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Module Specifies and array of commands in the Windows PowerShell snap-ins and modules. Enter the snap-in and module names. Wildcards are not permitted. `Import-PSSession` cannot import providers from a snap-in. For more information, see [about_PSSnapins](/powershell/module/Microsoft.PowerShell.Core/About/about_PSSnapins) and [about_Modules](../Microsoft.PowerShell.Core/About/about_Modules.md). ```yaml Type: System.String[] Parameter Sets: (All) Aliases: PSSnapin Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Prefix Specifies a prefix to the nouns in the names of imported commands. Use this parameter to avoid name conflicts that might occur when different commands in the session have the same name. For instance, if you specify the prefix Remote and then import a `Get-Date` cmdlet, the cmdlet is known in the session as `Get-RemoteDate`, and it is not confused with the original `Get-Date` cmdlet. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Session Specifies the **PSSession** from which the cmdlets are imported. Enter a variable that contains a session object or a command that gets a session object, such as a `New-PSSession` or `Get-PSSession` command. You can specify only one session. This parameter is required. ```yaml Type: System.Management.Automation.Runspaces.PSSession Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSModuleInfo This cmdlet returns the same module object that `New-Module` and `Get-Module` cmdlets return. However, the imported module is temporary and exists only in the current session. To create a permanent module on disk, use the `Export-PSSession` cmdlet. ## NOTES - `Import-PSSession` relies on the PowerShell remoting infrastructure. To use this cmdlet, the computer must be configured for WS-Management remoting. For more information, see [about_Remote](../Microsoft.PowerShell.Core/about/about_Remote.md) and [about_Remote_Requirements](../Microsoft.PowerShell.Core/about/about_Remote_Requirements.md). - `Import-PSSession` does not import variables or PowerShell providers. - When you import commands that have the same names as commands in the current session, the imported commands can hide aliases, functions, and cmdlets in the session and they can replace functions and variables in the session. To prevent name conflicts, use the **Prefix** parameter. For more information, see [about_Command_Precedence](../Microsoft.PowerShell.Core/about/about_Command_Precedence.md). - `Import-PSSession` converts all commands into functions before it imports them. As a result, imported commands behave a bit differently than they would if they retained their original command type. For example, if you import a cmdlet from a PSSession and then import a cmdlet with the same name from a module or snap-in, the cmdlet that is imported from the PSSession always runs by default because functions take precedence over cmdlets. Conversely, if you import an alias into a session that has an alias with the same name, the original alias is always used, because aliases take precedence over functions. For more information, see [about_Command_Precedence](../Microsoft.PowerShell.Core/about/about_Command_Precedence.md). - `Import-PSSession` uses the `Write-Progress` cmdlet to display the progress of the command. You might see the progress bar while the command is running. - To find the commands to import, `Import-PSSession` uses the `Invoke-Command` cmdlet to run a `Get-Command` command in the PSSession. To get formatting data for the commands, it uses the `Get-FormatData` cmdlet. You might see error messages from these cmdlets when you run an `Import-PSSession` command. Also, `Import-PSSession` cannot import commands from a PSSession that does not include the `Get-Command`, `Get-FormatData`, `Select-Object`, and `Get-Help` cmdlets. - Imported commands have the same limitations as other remote commands, including the inability to start a program with a user interface, such as Notepad. - Because Windows PowerShell profiles are not run in PSSessions, the commands that a profile adds to a session are not available to `Import-PSSession`. To import commands from a profile, use an `Invoke-Command` command to run the profile in the PSSession manually before importing commands. - The temporary module that `Import-PSSession` creates might include a formatting file, even if the command does not import formatting data. If the command does not import formatting data, any formatting files that are created will not contain formatting data. - To use `Import-PSSession`, the execution policy in the current session cannot be Restricted or AllSigned, because the temporary module that `Import-PSSession` creates contains unsigned script files that are prohibited by these policies. To use `Import-PSSession` without changing the execution policy for the local computer, use the **Scope** parameter of `Set-ExecutionPolicy` to set a less restrictive execution policy for a single process. - In Windows PowerShell 2.0, help topics for commands that are imported from another session do not include the prefix that you assign by using the **Prefix** parameter. To get help for an imported command in Windows PowerShell 2.0, use the original (non-prefixed) command name. ## RELATED LINKS [Export-PSSession](Export-PSSession.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Invoke-Expression.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 02/03/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/invoke-expression?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Invoke-Expression --- # Invoke-Expression ## SYNOPSIS Runs commands or expressions on the local computer. ## SYNTAX ``` Invoke-Expression [-Command] <String> [<CommonParameters>] ``` ## DESCRIPTION The `Invoke-Expression` cmdlet evaluates or runs a specified string as a command and returns the results of the expression or command. Without `Invoke-Expression`, a string submitted at the command line is returned (echoed) unchanged. Expressions are evaluated and run in the current scope. For more information, see [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md). > [!CAUTION] > Take reasonable precautions when using the `Invoke-Expression` cmdlet in scripts. When using > `Invoke-Expression` to run a command that the user enters, verify that the command is safe to run > before running it. In general, it is best to design your script with predefined input options, > rather than allowing freeform input. ## EXAMPLES ### Example 1: Evaluate an expression ```powershell $Command = "Get-Process" $Command ``` ```Output Get-Process ``` ```powershell Invoke-Expression $Command ``` ```Output Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 296 4 1572 1956 20 0.53 1348 AdtAgent 270 6 1328 800 34 0.06 2396 alg 67 2 620 484 20 0.22 716 ati2evxx 1060 15 12904 11840 74 11.48 892 CcmExec 1400 33 25280 37544 223 38.44 2564 communicator ... ``` This example demonstrates the use of `Invoke-Expression` to evaluate an expression. Without `Invoke-Expression`, the expression is printed, but not evaluated. The first command assigns a value of `Get-Process` (a string) to the `$Command` variable. The second command shows the effect of typing the variable name at the command line. PowerShell echoes the string. The third command uses `Invoke-Expression` to evaluate the string. ### Example 2: Run a script on the local computer ```powershell Invoke-Expression -Command "C:\ps-test\testscript.ps1" "C:\ps-test\testscript.ps1" | Invoke-Expression ``` These commands use `Invoke-Expression` to run a script, `TestScript.ps1`, on the local computer. The two commands are equivalent. The first uses the **Command** parameter to specify the command to run. The second uses a pipeline operator (`|`) to send the command string to `Invoke-Expression`. ### Example 3: Run a command in a variable ```powershell $Command = 'Get-Process | where {$_.CPU -gt 1000}' Invoke-Expression $Command ``` This example runs a command string that is saved in the `$Command` variable. The command string is enclosed in single quotation marks because it includes a variable, `$_`, which represents the current object. If it were enclosed in double quotation marks, the `$_` variable would be replaced by its value before it was saved in the `$Command` variable. ### Example 4: Get and run a cmdlet Help example ```powershell $Cmdlet_name = "Get-ComputerInfo" $Example_number = 1 $Example_code = (Get-Help $Cmdlet_name).examples.example[($Example_number-1)].code Invoke-Expression $Example_code ``` This command retrieves and runs the first example in the `Get-EventLog` cmdlet Help topic. To run an example of a different cmdlet, change the value of the `$Cmdlet_name` variable to the name of the cmdlet. And, change the `$Example_number` variable to the example number you want to run. The command fails if the example number is not valid. > [!NOTE] > If the example code from the help file has output in the example, PowerShell attempts to run the > output along with the code and an error will be thrown. ## PARAMETERS ### -Command Specifies the command or expression to run. Type the command or expression or enter a variable that contains the command or expression. The **Command** parameter is required. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string representing the expression to invoke to this cmdlet. Use the `$input` automatic variable to represent the input objects in the command. ### System.Management.Automation.PSObject You can pipe an object representing the expression to invoke to this cmdlet. Use the `$input` automatic variable to represent the input objects in the command. ## OUTPUTS ### None This cmdlet returns no output of its own, but the invoked command may return output. ## NOTES PowerShell includes the following aliases for `Invoke-Expression`: - All platforms: - `iex` In most cases, you invoke expressions using PowerShell's call operator and achieve the same results. The call operator is a safer method. For more information, see [about_Operators](../microsoft.powershell.core/about/about_operators.md#call-operator-). ## RELATED LINKS [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md) [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Invoke-RestMethod.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 02/05/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/invoke-restmethod?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Invoke-RestMethod --- # Invoke-RestMethod ## SYNOPSIS Sends an HTTP or HTTPS request to a RESTful web service. ## SYNTAX ### StandardMethod (Default) ``` Invoke-RestMethod [-FollowRelLink] [-MaximumFollowRelLink <Int32>] [-ResponseHeadersVariable <String>] [-StatusCodeVariable <String>] [-UseBasicParsing] [-Uri] <Uri> [-HttpVersion <Version>] [-WebSession <WebRequestSession>] [-SessionVariable <String>] [-AllowUnencryptedAuthentication] [-Authentication <WebAuthenticationType>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-CertificateThumbprint <String>] [-Certificate <X509Certificate>] [-SkipCertificateCheck] [-SslProtocol <WebSslProtocol>] [-Token <SecureString>] [-UserAgent <String>] [-DisableKeepAlive] [-ConnectionTimeoutSeconds <Int32>] [-OperationTimeoutSeconds <Int32>] [-Headers <IDictionary>] [-SkipHeaderValidation] [-AllowInsecureRedirect] [-MaximumRedirection <Int32>] [-MaximumRetryCount <Int32>] [-PreserveAuthorizationOnRedirect] [-RetryIntervalSec <Int32>] [-Method <WebRequestMethod>] [-PreserveHttpMethodOnRedirect] [-UnixSocket <UnixDomainSocketEndPoint>] [-Proxy <Uri>] [-ProxyCredential <PSCredential>] [-ProxyUseDefaultCredentials] [-Body <Object>] [-Form <IDictionary>] [-ContentType <String>] [-TransferEncoding <String>] [-InFile <String>] [-OutFile <String>] [-PassThru] [-Resume] [-SkipHttpErrorCheck] [<CommonParameters>] ``` ### StandardMethodNoProxy ``` Invoke-RestMethod [-FollowRelLink] [-MaximumFollowRelLink <Int32>] [-ResponseHeadersVariable <String>] [-StatusCodeVariable <String>] [-UseBasicParsing] [-Uri] <Uri> [-HttpVersion <Version>] [-WebSession <WebRequestSession>] [-SessionVariable <String>] [-AllowUnencryptedAuthentication] [-Authentication <WebAuthenticationType>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-CertificateThumbprint <String>] [-Certificate <X509Certificate>] [-SkipCertificateCheck] [-SslProtocol <WebSslProtocol>] [-Token <SecureString>] [-UserAgent <String>] [-DisableKeepAlive] [-ConnectionTimeoutSeconds <Int32>] [-OperationTimeoutSeconds <Int32>] [-Headers <IDictionary>] [-SkipHeaderValidation] [-AllowInsecureRedirect] [-MaximumRedirection <Int32>] [-MaximumRetryCount <Int32>] [-PreserveAuthorizationOnRedirect] [-RetryIntervalSec <Int32>] [-Method <WebRequestMethod>] [-PreserveHttpMethodOnRedirect] [-UnixSocket <UnixDomainSocketEndPoint>] [-NoProxy] [-Body <Object>] [-Form <IDictionary>] [-ContentType <String>] [-TransferEncoding <String>] [-InFile <String>] [-OutFile <String>] [-PassThru] [-Resume] [-SkipHttpErrorCheck] [<CommonParameters>] ``` ### CustomMethod ``` Invoke-RestMethod [-FollowRelLink] [-MaximumFollowRelLink <Int32>] [-ResponseHeadersVariable <String>] [-StatusCodeVariable <String>] [-UseBasicParsing] [-Uri] <Uri> [-HttpVersion <Version>] [-WebSession <WebRequestSession>] [-SessionVariable <String>] [-AllowUnencryptedAuthentication] [-Authentication <WebAuthenticationType>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-CertificateThumbprint <String>] [-Certificate <X509Certificate>] [-SkipCertificateCheck] [-SslProtocol <WebSslProtocol>] [-Token <SecureString>] [-UserAgent <String>] [-DisableKeepAlive] [-ConnectionTimeoutSeconds <Int32>] [-OperationTimeoutSeconds <Int32>] [-Headers <IDictionary>] [-SkipHeaderValidation] [-AllowInsecureRedirect] [-MaximumRedirection <Int32>] [-MaximumRetryCount <Int32>] [-PreserveAuthorizationOnRedirect] [-RetryIntervalSec <Int32>] -CustomMethod <String> [-PreserveHttpMethodOnRedirect] [-UnixSocket <UnixDomainSocketEndPoint>] [-Proxy <Uri>] [-ProxyCredential <PSCredential>] [-ProxyUseDefaultCredentials] [-Body <Object>] [-Form <IDictionary>] [-ContentType <String>] [-TransferEncoding <String>] [-InFile <String>] [-OutFile <String>] [-PassThru] [-Resume] [-SkipHttpErrorCheck] [<CommonParameters>] ``` ### CustomMethodNoProxy ``` Invoke-RestMethod [-FollowRelLink] [-MaximumFollowRelLink <Int32>] [-ResponseHeadersVariable <String>] [-StatusCodeVariable <String>] [-UseBasicParsing] [-Uri] <Uri> [-HttpVersion <Version>] [-WebSession <WebRequestSession>] [-SessionVariable <String>] [-AllowUnencryptedAuthentication] [-Authentication <WebAuthenticationType>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-CertificateThumbprint <String>] [-Certificate <X509Certificate>] [-SkipCertificateCheck] [-SslProtocol <WebSslProtocol>] [-Token <SecureString>] [-UserAgent <String>] [-DisableKeepAlive] [-ConnectionTimeoutSeconds <Int32>] [-OperationTimeoutSeconds <Int32>] [-Headers <IDictionary>] [-SkipHeaderValidation] [-AllowInsecureRedirect] [-MaximumRedirection <Int32>] [-MaximumRetryCount <Int32>] [-PreserveAuthorizationOnRedirect] [-RetryIntervalSec <Int32>] -CustomMethod <String> [-PreserveHttpMethodOnRedirect] [-UnixSocket <UnixDomainSocketEndPoint>] [-NoProxy] [-Body <Object>] [-Form <IDictionary>] [-ContentType <String>] [-TransferEncoding <String>] [-InFile <String>] [-OutFile <String>] [-PassThru] [-Resume] [-SkipHttpErrorCheck] [<CommonParameters>] ``` ## DESCRIPTION The `Invoke-RestMethod` cmdlet sends HTTP and HTTPS requests to Representational State Transfer (REST) web services that return richly structured data. PowerShell formats the response based to the data type. For an RSS or ATOM feed, PowerShell returns the Item or Entry XML nodes. For JavaScript Object Notation (JSON) or XML, PowerShell converts, or deserializes, the content into `[pscustomobject]` objects. Comments are permitted in the JSON data. > [!NOTE] > When the REST endpoint returns multiple objects, the objects are received as an array. If you pipe > the output from `Invoke-RestMethod` to another command, it's sent as a single `[Object[]]` > object. The contents of that array aren't enumerated for the next command on the pipeline. This cmdlet is introduced in Windows PowerShell 3.0. Beginning in PowerShell 7.0, `Invoke-RestMethod` supports proxy configuration defined by environment variables. See the [NOTES](#notes) section of this article. Beginning in PowerShell 7.4, character encoding for requests defaults to UTF-8 instead of ASCII. If you need a different encoding, you must set the `charset` attribute in the `Content-Type` header. ## EXAMPLES ### Example 1: Get the PowerShell RSS feed This example uses the `Invoke-RestMethod` cmdlet to get information from the PowerShell Blog RSS feed. The command uses the `Format-Table` cmdlet to display the values of the **Title** and **pubDate** properties of each blog in a table. ```powershell Invoke-RestMethod -Uri https://blogs.msdn.microsoft.com/powershell/feed/ | Format-Table -Property Title, pubDate ``` ```Output Title pubDate ----- ------- Join the PowerShell 10th Anniversary Celebration! Tue, 08 Nov 2016 23:00:04 +0000 DSC Resource Kit November 2016 Release Thu, 03 Nov 2016 00:19:07 +0000 PSScriptAnalyzer Community Call - Oct 18, 2016 Thu, 13 Oct 2016 17:52:35 +0000 New Home for In-Box DSC Resources Sat, 08 Oct 2016 07:13:10 +0000 New Social Features on Gallery Fri, 30 Sep 2016 23:04:34 +0000 PowerShellGet and PackageManagement in PowerShell Gallery and GitHub Thu, 29 Sep 2016 22:21:42 +0000 PowerShell Security at DerbyCon Wed, 28 Sep 2016 01:13:19 +0000 DSC Resource Kit September Release Thu, 22 Sep 2016 00:25:37 +0000 PowerShell DSC and implicit remoting broken in KB3176934 Tue, 23 Aug 2016 15:07:50 +0000 PowerShell on Linux and Open Source! Thu, 18 Aug 2016 15:32:02 +0000 ``` ### Example 2: Run a POST request In this example, a user runs `Invoke-RestMethod` to do a POST request on an intranet website in the user's organization. ```powershell $Cred = Get-Credential $Url = "https://server.contoso.com:8089/services/search/jobs/export" $Body = @{ search = "search index=_internal | reverse | table index,host,source,sourcetype,_raw" output_mode = "csv" earliest_time = "-2d@d" latest_time = "-1d@d" } Invoke-RestMethod -Method 'Post' -Uri $url -Credential $Cred -Body $body -OutFile output.csv ``` The cmdlet prompts for credentials and stores them in `$Cred`. `$Url` contains the REST endpoint URL. The `$Body` variable describes the search criteria, specifies CSV as the output mode, and specifies a time period for returned data that starts two days ago and ends one day ago. The body variable specifies values for parameters that apply to the particular REST API with which `Invoke-RestMethod` is communicating. The `Invoke-RestMethod` command is run with all variables in place, specifying a path and file name for the resulting CSV output file. ### Example 3: Follow relation links Some REST APIs support pagination via Relation Links per [RFC5988](https://tools.ietf.org/html/rfc5988#page-6). Instead of parsing the header to get the URL for the next page, you can have the cmdlet do this for you. This example returns the first two pages of issues from the PowerShell GitHub repository. ```powershell $url = 'https://api.github.com/repos/powershell/powershell/issues' Invoke-RestMethod $url -FollowRelLink -MaximumFollowRelLink 2 ``` ### Example 4: Simplified Multipart/Form-Data Submission Some APIs require `multipart/form-data` submissions to upload files and mixed content. This example demonstrates how to update a user's profile. ```powershell $Uri = 'https://api.contoso.com/v2/profile' $Form = @{ firstName = 'John' lastName = 'Doe' email = 'john.doe@contoso.com' avatar = Get-Item -Path 'C:\Pictures\jdoe.png' birthday = '1980-10-15' hobbies = 'Hiking','Fishing','Jogging' } $Result = Invoke-RestMethod -Uri $Uri -Method Post -Form $Form ``` The profile form requires these fields: `firstName`, `lastName`, `email`, `avatar`, `birthday`, and `hobbies`. The API is expecting an image for the user profile pic to be supplied in the `avatar` field. The API also accepts multiple `hobbies` entries to be submitted in the same form. When creating the `$Form` HashTable, the key names are used as form field names. By default, the values of the HashTable are converted to strings. If a `System.IO.FileInfo` value is present, the file contents are submitted. If a collection, such as an array or list are present, the form field is submitted multiple times. By using `Get-Item` on the `avatar` key, the `FileInfo` object is set as the value. The result is that the image data for `jdoe.png` is submitted. By supplying a list to the `hobbies` key, the `hobbies` field is present in the submissions once for each list item. ### Example 5: Pass multiple headers APIs often require passed headers for authentication or validation. This example demonstrates, how to pass multiple headers from a `hash-table` to a REST API. ```powershell $headers = @{ 'userId' = 'UserIDValue' 'token' = 'TokenValue' } Invoke-RestMethod -Uri $uri -Method Post -Headers $headers -Body $body ``` ### Example 6: Enumerate returned items on the pipeline GitHub returns multiple objects an array. If you pipe the output to another command, it's sent as a single `[Object[]]`object. To enumerate the objects into the pipeline, pipe the results to `Write-Output` or wrap the cmdlet in parentheses. The following example counts the number of objects returned by GitHub. Then counts the number of objects enumerated to the pipeline. ```powershell $uri = 'https://api.github.com/repos/microsoftdocs/powershell-docs/issues' $x = 0 Invoke-RestMethod -Uri $uri | ForEach-Object { $x++ } $x 1 $x = 0 (Invoke-RestMethod -Uri $uri) | ForEach-Object { $x++ } $x 30 $x = 0 Invoke-RestMethod -Uri $uri | Write-Output | ForEach-Object { $x++ } $x 30 ``` ### Example 7: Skipping Header Validation By default, the `Invoke-RestMethod` cmdlet validates the values of well-known headers that have a standards-defined value format. The following example shows how this validation can raise an error and how you can use the **SkipHeaderValidation** parameter to avoid validating values for endpoints that tolerate invalidly formatted values. ```powershell $Uri = 'https://httpbin.org/headers' $InvalidHeaders = @{ 'If-Match' = '12345' } Invoke-RestMethod -Uri $Uri -Headers $InvalidHeaders Invoke-RestMethod -Uri $Uri -Headers $InvalidHeaders -SkipHeaderValidation | Format-List ``` ```Output Invoke-RestMethod: The format of value '12345' is invalid. headers : @{Host=httpbin.org; If-Match=12345; User-Agent=Mozilla/5.0 (Windows NT 10.0; Microsoft Windows 10.0.19044; en-US) PowerShell/7.2.5; X-Amzn-Trace-Id=Root=1-62f150a6-27754fd4226f31b43a3d2874} ``` [httpbin.org](https://httpbin.org/) is a service that returns information about web requests and responses for troubleshooting. The `$Uri` variable is assigned to the `/headers` endpoint of the service, which returns a request's headers as the content in its response. The `If-Match` request header is defined in [RFC-7232 section 3.1](https://www.rfc-editor.org/rfc/rfc7232.html#section-3.1) and requires the value for that header to be defined with surrounding quotes. The `$InvalidHeaders` variable is assigned a hash table where the value of `If-Match` is invalid because it's defined as `12345` instead of `"12345"`. Calling `Invoke-RestMethod` with the invalid headers returns an error reporting that the formatted value is invalid. The request isn't sent to the endpoint. Calling `Invoke-RestMethod` with the **SkipHeaderValidation** parameter ignores the validation failure and sends the request to the endpoint. Because the endpoint tolerates non-compliant header values, the cmdlet returns the response object without error. ### Example 8: Send a request using HTTP 2.0 This example queries for GitHub issue using the HTTP 2.0 protocol. ```powershell $uri = 'https://api.github.com/repos/microsoftdocs/powershell-docs/issues' Invoke-RestMethod -Uri $uri -HttpVersion 2.0 -SkipCertificateCheck ``` ### Example 9: Send a request to a Unix socket application Some applications, such as Docker, expose a Unix socket for communication. This example queries for a list of Docker images using the Docker API. The cmdlet connects to the Docker daemon using the Unix socket. ```powershell Invoke-RestMethod -Uri "http://localhost/v1.40/images/json/" -UnixSocket "/var/run/docker.sock" ``` ## PARAMETERS ### -AllowInsecureRedirect Allows redirecting from HTTPS to HTTP. By default, any request that's redirected from HTTPS to HTTP results in an error and the request is aborted to prevent unintentionally communicating in plain text over unencrypted connections. To override this behavior at your own risk, use the **AllowInsecureRedirect** parameter. This parameter was added in PowerShell 7.4. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -AllowUnencryptedAuthentication Allows sending of credentials and secrets over unencrypted connections. By default, supplying **Credential** or any **Authentication** option with a **Uri** that doesn't begin with `https://` results in an error and the request aborts to prevent unintentionally communicating secrets in plain text over unencrypted connections. To override this behavior at your own risk, supply the **AllowUnencryptedAuthentication** parameter. > [!WARNING] > Using this parameter isn't secure and isn't recommended. It's provided only for compatibility > with legacy systems that can't provide encrypted connections. Use at your own risk. This feature was added in PowerShell 6.0.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Authentication Specifies the explicit authentication type to use for the request. The default is **None**. The **Authentication** parameter can't be used with the **UseDefaultCredentials** parameter. Available Authentication Options: - `None`: This is the default option when **Authentication** isn't supplied. No explicit authentication is used. - `Basic`: Requires **Credential**. The credentials are used to send an RFC 7617 Basic Authentication `Authorization: Basic` header in the format of `base64(user:password)`. - `Bearer`: Requires the **Token** parameter. Sends an RFC 6750 `Authorization: Bearer` header with the supplied token. - `OAuth`: Requires the **Token** parameter. Sends an RFC 6750 `Authorization: Bearer` header with the supplied token. Supplying **Authentication** overrides any `Authorization` headers supplied to **Headers** or included in **WebSession**. This feature was added in PowerShell 6.0.0. ```yaml Type: Microsoft.PowerShell.Commands.WebAuthenticationType Parameter Sets: (All) Aliases: Accepted values: None, Basic, Bearer, OAuth Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Body Specifies the body of the request. The body is the content of the request that follows the headers. You can also pipe a body value to `Invoke-RestMethod`. The **Body** parameter can be used to specify a list of query parameters or specify the content of the response. For query parameters, the cmdlet uses the **System.Net.WebUtility.UrlEncode** method method to encode the key-value pairs. For more information about encoding strings for URLs, see [the UrlEncode() method reference](xref:System.Net.WebUtility.UrlEncode*). When the input is a POST request and the body is a **String**, the value to the left of the first equals sign (`=`) is set as a key in the form data and the remaining text is set as the value. To specify multiple keys, use an **IDictionary** object, such as a hash table, for the **Body**. When the input is a GET request and the body is an **IDictionary** (typically, a hash table), the body is added to the URI as query parameters. For other request types (such as PATCH), the body is set as the value of the request body in the standard `name=value` format with the values URL-encoded. When the input is a **System.Xml.XmlNode** object and the XML declaration specifies an encoding, that encoding is used for the data in the request unless overridden by the **ContentType** parameter. When the body is a form, or it's the output of another `Invoke-WebRequest` call, PowerShell sets the request content to the form fields. The **Body** parameter can also accept a **System.Net.Http.MultipartFormDataContent** object, which facilitates `multipart/form-data` requests. When a **MultipartFormDataContent** object is supplied for **Body**, any content related headers supplied to the **ContentType**, **Headers**, or **WebSession** parameters are overridden by the content headers of the `MultipartFormDataContent` object. This feature was added in PowerShell 6.0.0. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Certificate Specifies the client certificate that's used for a secure web request. Enter a variable that contains a certificate or a command or expression that gets the certificate. To find a certificate, use `Get-PfxCertificate` or use the `Get-ChildItem` cmdlet in the Certificate (`Cert:`) drive. If the certificate isn't valid or doesn't have sufficient authority, the command fails. ```yaml Type: System.Security.Cryptography.X509Certificates.X509Certificate Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to send the request. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. Certificates can only be mapped only to local user accounts, not domain accounts. To see the certificate thumbprint, use the `Get-Item` or `Get-ChildItem` command to find the certificate in `Cert:\CurrentUser\My`. > [!NOTE] > This feature is currently only supported on Windows OS platforms. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ConnectionTimeoutSeconds Specifies how long the request can be pending before it times out. Enter a value in seconds. The default value, 0, specifies an indefinite time-out. A Domain Name System (DNS) query can take up to 15 seconds to return or time out. If your request contains a host name that requires resolution, and you set **ConnectionTimeoutSeconds** to a value greater than zero, but less than 15 seconds, it can take 15 seconds or more before a **WebException** is thrown, and your request times out. This parameter replaced the **TimeoutSec** parameter in PowerShell 7.4. You can use **TimeoutSec** as an alias for **ConnectionTimeoutSeconds**. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: TimeoutSec Required: False Position: Named Default value: 0 Accept pipeline input: False Accept wildcard characters: False ``` ### -ContentType Specifies the content type of the web request. If the value for **ContentType** contains the encoding format (as `charset`), the cmdlet uses that format to encode the body of the web request. If the **ContentType** doesn't specify an encoding format, the default encoding format is used instead. An example of a **ContentType** with an encoding format is `text/plain; charset=iso-8859-5`, which specifies the [Latin/Cyrillic](https://www.iso.org/standard/28249.html) alphabet. If you omit the parameter, the content type may be different based on the HTTP method you use: - For a POST method, the content type is `application/x-www-form-urlencoded` - For a PUT method, the content type is `application/json` - For other methods, the content type isn't specified in the request If you are using the **InFile** parameter to upload a file, you should set the content type. Usually, the type should be `application/octet-stream`. However, you need to set the content type based on the requirements of the endpoint. **ContentType** is overridden when the **Body** is a [MultipartFormDataContent](xref:System.Net.Http.MultipartFormDataContent) object. Starting in PowerShell 7.4, if you use this both this parameter and the **Headers** parameter to define the `Content-Type` header, the value specified in the **ContentType** parameter is used. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to send the request. The default is the current user. Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. You can use **Credential** alone or in conjunction with certain **Authentication** parameter options. When used alone, it only supplies credentials to the remote server if the remote server sends an authentication challenge request. When used with **Authentication** options, the credentials is explicitly sent. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: False Accept wildcard characters: False ``` ### -CustomMethod Specifies custom method used for the web request. This can be used with the Request Method required by the endpoint isn't an available option on the **Method**. **Method** and **CustomMethod** can't be used together. Example: `Invoke-RestMethod -Uri 'https://api.contoso.com/widget/' -CustomMethod 'TEST'` This makes a `TEST` HTTP request to the API. This feature was added in PowerShell 6.0.0. ```yaml Type: System.String Parameter Sets: CustomMethod, CustomMethodNoProxy Aliases: CM Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DisableKeepAlive Sets the **KeepAlive** value in the HTTP header to False. By default, **KeepAlive** is True. **KeepAlive** establishes a persistent connection to the server to facilitate subsequent requests. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -FollowRelLink Indicates the cmdlet should follow relation links. Some REST APIs support pagination via Relation Links per [RFC5988](https://tools.ietf.org/html/rfc5988#section-5). Instead of parsing the header to get the URL for the next page, you can have the cmdlet do this for you. To set how many times to follow relation links, use the **MaximumFollowRelLink** parameter. When using this switch, the cmdlet returns a collection of pages of results. Each page of results may contain multiple result items. This feature was added in PowerShell 6.0.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: FL Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Form Converts a dictionary to a `multipart/form-data` submission. **Form** may not be used with **Body**. The **ContentType** is ignored. The keys of the dictionary are used as the form field names. By default, form values are converted to string values. If the value is a **System.IO.FileInfo** object, then the binary file contents is submitted. The name of the file is submitted as the `filename`. The MIME type is set as `application/octet-stream`. `Get-Item` can be used to simplify supplying the **System.IO.FileInfo** object. ```powershell $Form = @{ resume = Get-Item 'C:\Users\jdoe\Documents\John Doe.pdf' } ``` If the value is a collection type, such as an Array or List, the form field is submitted multiple times. The values of the list are treated as strings by default. If the value is a **System.IO.FileInfo** object, then the binary file contents are submitted. Nested collections aren't supported. ```powershell $Form = @{ tags = 'Vacation', 'Italy', '2017' pictures = Get-ChildItem 'C:\Users\jdoe\Pictures\2017-Italy\' } ``` In the above example, the `tags` field is supplied three times in the form, once for each of the values: `Vacation`, `Italy`, and `2017`. The `pictures` field is submitted once for each file in the `2017-Italy` folder. The binary contents of the files in that folder are submitted as the values. This feature was added in PowerShell 6.1.0. ```yaml Type: System.Collections.IDictionary Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Headers Specifies the headers of the web request. Enter a hash table or dictionary. Content related headers, such as `Content-Type` are overridden when a `MultipartFormDataContent` object is supplied for **Body**. Starting in PowerShell 7.4, if you use this parameter to define the `Content-Type` header and use **ContentType** parameter, the value specified in the **ContentType** parameter is used. ```yaml Type: System.Collections.IDictionary Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -HttpVersion Specifies the HTTP version used for the request. The default is `1.1`. Valid values are: - 1.0 - 1.1 - 2.0 - 3.0 ```yaml Type: System.Version Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InFile Gets the content of the web request body from a file. Enter a path and filename. If you omit the path, the default is the current location. You also need to set the content type of the request. For example, to upload a file you should set the content type. Usually, the type should be `application/octet-stream`. However, you need to set the content type based on the requirements of the endpoint. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumFollowRelLink Specifies how many times to follow relation links if **FollowRelLink** is used. A smaller value may be needed if the REST api throttles due to too many requests. The default value is `[int32]::MaxValue`. A value of 0 (zero) prevents following relation links. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: ML Required: False Position: Named Default value: Int32.MaxValue Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumRedirection Specifies how many times PowerShell redirects a connection to an alternate Uniform Resource Identifier (URI) before the connection fails. The default value is 5. A value of 0 (zero) prevents all redirection. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumRetryCount Specifies how many times PowerShell retries a connection when a failure code between 400 and 599, inclusive or 304 is received. Also see **RetryIntervalSec** parameter for specifying the interval between retries. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Method Specifies the method used for the web request. The acceptable values for this parameter are: - `Default` - `Delete` - `Get` - `Head` - `Merge` - `Options` - `Patch` - `Post` - `Put` - `Trace` The **CustomMethod** parameter can be used for Request Methods not listed above. ```yaml Type: Microsoft.PowerShell.Commands.WebRequestMethod Parameter Sets: StandardMethod, StandardMethodNoProxy Aliases: Accepted values: Default, Get, Head, Post, Put, Delete, Trace, Options, Merge, Patch Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NoProxy Indicates that the cmdlet won't use a proxy to reach the destination. Use this to bypass the proxy configured in your internet settings or specified in the environment. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: StandardMethodNoProxy, CustomMethodNoProxy Aliases: Required: True Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -OperationTimeoutSeconds This timeout applies to data reads within a stream, not to the stream time as a whole. The default value, 0, specifies an indefinite timeout. Setting the value to 30 seconds means that any delay of longer than 30 seconds between data in the stream terminates the request. A large file that takes several minutes to download won't terminate unless the stream stalls for more than 30 seconds. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OutFile By default, `Invoke-RestMethod` returns the results to the pipeline. When you use the **OutFile** parameter, the results are saved to the specified file and not returned to the pipeline. Enter a path and filename. To send the results to a file and to the pipeline, add the **PassThru** parameter. If you omit the path, the default is the current location. The name is treated as a literal path. Names that contain brackets (`[]`) must be enclosed in single quotes (`'`). Starting in PowerShell 7.4, you can specify a folder path without the filename. When you do, the command uses filename from the last segment of the resolved URI after any redirections. When you specify a folder path for **OutFile**, you can't use the **Resume** parameter. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru This parameter is valid only when the **OutFile** parameter is also used in the command. The intent is to have the results written to the file and to the pipeline. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: No output Accept pipeline input: False Accept wildcard characters: False ``` ### -PreserveAuthorizationOnRedirect Indicates the cmdlet should preserve the `Authorization` header, when present, across redirections. By default, the cmdlet strips the `Authorization` header before redirecting. Specifying this parameter disables this logic for cases where the header needs to be sent to the redirection location. This feature was added in PowerShell 6.0.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -PreserveHttpMethodOnRedirect Indicates the cmdlet should preserve the method of the request across redirections. By default, the cmdlet changes the method to `GET` when redirected. Specifying this parameter disables this logic to ensure that the intended method can be used with redirection. This feature was added in PowerShell 7.4. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Proxy Uses a proxy server for the request, rather than connecting directly to the internet resource. Enter the Uniform Resource Identifier (URI) of a network proxy server. This feature was added in PowerShell 6.0.0. ```yaml Type: System.Uri Parameter Sets: StandardMethod, CustomMethod Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProxyCredential Specifies a user account that has permission to use the proxy server that's specified by the **Proxy** parameter. The default is the current user. Type a user name, such as "User01" or "Domain01\User01", or enter a **PSCredential** object, such as one generated by the `Get-Credential` cmdlet. This parameter is valid only when the **Proxy** parameter is also used in the command. You can't use the **ProxyCredential** and **ProxyUseDefaultCredentials** parameters in the same command. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: StandardMethod, CustomMethod Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProxyUseDefaultCredentials Uses the credentials of the current user to access the proxy server that is specified by the **Proxy** parameter. This parameter is valid only when the **Proxy** parameter is also used in the command. You can't use the **ProxyCredential** and **ProxyUseDefaultCredentials** parameters in the same command. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: StandardMethod, CustomMethod Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ResponseHeadersVariable Creates a variable containing a Response Headers Dictionary. Enter a variable name without the dollar sign (`$`) symbol. The keys of the dictionary contain the field names and values of the Response Header returned by the web server. This feature was added in PowerShell 6.0.0. ```yaml Type: System.String Parameter Sets: (All) Aliases: RHV Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Resume Performs a best effort attempt to resume downloading a partial file. The **Resume** parameter requires the **OutFile** parameter. **Resume** only operates on the size of the local file and remote file and performs no other validation that the local file and the remote file are the same. If the local file size is smaller than the remote file size, then the cmdlet attempts to resume downloading the file and append the remaining bytes to the end of the file. If the local file size is the same as the remote file size, then no action is taken and the cmdlet assumes the download already completed. If the local file size is larger than the remote file size, then the local file is overwritten and the entire remote file is re-downloaded. This behavior is the same as using **OutFile** without **Resume**. If the remote server doesn't support download resuming, then the local file is overwritten and the entire remote file is re-downloaded. This behavior is the same as using **OutFile** without **Resume**. If the local file doesn't exist, then the local file is created and the entire remote file is downloaded. This behavior is the same as using **OutFile** without **Resume**. This feature was added in PowerShell 6.1.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -RetryIntervalSec Specifies the interval between retries for the connection when a failure code between 400 and 599, inclusive or 304 is received. The value must be between `1` and `[int]::MaxValue`. When the failure code is 429 and the response includes the **Retry-After** property in its headers, the cmdlet uses that value for the retry interval, even if this parameter is specified. Also, see the **MaximumRetryCount** parameter for specifying number of retries. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 5 Accept pipeline input: False Accept wildcard characters: False ``` ### -SessionVariable Creates a variable containing the web request session. Enter a variable name without the dollar sign (`$`) symbol. When you specify a session variable, `Invoke-RestMethod` creates a web request session object and assigns it to a variable with the specified name in your PowerShell session. You can use the variable in your session as soon as the command completes. Before PowerShell 7.4, the web request session isn't a persistent connection. It's an object that contains information about the connection and the request, including cookies, credentials, the maximum redirection value, and the user agent string. You can use it to share state and data among web requests. Starting in PowerShell 7.4, the web request session is persistent as long as the properties of the session aren't overridden in a subsequent request. When they are, the cmdlet recreates the session with the new values. The persistent sessions reduce the overhead for repeated requests, making them much faster. To use the web request session in subsequent web requests, specify the session variable in the value of the **WebSession** parameter. PowerShell uses the data in the web request session object when establishing the new connection. To override a value in the web request session, use a cmdlet parameter, such as **UserAgent** or **Credential**. Parameter values take precedence over values in the web request session. You can't use the **SessionVariable** and **WebSession** parameters in the same command. ```yaml Type: System.String Parameter Sets: (All) Aliases: SV Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipCertificateCheck Skips certificate validation checks that include all validations such as expiration, revocation, trusted root authority, etc. > [!WARNING] > Using this parameter isn't secure and isn't recommended. This switch is only intended to be used > against known hosts using a self-signed certificate for testing purposes. Use at your own risk. This feature was added in PowerShell 6.0.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipHeaderValidation Indicates the cmdlet should add headers to the request without validation. This switch should be used for sites that require header values that don't conform to standards. Specifying this switch disables validation to allow the value to be passed unchecked. When specified, all headers are added without validation. This switch disables validation for values passed to the **ContentType**, **Headers**, and **UserAgent** parameters. This feature was added in PowerShell 6.0.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipHttpErrorCheck This parameter causes the cmdlet to ignore HTTP error statuses and continue to process responses. The error responses are written to the pipeline just as if they were successful. This parameter was introduced in PowerShell 7. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -SslProtocol Sets the SSL/TLS protocols that are permissible for the web request. By default all, SSL/TLS protocols supported by the system are allowed. **SslProtocol** allows for limiting to specific protocols for compliance purposes. These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **SslProtocol** parameter as an array of values or as a comma-separated string of those values. The cmdlet combines the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. You may not be able to supply multiple values on all platforms. This feature was added in PowerShell 6.0.0. Support for `Tls13` was added in PowerShell 7.1. ```yaml Type: Microsoft.PowerShell.Commands.WebSslProtocol Parameter Sets: (All) Aliases: Accepted values: Default, Tls, Tls11, Tls12, Tls13 Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -StatusCodeVariable Creates a variable containing a HTTP status code result of the request. Enter a variable name without the dollar sign (`$`) symbol. The parameter can identify success messages or failure messages when used with the **SkipHttpErrorCheck** parameter. Input the parameter's variable name as a string such as `-StatusCodeVariable "scv"`. This parameter was introduced in PowerShell 7. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Token The OAuth or Bearer token to include in the request. **Token** is required by certain **Authentication** options. It can't be used independently. **Token** takes a `SecureString` that contains the token. To supply the token, manually use the following: `Invoke-RestMethod -Uri $uri -Authentication OAuth -Token (Read-Host -AsSecureString)` This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Security.SecureString Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TransferEncoding Specifies a value for the transfer-encoding HTTP response header. The acceptable values for this parameter are: - Chunked - Compress - Deflate - GZip - Identity ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: chunked, compress, deflate, gzip, identity Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UnixSocket Specifies the name of the Unix socket to connect to. This parameter is supported on Unix-based systems and Windows version 1803 and later. For more information about Windows support of Unix sockets, see the [Windows/WSL Interop with AF_UNIX](https://devblogs.microsoft.com/commandline/windowswsl-interop-with-af_unix/) blog post. This parameter was added in PowerShell 7.4. ```yaml Type: System.Net.Sockets.UnixDomainSocketEndPoint Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Uri Specifies the Uniform Resource Identifier (URI) of the internet resource to which the web request is sent. This parameter supports HTTP, HTTPS, FTP, and FILE values. This parameter is required. The parameter name (**Uri**) is optional. ```yaml Type: System.Uri Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseBasicParsing This parameter has been deprecated. Beginning with PowerShell 6.0.0, all Web requests use basic parsing only. This parameter is included for backwards compatibility only. When used, it has no effect on the operation of the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -UseDefaultCredentials Indicates that the cmdlet uses the credentials of the current user to send the web request. This can't be used with **Authentication** or **Credential** and may not be supported on all platforms. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -UserAgent Specifies a user agent string for the web request. The default user agent is similar to `Mozilla/5.0 (Windows NT 10.0; Microsoft Windows 10.0.15063; en-US) PowerShell/6.0.0` with slight variations for each operating system and platform. To test a website with the standard user agent string that's used by most internet browsers, use the properties of the [PSUserAgent](xref:Microsoft.PowerShell.Commands.PSUserAgent) class, such as Chrome, Firefox, InternetExplorer, Opera, and Safari. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WebSession Specifies a web request session. Enter the variable name, including the dollar sign (`$`). To override a value in the web request session, use a cmdlet parameter, such as **UserAgent** or **Credential**. Parameter values take precedence over values in the web request session. Content related headers, such as `Content-Type`, are overridden when a **MultipartFormDataContent** object is supplied for **Body**. Unlike a remote session, the web request session isn't a persistent connection. It's an object that contains information about the connection and the request, including cookies, credentials, the maximum redirection value, and the user agent string. You can use it to share state and data among web requests. To create a web request session, enter a variable name, without a dollar sign, in the value of the **SessionVariable** parameter of an `Invoke-RestMethod` command. `Invoke-RestMethod` creates the session and saves it in the variable. In subsequent commands, use the variable as the value of the **WebSession** parameter. You can't use the **SessionVariable** and **WebSession** parameters in the same command. ```yaml Type: Microsoft.PowerShell.Commands.WebRequestSession Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -ProgressAction, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Object You can pipe the body of a web request to this cmdlet. ## OUTPUTS ### System.Int64 When the request returns an integer, this cmdlet returns that integer. ### System.String When the request returns a string, this cmdlet returns that string. ### System.Xml.XmlDocument When the request returns valid XML, this cmdlet returns it as an **XmlDocument**. ### PSObject When the request returns JSON strings, this cmdlet returns a **PSObject** representing the data. ## NOTES PowerShell includes the following aliases for `Invoke-RestMethod`: - All platforms: - `irm` Some features may not be available on all platforms. Because of changes in .NET Core 3.1, PowerShell 7.0 and higher use the [HttpClient.DefaultProxy](xref:System.Net.Http.HttpClient.DefaultProxy*) property to determine the proxy configuration. The value of this property differ depending on your platform: - **For Windows**: Reads proxy configuration from environment variables or, if those aren't defined, from the user's proxy settings. - **For macOS**: Reads proxy configuration from environment variables or, if those aren't defined, from the system's proxy settings. - **For Linux**: Reads proxy configuration from environment variables or, in case those aren't defined, this property initializes a non-configured instance that bypasses all addresses. The environment variables used for `DefaultProxy` initialization on Windows and Unix-based platforms are: - `HTTP_PROXY`: the hostname or IP address of the proxy server used on HTTP requests. - `HTTPS_PROXY`: the hostname or IP address of the proxy server used on HTTPS requests. - `ALL_PROXY`: the hostname or IP address of the proxy server used on HTTP and HTTPS requests in case `HTTP_PROXY` or `HTTPS_PROXY` aren't defined. - `NO_PROXY`: a comma-separated list of hostnames that should be excluded from proxying. PowerShell 7.4 added support for the Brotli compression algorithm. ## RELATED LINKS [ConvertTo-Json](ConvertTo-Json.md) [ConvertFrom-Json](ConvertFrom-Json.md) [Invoke-WebRequest](Invoke-WebRequest.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Invoke-WebRequest.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 02/05/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Invoke-WebRequest --- # Invoke-WebRequest ## SYNOPSIS Gets content from a web page on the internet. ## SYNTAX ### StandardMethod (Default) ``` Invoke-WebRequest [-UseBasicParsing] [-Uri] <Uri> [-HttpVersion <Version>] [-WebSession <WebRequestSession>] [-SessionVariable <String>] [-AllowUnencryptedAuthentication] [-Authentication <WebAuthenticationType>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-CertificateThumbprint <String>] [-Certificate <X509Certificate>] [-SkipCertificateCheck] [-SslProtocol <WebSslProtocol>] [-Token <SecureString>] [-UserAgent <String>] [-DisableKeepAlive] [-ConnectionTimeoutSeconds <Int32>] [-OperationTimeoutSeconds <Int32>] [-Headers <IDictionary>] [-SkipHeaderValidation] [-AllowInsecureRedirect] [-MaximumRedirection <Int32>] [-MaximumRetryCount <Int32>] [-PreserveAuthorizationOnRedirect] [-RetryIntervalSec <Int32>] [-Method <WebRequestMethod>] [-PreserveHttpMethodOnRedirect] [-UnixSocket <UnixDomainSocketEndPoint>] [-Proxy <Uri>] [-ProxyCredential <PSCredential>] [-ProxyUseDefaultCredentials] [-Body <Object>] [-Form <IDictionary>] [-ContentType <String>] [-TransferEncoding <String>] [-InFile <String>] [-OutFile <String>] [-PassThru] [-Resume] [-SkipHttpErrorCheck] [<CommonParameters>] ``` ### StandardMethodNoProxy ``` Invoke-WebRequest [-UseBasicParsing] [-Uri] <Uri> [-HttpVersion <Version>] [-WebSession <WebRequestSession>] [-SessionVariable <String>] [-AllowUnencryptedAuthentication] [-Authentication <WebAuthenticationType>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-CertificateThumbprint <String>] [-Certificate <X509Certificate>] [-SkipCertificateCheck] [-SslProtocol <WebSslProtocol>] [-Token <SecureString>] [-UserAgent <String>] [-DisableKeepAlive] [-ConnectionTimeoutSeconds <Int32>] [-OperationTimeoutSeconds <Int32>] [-Headers <IDictionary>] [-SkipHeaderValidation] [-AllowInsecureRedirect] [-MaximumRedirection <Int32>] [-MaximumRetryCount <Int32>] [-PreserveAuthorizationOnRedirect] [-RetryIntervalSec <Int32>] [-Method <WebRequestMethod>] [-PreserveHttpMethodOnRedirect] [-UnixSocket <UnixDomainSocketEndPoint>] [-NoProxy] [-Body <Object>] [-Form <IDictionary>] [-ContentType <String>] [-TransferEncoding <String>] [-InFile <String>] [-OutFile <String>] [-PassThru] [-Resume] [-SkipHttpErrorCheck] [<CommonParameters>] ``` ### CustomMethod ``` Invoke-WebRequest [-UseBasicParsing] [-Uri] <Uri> [-HttpVersion <Version>] [-WebSession <WebRequestSession>] [-SessionVariable <String>] [-AllowUnencryptedAuthentication] [-Authentication <WebAuthenticationType>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-CertificateThumbprint <String>] [-Certificate <X509Certificate>] [-SkipCertificateCheck] [-SslProtocol <WebSslProtocol>] [-Token <SecureString>] [-UserAgent <String>] [-DisableKeepAlive] [-ConnectionTimeoutSeconds <Int32>] [-OperationTimeoutSeconds <Int32>] [-Headers <IDictionary>] [-SkipHeaderValidation] [-AllowInsecureRedirect] [-MaximumRedirection <Int32>] [-MaximumRetryCount <Int32>] [-PreserveAuthorizationOnRedirect] [-RetryIntervalSec <Int32>] -CustomMethod <String> [-PreserveHttpMethodOnRedirect] [-UnixSocket <UnixDomainSocketEndPoint>] [-Proxy <Uri>] [-ProxyCredential <PSCredential>] [-ProxyUseDefaultCredentials] [-Body <Object>] [-Form <IDictionary>] [-ContentType <String>] [-TransferEncoding <String>] [-InFile <String>] [-OutFile <String>] [-PassThru] [-Resume] [-SkipHttpErrorCheck] [<CommonParameters>] ``` ### CustomMethodNoProxy ``` Invoke-WebRequest [-UseBasicParsing] [-Uri] <Uri> [-HttpVersion <Version>] [-WebSession <WebRequestSession>] [-SessionVariable <String>] [-AllowUnencryptedAuthentication] [-Authentication <WebAuthenticationType>] [-Credential <PSCredential>] [-UseDefaultCredentials] [-CertificateThumbprint <String>] [-Certificate <X509Certificate>] [-SkipCertificateCheck] [-SslProtocol <WebSslProtocol>] [-Token <SecureString>] [-UserAgent <String>] [-DisableKeepAlive] [-ConnectionTimeoutSeconds <Int32>] [-OperationTimeoutSeconds <Int32>] [-Headers <IDictionary>] [-SkipHeaderValidation] [-AllowInsecureRedirect] [-MaximumRedirection <Int32>] [-MaximumRetryCount <Int32>] [-PreserveAuthorizationOnRedirect] [-RetryIntervalSec <Int32>] -CustomMethod <String> [-PreserveHttpMethodOnRedirect] [-UnixSocket <UnixDomainSocketEndPoint>] [-NoProxy] [-Body <Object>] [-Form <IDictionary>] [-ContentType <String>] [-TransferEncoding <String>] [-InFile <String>] [-OutFile <String>] [-PassThru] [-Resume] [-SkipHttpErrorCheck] [<CommonParameters>] ``` ## DESCRIPTION The `Invoke-WebRequest` cmdlet sends HTTP and HTTPS requests to a web page or web service. It parses the response and returns collections of links, images, and other significant HTML elements. This cmdlet was introduced in PowerShell 3.0. Beginning in PowerShell 7.0, `Invoke-WebRequest` supports proxy configuration defined by environment variables. See the [Notes](#notes) section of this article. > [!IMPORTANT] > The examples in this article reference hosts in the `contoso.com` domain. This is a fictitious > domain used by Microsoft for examples. The examples are designed to show how to use the cmdlets. > However, since the `contoso.com` sites don't exist, the examples don't work. Adapt the examples > to hosts in your environment. Beginning in PowerShell 7.4, character encoding for requests defaults to UTF-8 instead of ASCII. If you need a different encoding, you must set the `charset` attribute in the `Content-Type` header. ## EXAMPLES ### Example 1: Send a web request This example uses the `Invoke-WebRequest` cmdlet to send a web request to the Bing.com site. ```powershell $Response = Invoke-WebRequest -Uri https://www.bing.com/search?q=how+many+feet+in+a+mile $Response.InputFields | Where-Object { $_.Name -like "* Value*" } | Select-Object Name, Value ``` ```Output Name Value ---- ----- From Value 1 To Value 5280 ``` The first command issues the request and saves the response in the `$Response` variable. The second command gets any **InputField** where the **Name** property is like `"* Value"`. The filtered results are piped to `Select-Object` to select the **Name** and **Value** properties. ### Example 2: Use a stateful web service This example shows how to use the `Invoke-WebRequest` cmdlet with a stateful web service. ```powershell $LoginParameters = @{ Uri = 'https://www.contoso.com/login/' SessionVariable = 'Session' Method = 'POST' Body = @{ User = 'jdoe' Password = 'P@S$w0rd!' } } $LoginResponse = Invoke-WebRequest @LoginParameters $ProfileResponse = Invoke-WebRequest 'https://www.contoso.com/profile/' -WebSession $Session ``` The first call to `Invoke-WebRequest` sends a sign-in request. The command specifies a value of `Session` for the value of the **SessionVariable** parameter. When the command completes, the `$LoginResponse` variable contains an **BasicHtmlWebResponseObject** and the `$Session` variable contains a `WebRequestSession` object. This logs the user into the site. The second call to `Invoke-WebRequest` fetches the user's profile, which requires the user be signed into the site. The session data stored in the `$Session` variable provides session cookies to the site created during the login. ### Example 3: Get links from a web page This example gets the links in a web page. It uses the `Invoke-WebRequest` cmdlet to get the web page content. Then it uses the **Links** property of the **BasicHtmlWebResponseObject** that `Invoke-WebRequest` returns, and the **Href** property of each link. ```powershell (Invoke-WebRequest -Uri "https://aka.ms/pscore6-docs").Links.Href ``` ### Example 4: Write response content to a file using the encoding defined in the requested page This example uses the `Invoke-WebRequest` cmdlet to retrieve the web page content of a PowerShell documentation page. ```powershell $Response = Invoke-WebRequest -Uri "https://aka.ms/pscore6-docs" $Stream = [System.IO.StreamWriter]::new('.\docspage.html', $false, $Response.Encoding) try { $Stream.Write($Response.Content) } finally { $Stream.Dispose() } ``` The first command retrieves the page and saves the response object in the `$Response` variable. The second command creates a **StreamWriter** to use to write the response content to a file. The **Encoding** property of the response object is used to set the encoding for the file. The final few commands write the **Content** property to the file then disposes the **StreamWriter**. Note that the **Encoding** property is null if the web request doesn't return text content. ### Example 5: Submit a multipart/form-data file This example uses the `Invoke-WebRequest` cmdlet upload a file as a `multipart/form-data` submission. The file `C:\document.txt` is submitted as the form field `document` with the `Content-Type` of `text/plain`. ```powershell $FilePath = 'C:\document.txt' $FieldName = 'document' $ContentType = 'text/plain' $FileStream = [System.IO.FileStream]::new($filePath, [System.IO.FileMode]::Open) $FileHeader = [System.Net.Http.Headers.ContentDispositionHeaderValue]::new('form-data') $FileHeader.Name = $FieldName $FileHeader.FileName = Split-Path -Leaf $FilePath $FileContent = [System.Net.Http.StreamContent]::new($FileStream) $FileContent.Headers.ContentDisposition = $FileHeader $FileContent.Headers.ContentType = [System.Net.Http.Headers.MediaTypeHeaderValue]::Parse($ContentType) $MultipartContent = [System.Net.Http.MultipartFormDataContent]::new() $MultipartContent.Add($FileContent) $Response = Invoke-WebRequest -Body $MultipartContent -Method 'POST' -Uri 'https://api.contoso.com/upload' ``` ### Example 6: Simplified Multipart/Form-Data Submission Some APIs require `multipart/form-data` submissions to upload files and mixed content. This example demonstrates updating a user profile. ```powershell $Uri = 'https://api.contoso.com/v2/profile' $Form = @{ firstName = 'John' lastName = 'Doe' email = 'john.doe@contoso.com' avatar = Get-Item -Path 'C:\Pictures\jdoe.png' birthday = '1980-10-15' hobbies = 'Hiking','Fishing','Jogging' } $Result = Invoke-WebRequest -Uri $Uri -Method Post -Form $Form ``` The profile form requires these fields: `firstName`, `lastName`, `email`, `avatar`, `birthday`, and `hobbies`. The API is expecting an image for the user profile pic to be supplied in the `avatar` field. The API also accepts multiple `hobbies` entries to be submitted in the same form. When creating the `$Form` HashTable, the key names are used as form field names. By default, the values of the HashTable are converted to strings. If a **System.IO.FileInfo** value is present, the file contents are submitted. If a collection such as arrays or lists are present, the form field is submitted multiple times. Using `Get-Item` on the `avatar` key, the `FileInfo` object is set as the value. The result is that the image data for `jdoe.png` is submitted. By supplying a list to the `hobbies` key, the `hobbies` field is present in the submissions once for each list item. ### Example 7: Catch non success messages from Invoke-WebRequest When `Invoke-WebRequest` encounters a non-success HTTP message (404, 500, etc.), it returns no output and throws a terminating error. To catch the error and view the **StatusCode** you can enclose execution in a `try/catch` block. ```powershell try { $Response = Invoke-WebRequest -Uri "www.microsoft.com/unkownhost" # This will only execute if the Invoke-WebRequest is successful. $StatusCode = $Response.StatusCode } catch { $StatusCode = $_.Exception.Response.StatusCode.value__ } $StatusCode ``` ```Output 404 ``` The terminating error is caught by the `catch` block, which retrieves the **StatusCode** from the **Exception** object. ### Example 8: Download multiple files at the same time The `Invoke-WebRequest` cmdlet can only download one file at a time. The following example uses `Start-ThreadJob` to create multiple thread jobs to download multiple files at the same time. ```powershell $baseUri = 'https://github.com/PowerShell/PowerShell/releases/download' $files = @( @{ Uri = "$baseUri/v7.3.0-preview.5/PowerShell-7.3.0-preview.5-win-x64.msi" OutFile = 'PowerShell-7.3.0-preview.5-win-x64.msi' }, @{ Uri = "$baseUri/v7.3.0-preview.5/PowerShell-7.3.0-preview.5-win-x64.zip" OutFile = 'PowerShell-7.3.0-preview.5-win-x64.zip' }, @{ Uri = "$baseUri/v7.2.5/PowerShell-7.2.5-win-x64.msi" OutFile = 'PowerShell-7.2.5-win-x64.msi' }, @{ Uri = "$baseUri/v7.2.5/PowerShell-7.2.5-win-x64.zip" OutFile = 'PowerShell-7.2.5-win-x64.zip' } ) $jobs = @() foreach ($file in $files) { $jobs += Start-ThreadJob -Name $file.OutFile -ScriptBlock { $params = $Using:file Invoke-WebRequest @params } } Write-Host "Downloads started..." Wait-Job -Job $jobs foreach ($job in $jobs) { Receive-Job -Job $job } ``` ### Example 9: Skipping Header Validation By default, the `Invoke-WebRequest` cmdlet validates the values of well-known headers that have a standards-defined value format. The following example shows how this validation can raise an error and how you can use the **SkipHeaderValidation** parameter to avoid validating values for endpoints that tolerate invalidly formatted values. ```powershell $Uri = 'https://httpbin.org/headers' $InvalidHeaders = @{ 'If-Match' = '12345' } Invoke-WebRequest -Uri $Uri -Headers $InvalidHeaders Invoke-WebRequest -Uri $Uri -Headers $InvalidHeaders -SkipHeaderValidation ``` ```Output Invoke-WebRequest: The format of value '12345' is invalid. StatusCode : 200 StatusDescription : OK Content : { "headers": { "Host": "httpbin.org", "If-Match": "12345", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Microsoft Windows 10.0.19044; en-US) PowerShell/7.2.5", "X-Amzn-Trace-Id": � RawContent : HTTP/1.1 200 OK Date: Mon, 08 Aug 2022 16:24:24 GMT Connection: keep-alive Server: gunicorn/19.9.0 Access-Control-Allow-Origin: * Access-Control-Allow-Credentials: true Content-Type: application� Headers : {[Date, System.String[]], [Connection, System.String[]], [Server, System.String[]], [Access-Control-Allow-Origin, System.String[]]�} Images : {} InputFields : {} Links : {} RawContentLength : 249 RelationLink : {} ``` [httpbin.org](https://httpbin.org/) is a service that returns information about web requests and responses for troubleshooting. The `$Uri` variable is assigned to the `/headers` endpoint of the service, which returns a request's headers as the content in its response. The `If-Match` request header is defined in [RFC-7232 section 3.1](https://www.rfc-editor.org/rfc/rfc7232.html#section-3.1) and requires the value for that header to be defined with surrounding quotes. The `$InvalidHeaders` variable is assigned a hash table where the value of `If-Match` is invalid because it's defined as `12345` instead of `"12345"`. Calling `Invoke-WebRequest` with the invalid headers returns an error reporting that the formatted value is invalid. The request is not sent to the endpoint. Calling `Invoke-WebRequest` with the **SkipHeaderValidation** parameter ignores the validation failure and sends the request to the endpoint. Because the endpoint tolerates non-compliant header values, the cmdlet returns the response object without error. ### Example 10: Send a request using HTTP 2.0 This example gets the links in a web page using the HTTP 2.0 protocol. It uses the `Invoke-WebRequest` cmdlet to get the web page content. Then it uses the **Links** property of the **BasicHtmlWebResponseObject** that `Invoke-WebRequest` returns, and the **Href** property of each link. ```powershell (Invoke-WebRequest -Uri 'https://aka.ms/pscore6-docs' -HttpVersion 2.0).Links.Href ``` ### Example 11: Send a request to a Unix socket application Some applications, such as Docker, expose a Unix socket for communication. This example queries for a list of Docker images using the Docker API. The cmdlet connects to the Docker daemon using the Unix socket. ```powershell Invoke-WebRequest -Uri "http://localhost/v1.40/images/json/" -UnixSocket "/var/run/docker.sock" ``` ## PARAMETERS ### -AllowInsecureRedirect Allows redirecting from HTTPS to HTTP. By default, any request that is redirected from HTTPS to HTTP results in an error and the request is aborted to prevent unintentionally communicating in plain text over unencrypted connections. To override this behavior at your own risk, use the **AllowInsecureRedirect** parameter. This parameter was added in PowerShell 7.4. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -AllowUnencryptedAuthentication Allows sending of credentials and secrets over unencrypted connections. By default, supplying **Credential** or any **Authentication** option with a **Uri** that doesn't begin with `https://` results in an error and the request is aborted to prevent unintentionally communicating secrets in plain text over unencrypted connections. To override this behavior at your own risk, supply the **AllowUnencryptedAuthentication** parameter. > [!WARNING] > Using this parameter isn't secure and isn't recommended. It is provided only for compatibility > with legacy systems that can't provide encrypted connections. Use at your own risk. This feature was added in PowerShell 6.0.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Authentication Specifies the explicit authentication type to use for the request. The default is **None**. The **Authentication** parameter can't be used with the **UseDefaultCredentials** parameter. Available Authentication Options: - `None`: This is the default option when **Authentication** isn't supplied. No explicit authentication is used. - `Basic`: Requires **Credential**. The credentials are sent as an RFC 7617 Basic Authentication `Authorization: Basic` header in the format of `base64(user:password)`. - `Bearer`: Requires the **Token** parameter. Sends an RFC 6750 `Authorization: Bearer` header with the supplied token. - `OAuth`: Requires the **Token** parameter. Sends an RFC 6750 `Authorization: Bearer` header with the supplied token. Supplying **Authentication** overrides any `Authorization` headers supplied to **Headers** or included in **WebSession**. This feature was added in PowerShell 6.0.0. ```yaml Type: Microsoft.PowerShell.Commands.WebAuthenticationType Parameter Sets: (All) Aliases: Accepted values: None, Basic, Bearer, OAuth Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Body Specifies the body of the request. The body is the content of the request that follows the headers. You can also pipe a body value to `Invoke-WebRequest`. The **Body** parameter can be used to specify a list of query parameters or specify the content of the response. For query parameters, the cmdlet uses the **System.Net.WebUtility.UrlEncode** method method to encode the key-value pairs. For more information about encoding strings for URLs, see [the UrlEncode() method reference](xref:System.Net.WebUtility.UrlEncode*). When the input is a POST request and the body is a **String**, the value to the left of the first equals sign (`=`) is set as a key in the form data and the remaining text is set as the value. To specify multiple keys, use an **IDictionary** object, such as a hash table, for the **Body**. When the input is a GET request and the body is an **IDictionary** (typically, a hash table), the body is added to the URI as query parameters. For other request types (such as PATCH), the body is set as the value of the request body in the standard `name=value` format with the values URL-encoded. When the input is a **System.Xml.XmlNode** object and the XML declaration specifies an encoding, that encoding is used for the data in the request unless overridden by the **ContentType** parameter. The **Body** parameter also accepts a `System.Net.Http.MultipartFormDataContent` object. This facilitates `multipart/form-data` requests. When a **MultipartFormDataContent** object is supplied for **Body**, any Content related headers supplied to the **ContentType**, **Headers**, or **WebSession** parameters is overridden by the Content headers of the **MultipartFormDataContent** object. This feature was added in PowerShell 6.0.0. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Certificate Specifies the client certificate that's used for a secure web request. Enter a variable that contains a certificate or a command or expression that gets the certificate. To find a certificate, use `Get-PfxCertificate` or use the `Get-ChildItem` cmdlet in the Certificate (`Cert:`) drive. If the certificate isn't valid or doesn't have sufficient authority, the command fails. ```yaml Type: System.Security.Cryptography.X509Certificates.X509Certificate Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to send the request. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. Certificates can only be mapped only to local user accounts, not domain accounts. To see the certificate thumbprint, use the `Get-Item` or `Get-ChildItem` command to find the certificate in `Cert:\CurrentUser\My`. > [!NOTE] > This feature is only supported on Windows OS platforms. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ConnectionTimeoutSeconds Specifies how long the request can be pending before it times out. Enter a value in seconds. The default value, 0, specifies an indefinite time-out. A Domain Name System (DNS) query can take up to 15 seconds to return or time out. If your request contains a host name that requires resolution, and you set **ConnectionTimeoutSeconds** to a value greater than zero, but less than 15 seconds, it can take 15 seconds or more before a **WebException** is thrown, and your request times out. This parameter replaced the **TimeoutSec** parameter in PowerShell 7.4. You can use **TimeoutSec** as an alias for **ConnectionTimeoutSeconds**. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: TimeoutSec Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ContentType Specifies the content type of the web request. If the value for **ContentType** contains the encoding format (as `charset`), the cmdlet uses that format to encode the body of the web request. If the **ContentType** doesn't specify an encoding format, the default encoding format is used instead. An example of a **ContentType** with an encoding format is `text/plain; charset=iso-8859-5`, which specifies the [Latin/Cyrillic](https://www.iso.org/standard/28249.html) alphabet. If you omit the parameter, the content type may be different based on the HTTP method you use: - For a POST method, the content type is `application/x-www-form-urlencoded` - For a PUT method, the content type is `application/json` - For other methods, the content type isn't specified in the request If you are using the **InFile** parameter to upload a file, you should set the content type. Usually, the type should be `application/octet-stream`. However, you need to set the content type based on the requirements of the endpoint. **ContentType** is overridden when the **Body** is a [MultipartFormDataContent](xref:System.Net.Http.MultipartFormDataContent) object. Starting in PowerShell 7.4, if you use this both this parameter and the **Headers** parameter to define the `Content-Type` header, the value specified in the **ContentType** parameter is used. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to send the request. The default is the current user. Type a user name, such as **User01** or **Domain01\User01**, or enter a **PSCredential** object generated by the `Get-Credential` cmdlet. **Credential** can be used alone or in conjunction with certain **Authentication** parameter options. When used alone, it only supplies credentials to the remote server if the remote server sends an authentication challenge request. When used with **Authentication** options, the credentials are explicitly sent. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: False Accept wildcard characters: False ``` ### -CustomMethod Specifies a custom method used for the web request. This can be used if the Request Method required by the endpoint isn't an available option on the **Method**. **Method** and **CustomMethod** can't be used together. This example makes a `TEST` HTTP request to the API: `Invoke-WebRequest -Uri 'https://api.contoso.com/widget/' -CustomMethod 'TEST'` This feature was added in PowerShell 6.0.0. ```yaml Type: System.String Parameter Sets: CustomMethod, CustomMethodNoProxy Aliases: CM Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DisableKeepAlive Indicates that the cmdlet sets the **KeepAlive** value in the HTTP header to **False**. By default, **KeepAlive** is **True**. **KeepAlive** establishes a persistent connection to the server to facilitate subsequent requests. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Form Converts a dictionary to a `multipart/form-data` submission. **Form** may not be used with **Body**. If **ContentType** is used, it's ignored. The keys of the dictionary are used as the form field names. By default, form values are converted to string values. If the value is a **System.IO.FileInfo** object, then the binary file contents are submitted. The name of the file is submitted as the **filename** property. The MIME type is set as `application/octet-stream`. `Get-Item` can be used to simplify supplying the **System.IO.FileInfo** object. ```powershell $Form = @{ resume = Get-Item 'C:\Users\jdoe\Documents\John Doe.pdf' } ``` If the value is a collection type, such Arrays or Lists, the for field are submitted multiple times. The values of the list are treated as strings by default. If the value is a **System.IO.FileInfo** object, then the binary file contents are submitted. Nested collections aren't supported. ```powershell $Form = @{ tags = 'Vacation', 'Italy', '2017' pictures = Get-ChildItem 'C:\Users\jdoe\Pictures\2017-Italy\' } ``` In the above example the `tags` field are supplied three times in the form, once for each of `Vacation`, `Italy`, and `2017`. The `pictures` field is also submitted once for each file in the `2017-Italy` folder. The binary contents of the files in that folder are submitted as the values. This feature was added in PowerShell 6.1.0. ```yaml Type: System.Collections.IDictionary Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Headers Specifies the headers of the web request. Enter a hash table or dictionary. Content related headers, such as `Content-Type` are overridden when a **MultipartFormDataContent** object is supplied for **Body**. Starting in PowerShell 7.4, if you use this parameter to define the `Content-Type` header and use **ContentType** parameter, the value specified in the **ContentType** parameter is used. ```yaml Type: System.Collections.IDictionary Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -HttpVersion Specifies the HTTP version used for the request. The default is `1.1`. Valid values are: - 1.0 - 1.1 - 2.0 - 3.0 ```yaml Type: System.Version Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 1.1 Accept pipeline input: False Accept wildcard characters: False ``` ### -InFile Gets the content of the web request body from a file. Enter a path and filename. If you omit the path, the default is the current location. You also need to set the content type of the request. For example, to upload a file you should set the content type. Usually, the type should be `application/octet-stream`. However, you need to set the content type based on the requirements of the endpoint. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumRedirection Specifies how many times PowerShell redirects a connection to an alternate Uniform Resource Identifier (URI) before the connection fails. The default value is 5. A value of 0 (zero) prevents all redirection. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 5 Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumRetryCount Specifies how many times PowerShell retries a connection when a failure code between 400 and 599, inclusive or 304 is received. Also see **RetryIntervalSec** parameter for specifying the interval between retries. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Method Specifies the method used for the web request. The acceptable values for this parameter are: - `Default` - `Delete` - `Get` - `Head` - `Merge` - `Options` - `Patch` - `Post` - `Put` - `Trace` The **CustomMethod** parameter can be used for Request Methods not listed above. ```yaml Type: Microsoft.PowerShell.Commands.WebRequestMethod Parameter Sets: StandardMethod, StandardMethodNoProxy Aliases: Accepted values: Default, Get, Head, Post, Put, Delete, Trace, Options, Merge, Patch Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NoProxy Indicates that the cmdlet shouldn't use a proxy to reach the destination. When you need to bypass the proxy configured in the environment, use this switch. This feature was added in PowerShell 6.0.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: StandardMethodNoProxy, CustomMethodNoProxy Aliases: Required: True Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -OperationTimeoutSeconds This timeout applies to data reads within a stream, not to the stream time as a whole. The default value, 0, specifies an indefinite timeout. Setting the value to 30 seconds means that any delay of longer than 30 seconds between data in the stream terminates the request. A large file that takes several minutes to download won't terminate unless the stream stalls for more than 30 seconds. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OutFile By default, `Invoke-WebRequest` returns the results to the pipeline. When you use the **OutFile** parameter, the results are saved to the specified file and not returned to the pipeline. Enter a path and filename. To send the results to a file and to the pipeline, add the **PassThru** parameter. If you omit the path, the default is the current location. The name is treated as a literal path. Names that contain brackets (`[]`) must be enclosed in single quotes (`'`). Starting in PowerShell 7.4, you can specify a folder path without the filename. When you do, the command uses the filename from the last segment of the resolved URI after any redirections. When you specify a folder path for **OutFile**, you can't use the **Resume** parameter. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Indicates that the cmdlet returns the results, in addition to writing them to a file. This parameter is valid only when the **OutFile** parameter is also used in the command. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -PreserveAuthorizationOnRedirect Indicates the cmdlet should preserve the `Authorization` header, when present, across redirections. By default, the cmdlet strips the `Authorization` header before redirecting. Specifying this parameter disables this logic for cases where the header needs to be sent to the redirection location. This feature was added in PowerShell 6.0.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -PreserveHttpMethodOnRedirect Indicates the cmdlet should preserve the method of the request across redirections. By default, the cmdlet changes the method to `GET` when redirected. Specifying this parameter disables this logic to ensure that the intended method can be used with redirection. This feature was added in PowerShell 7.4. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Proxy Specifies a proxy server for the request, rather than connecting directly to the internet resource. Enter the URI of a network proxy server. ```yaml Type: System.Uri Parameter Sets: StandardMethod, CustomMethod Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProxyCredential Specifies a user account that has permission to use the proxy server specified by the **Proxy** parameter. The default is the current user. Type a user name, such as `User01` or `Domain01\User01`, or enter a **PSCredential** object, such as one generated by the `Get-Credential` cmdlet. This parameter is valid only when the **Proxy** parameter is also used in the command. You can't use the **ProxyCredential** and **ProxyUseDefaultCredentials** parameters in the same command. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: StandardMethod, CustomMethod Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: False Accept wildcard characters: False ``` ### -ProxyUseDefaultCredentials Indicates that the cmdlet uses the credentials of the current user to access the proxy server that is specified by the **Proxy** parameter. This parameter is valid only when the **Proxy** parameter is also used in the command. You can't use the **ProxyCredential** and **ProxyUseDefaultCredentials** parameters in the same command. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: StandardMethod, CustomMethod Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Resume Performs a best effort attempt to resume downloading a partial file. **Resume** requires **OutFile**. **Resume** only operates on the size of the local file and remote file and performs no other validation that the local file and the remote file are the same. If the local file size is smaller than the remote file size, then the cmdlet attempts to resume downloading the file and append the remaining bytes to the end of the file. If the local file size is the same as the remote file size, then no action is taken and the cmdlet assumes the download already complete. If the local file size is larger than the remote file size, then the local file is overwritten and the entire remote file is re-downloaded. This behavior is the same as using **OutFile** without **Resume**. If the remote server doesn't support download resuming, then the local file is overwritten and the entire remote file is re-downloaded. This behavior is the same as using **OutFile** without **Resume**. If the local file doesn't exist, then the local file is created and the entire remote file is downloaded. This behavior is the same as using **OutFile** without **Resume**. This feature was added in PowerShell 6.1.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -RetryIntervalSec Specifies the interval between retries for the connection when a failure code between 400 and 599, inclusive or 304 is received. Also see **MaximumRetryCount** parameter for specifying number of retries. The value must be between `1` and `[int]::MaxValue`. When the failure code is 429 and the response includes the **Retry-After** property in its headers, the cmdlet uses that value for the retry interval, even if this parameter is specified. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 5 Accept pipeline input: False Accept wildcard characters: False ``` ### -SessionVariable Specifies a variable for which this cmdlet creates a web request session and saves it in the value. Enter a variable name without the dollar sign (`$`) symbol. When you specify a session variable, `Invoke-WebRequest` creates a web request session object and assigns it to a variable with the specified name in your PowerShell session. You can use the variable in your session as soon as the command completes. Before PowerShell 7.4, the web request session isn't a persistent connection. It's an object that contains information about the connection and the request, including cookies, credentials, the maximum redirection value, and the user agent string. You can use it to share state and data among web requests. Starting in PowerShell 7.4, the web request session is persistent as long as the properties of the session aren't overridden in a subsequent request. When they are, the cmdlet recreates the session with the new values. The persistent sessions reduce the overhead for repeated requests, making them much faster. To use the web request session in subsequent web requests, specify the session variable in the value of the **WebSession** parameter. PowerShell uses the data in the web request session object when establishing the new connection. To override a value in the web request session, use a cmdlet parameter, such as **UserAgent** or **Credential**. Parameter values take precedence over values in the web request session. You can't use the **SessionVariable** and **WebSession** parameters in the same command. ```yaml Type: System.String Parameter Sets: (All) Aliases: SV Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipCertificateCheck Skips certificate validation checks. This includes all validations such as expiration, revocation, trusted root authority, etc. > [!WARNING] > Using this parameter isn't secure and isn't recommended. This switch is only intended to be used > against known hosts using a self-signed certificate for testing purposes. Use at your own risk. This feature was added in PowerShell 6.0.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipHeaderValidation Indicates the cmdlet should add headers to the request without validation. This switch should be used for sites that require header values that don't conform to standards. Specifying this switch disables validation to allow the value to be passed unchecked. When specified, all headers are added without validation. This switch disables validation for values passed to the **ContentType**, **Headers** and **UserAgent** parameters. This feature was added in PowerShell 6.0.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipHttpErrorCheck This parameter causes the cmdlet to ignore HTTP error statuses and continue to process responses. The error responses are written to the pipeline just as if they were successful. This parameter was introduced in PowerShell 7. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -SslProtocol Sets the SSL/TLS protocols that are permissible for the web request. By default all, SSL/TLS protocols supported by the system are allowed. **SslProtocol** allows for limiting to specific protocols for compliance purposes. These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **SslProtocol** parameter as an array of values or as a comma-separated string of those values. The cmdlet combines the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. You may not be able to define multiple options on all platforms. > [!NOTE] > On non-Windows platforms it may not be possible to supply `Tls` or `Tls12` as an option. Support > for `Tls13` isn't available on all operating systems and will need to be verified on a per > operating system basis. This feature was added in PowerShell 6.0.0 and support for `Tls13` was added in PowerShell 7.1. ```yaml Type: Microsoft.PowerShell.Commands.WebSslProtocol Parameter Sets: (All) Aliases: Accepted values: Default, Tls, Tls11, Tls12 Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Token The OAuth or Bearer token to include in the request. **Token** is required by certain **Authentication** options. It can't be used independently. **Token** takes a `SecureString` containing the token. To supply the token manually use the following: `Invoke-WebRequest -Uri $uri -Authentication OAuth -Token (Read-Host -AsSecureString)` This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Security.SecureString Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TransferEncoding Specifies a value for the transfer-encoding HTTP response header. The acceptable values for this parameter are: - `Chunked` - `Compress` - `Deflate` - `GZip` - `Identity` ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: chunked, compress, deflate, gzip, identity Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UnixSocket Specifies the name of the Unix socket to connect to. This parameter is supported on Unix-based systems and Windows version 1803 and later. For more information about Windows support of Unix sockets, see the [Windows/WSL Interop with AF_UNIX](https://devblogs.microsoft.com/commandline/windowswsl-interop-with-af_unix/) blog post. This parameter was added in PowerShell 7.4. ```yaml Type: System.Net.Sockets.UnixDomainSocketEndPoint Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Uri Specifies the Uniform Resource Identifier (URI) of the internet resource to which the web request is sent. Enter a URI. This parameter supports HTTP or HTTPS only. This parameter is required. The parameter name **Uri** is optional. ```yaml Type: System.Uri Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseBasicParsing This parameter has been deprecated. Beginning with PowerShell 6.0.0, all Web requests use basic parsing only. This parameter is included for backwards compatibility only and any use of it has no effect on the operation of the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -UseDefaultCredentials Indicates that the cmdlet uses the credentials of the current user to send the web request. This can't be used with **Authentication** or **Credential** and may not be supported on all platforms. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -UserAgent Specifies a user agent string for the web request. The default user agent is similar to `Mozilla/5.0 (Windows NT 10.0; Microsoft Windows 10.0.15063; en-US) PowerShell/6.0.0` with slight variations for each operating system and platform. To test a website with the standard user agent string that's used by most internet browsers, use the properties of the [PSUserAgent](/dotnet/api/microsoft.powershell.commands.psuseragent) class, such as Chrome, Firefox, InternetExplorer, Opera, and Safari. For example, the following command uses the user agent string for Internet Explorer: `Invoke-WebRequest -Uri https://website.com/ -UserAgent ([Microsoft.PowerShell.Commands.PSUserAgent]::InternetExplorer)` ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WebSession Specifies a web request session. Enter the variable name, including the dollar sign (`$`). To override a value in the web request session, use a cmdlet parameter, such as **UserAgent** or **Credential**. Parameter values take precedence over values in the web request session. Content related headers, such as `Content-Type`, are also be overridden when a **MultipartFormDataContent** object is supplied for **Body**. Unlike a remote session, the web request session isn't a persistent connection. It's an object that contains information about the connection and the request, including cookies, credentials, the maximum redirection value, and the user agent string. You can use it to share state and data among web requests. To create a web request session, enter a variable name, without a dollar sign, in the value of the **SessionVariable** parameter of an `Invoke-WebRequest` command. `Invoke-WebRequest` creates the session and saves it in the variable. In subsequent commands, use the variable as the value of the **WebSession** parameter. You can't use the **SessionVariable** and **WebSession** parameters in the same command. ```yaml Type: Microsoft.PowerShell.Commands.WebRequestSession Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Object You can pipe the body of a web request to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject This cmdlet returns the response object representing the result of the web request. ## NOTES PowerShell includes the following aliases for `Invoke-WebRequest`: - All platforms: - `iwr` Beginning with PowerShell 6.0.0 `Invoke-WebRequest` supports basic parsing only. For more information, see [BasicHtmlWebResponseObject](xref:Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject). Because of changes in .NET Core 3.1, PowerShell 7.0 and higher use the [HttpClient.DefaultProxy](xref:System.Net.Http.HttpClient.DefaultProxy*) property to determine the proxy configuration. The value of this property is determined by your platform: - **For Windows**: Reads proxy configuration from environment variables. If those variables aren't defined the property is derived from the user's proxy settings. - **For macOS**: Reads proxy configuration from environment variables. If those variables aren't defined the property is derived from the system's proxy settings. - **For Linux**: Reads proxy configuration from environment variables. If those variables aren't defined the property initializes a non-configured instance that bypasses all addresses. The environment variables used for `DefaultProxy` initialization on Windows and Unix-based platforms are: - `HTTP_PROXY`: the hostname or IP address of the proxy server used on HTTP requests. - `HTTPS_PROXY`: the hostname or IP address of the proxy server used on HTTPS requests. - `ALL_PROXY`: the hostname or IP address of the proxy server used on HTTP and HTTPS requests in case `HTTP_PROXY` or `HTTPS_PROXY` aren't defined. - `NO_PROXY`: a comma-separated list of hostnames that should be excluded from proxying. PowerShell 7.4 added support for the Brotli compression algorithm. ## RELATED LINKS [Invoke-RestMethod](Invoke-RestMethod.md) [ConvertFrom-Json](ConvertFrom-Json.md) [ConvertTo-Json](ConvertTo-Json.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Join-String.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/19/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/join-string?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Join-String --- # Join-String ## SYNOPSIS Combines objects from the pipeline into a single string. ## SYNTAX ### Default (Default) ``` Join-String [[-Property] <PSPropertyExpression>] [[-Separator] <String>] [-OutputPrefix <String>] [-OutputSuffix <String>] [-UseCulture] [-InputObject <PSObject[]>] [<CommonParameters>] ``` ### SingleQuote ``` Join-String [[-Property] <PSPropertyExpression>] [[-Separator] <String>] [-OutputPrefix <String>] [-OutputSuffix <String>] [-SingleQuote] [-UseCulture] [-InputObject <PSObject[]>] [<CommonParameters>] ``` ### DoubleQuote ``` Join-String [[-Property] <PSPropertyExpression>] [[-Separator] <String>] [-OutputPrefix <String>] [-OutputSuffix <String>] [-DoubleQuote] [-UseCulture] [-InputObject <PSObject[]>] [<CommonParameters>] ``` ### Format ``` Join-String [[-Property] <PSPropertyExpression>] [[-Separator] <String>] [-OutputPrefix <String>] [-OutputSuffix <String>] [-FormatString <String>] [-UseCulture] [-InputObject <PSObject[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Join-String` cmdlet joins, or combines, text from pipeline objects into a single string. If no parameters are specified, the pipeline objects are converted to a string and joined with the default separator `$OFS`. > [!NOTE] > When you set `$OFS` its value is used to join arrays when they're converted to strings until the > variable is reset to `$null`. Because using `$OFS` can have unintended effects elsewhere in your > code, it's best to use the **Separator** parameter instead. By specifying a property name, the property's value is converted to a string and joined into a string. Instead of a property name, a script block can be used. The script block's result is converted to a string before it's joined to form the result. It can either combine the text of an object's property or the result of the object that was converted to a string. This cmdlet was introduced in PowerShell 6.2. ## EXAMPLES ### Example 1: Join directory names <!-- markdownlint-disable MD038 --> This example joins directory names, wraps the output in double-quotes, and separates the directory names with a comma and space (`, `). The output is a string object. ```powershell Get-ChildItem -Directory C:\ | Join-String -Property Name -DoubleQuote -Separator ', ' ``` ```Output "PerfLogs", "Program Files", "Program Files (x86)", "Users", "Windows" ``` `Get-ChildItem` uses the **Directory** parameter to get all the directory names for the `C:\` drive. The objects are sent down the pipeline to `Join-String`. The **Property** parameter specifies the directory names. The **DoubleQuote** parameter wraps the directory names with double-quote marks. The **Separator** parameter specifies to use a comma and space (`, `) to separate the directory names. The `Get-ChildItem` objects are **System.IO.DirectoryInfo** and `Join-String` converts the objects to **System.String**. ### Example 2: Use a property substring to join directory names This example uses a substring method to get the first four letters of directory names, wraps the output in single-quotes, and separates the directory names with a semicolon (`;`). ```powershell Get-ChildItem -Directory C:\ | Join-String -Property {$_.Name.SubString(0,4)} -SingleQuote -Separator ';' ``` ```Output 'Perf';'Prog';'Prog';'User';'Wind' ``` `Get-ChildItem` uses the **Directory** parameter to get all the directory names for the `C:\` drive. The objects are sent down the pipeline to `Join-String`. The **Property** parameter script block uses automatic variable (`$_`) to specify each object's **Name** property substring. The substring gets the first four letters of each directory name. The substring specifies the character start and end positions. The **SingleQuote** parameter wraps the directory names with single-quote marks. The **Separator** parameter specifies to use a semicolon (`;`) to separate the directory names. For more information about automatic variables and substrings, see [about_Automatic_Variables](../microsoft.powershell.core/about/about_automatic_variables.md) and [Substring](/dotnet/api/system.string.substring). ### Example 3: Display join output on a separate line This example joins service names with each service on a separate line and indented by a tab. ```powershell Get-Service -Name se* | Join-String -Property Name -Separator "`r`n`t" -OutputPrefix "Services:`n`t" ``` ```Output Services: seclogon SecurityHealthService SEMgrSvc SENS Sense SensorDataService SensorService SensrSvc SessionEnv ``` `Get-Service` uses the **Name** parameter with to specify services that begin with `se*`. The asterisk (`*`) is a wildcard for any character. The objects are sent down the pipeline to `Join-String` that uses the **Property** parameter to specify the service names. The **Separator** parameter specifies three special characters that represent a carriage return (`` `r ``), newline (`` `n ``), and tab (`` `t ``). The **OutputPrefix** inserts a label `Services:` with a new line and tab before the first line of output. For more information about special characters, see [about_Special_Characters](../microsoft.powershell.core/about/about_special_characters.md). ### Example 4: Create a class definition from an object This example generates a PowerShell class definition using an existing object as a template. This code sample uses splatting to reduce the line length and improve readability. For more information, see [about_Splatting](../Microsoft.PowerShell.Core/About/about_Splatting.md). ```powershell $obj = [pscustomobject] @{Name = "Joe"; Age = 42} $parms = @{ Property = "Name" FormatString = ' ${0}' OutputPrefix = "class {`n" OutputSuffix = "`n}`n" Separator = "`n" } $obj.psobject.Properties | Join-String @parms ``` ```Output class { $Name $Age } ``` ## PARAMETERS ### -DoubleQuote Wraps the string value of each pipeline object in double-quotes. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: DoubleQuote Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -FormatString Specifies a format string that specifies how each pipeline object should be formatted before joining them. Use the `{0}` placeholder to represent the current object. If you need to keep the curly braces (`{}`) in the formatted string, you can escape them by doubling the curly braces (`{{` and `}}`). For more information, see the [String.Format](/dotnet/api/system.string.format) method and [Composite Formatting](/dotnet/standard/base-types/composite-formatting). ```yaml Type: System.String Parameter Sets: Format Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the text to be joined. Enter a variable that contains the text, or type a command or expression that gets the objects to join into strings. ```yaml Type: System.Management.Automation.PSObject[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -OutputPrefix Text that's inserted before the output string. The string can contain special characters such as carriage return (`` `r ``), newline (`` `n ``), and tab (`` `t ``). ```yaml Type: System.String Parameter Sets: (All) Aliases: op Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OutputSuffix Text that's appended to the output string. The string can contain special characters such as carriage return (`` `r ``), newline (`` `n ``), and tab (`` `t ``). ```yaml Type: System.String Parameter Sets: (All) Aliases: os Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Property The name of a property, or a property expression, to be converted to text. ```yaml Type: Microsoft.PowerShell.Commands.PSPropertyExpression Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Separator Text or characters such as a comma or semicolon that's inserted between the text for each pipeline object. By default, the pipeline objects are joined without a separator. If the [Output Field Separator](../microsoft.powershell.core/about/about_preference_variables.md#ofs) preference variable (`$OFS`) is set, that value is used unless this parameter is specified. > [!NOTE] > When you set `$OFS` its value is used to join arrays when they're converted to strings until the > variable is reset to `$null`. Because using `$OFS` can have unintended effects elsewhere in your > code, it's best to use the **Separator** parameter instead. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SingleQuote Wraps the string value of each pipeline object in single quotes. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: SingleQuote Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -UseCulture Uses the list separator for the current culture as the item delimiter. To find the list separator for a culture, use the following command: `(Get-Culture).TextInfo.ListSeparator`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject ## OUTPUTS ### System.String ## NOTES ## RELATED LINKS [about_Automatic_Variables](../microsoft.powershell.core/about/about_automatic_variables.md) [about_Special_Characters](../microsoft.powershell.core/about/about_special_characters.md) [Substring](/dotnet/api/system.string.substring)

#File: reference/7.6/Microsoft.PowerShell.Utility/Measure-Command.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/measure-command?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Measure-Command --- # Measure-Command ## SYNOPSIS Measures the time it takes to run script blocks and cmdlets. ## SYNTAX ``` Measure-Command [-InputObject <PSObject>] [-Expression] <ScriptBlock> [<CommonParameters>] ``` ## DESCRIPTION The `Measure-Command` cmdlet runs a script block or cmdlet internally, times the execution of the operation, and returns the execution time. > [!NOTE] > Script blocks run by `Measure-Command` run in the current scope, not a child scope. ## EXAMPLES ### Example 1: Measure a command This example measures the time it takes to run a `Get-EventLog` command that gets the events in the Windows PowerShell event log. ```powershell Measure-Command { Get-EventLog "Windows PowerShell" } ``` ### Example 2: Compare two outputs from Measure-Command The first command measures the time it takes to process a recursive `Get-ChildItem` command that uses the **Path** parameter to get only `.txt` files in the `C:\Windows` directory and its subdirectories. The second command measures the time it takes to process a recursive `Get-ChildItem` command that uses the provider-specific **Filter** parameter. These commands show the value of using a provider-specific filter in PowerShell commands. ```powershell Measure-Command { Get-ChildItem -Path C:\Windows\*.txt -Recurse } ``` ```Output Days : 0 Hours : 0 Minutes : 0 Seconds : 8 Milliseconds : 618 Ticks : 86182763 TotalDays : 9.9748568287037E-05 TotalHours : 0.00239396563888889 TotalMinutes : 0.143637938333333 TotalSeconds : 8.6182763 TotalMilliseconds : 8618.2763 ``` ```powershell Measure-Command {Get-ChildItem C:\Windows -Filter "*.txt" -Recurse} ``` ```Output Days : 0 Hours : 0 Minutes : 0 Seconds : 1 Milliseconds : 140 Ticks : 11409189 TotalDays : 1.32050798611111E-05 TotalHours : 0.000316921916666667 TotalMinutes : 0.019015315 TotalSeconds : 1.1409189 TotalMilliseconds : 1140.9189 ``` ### Example 3: Piping input to Measure-Command Objects that are piped to `Measure-Command` are available to the script block that is passed to the **Expression** parameter. The script block is executed once for each object on the pipeline. ```powershell # Perform a simple operation to demonstrate the InputObject parameter # Note that no output is displayed. 10, 20, 50 | Measure-Command -Expression { for ($i=0; $i -lt $_; $i++) {$i} } ``` ```Output Days : 0 Hours : 0 Minutes : 0 Seconds : 0 Milliseconds : 12 Ticks : 122672 TotalDays : 1.41981481481481E-07 TotalHours : 3.40755555555556E-06 TotalMinutes : 0.000204453333333333 TotalSeconds : 0.0122672 TotalMilliseconds : 12.2672 ``` ### Example 4: Displaying output of measured command To display output of expression in `Measure-Command` you can use a pipe to `Out-Default`. ```powershell # Perform the same operation as above adding Out-Default to every execution. # This will show that the ScriptBlock is in fact executing for every item. 10, 20, 50 | Measure-Command -Expression {for ($i=0; $i -lt $_; $i++) {$i}; "$($_)" | Out-Default } ``` ```Output 10 20 50 Days : 0 Hours : 0 Minutes : 0 Seconds : 0 Milliseconds : 11 Ticks : 113745 TotalDays : 1.31649305555556E-07 TotalHours : 3.15958333333333E-06 TotalMinutes : 0.000189575 TotalSeconds : 0.0113745 TotalMilliseconds : 11.3745 ``` ### Example 5: Measuring execution in a child scope `Measure-Command` runs the script block in the current scope, so the script block can modify values in the current scope. To avoid changes to the current scope, you must wrap the script block in braces (`{}`) and use the invocation operator (`&`) to execute the block in a child scope. ```powershell $foo = 'Value 1' $null = Measure-Command { $foo = 'Value 2' } $foo $null = Measure-Command { & { $foo = 'Value 3' } } $foo ``` ```Output Value 2 Value 2 ``` For more information about the invocation operator, see [about_Operators](../Microsoft.PowerShell.Core/About/about_Operators.md#call-operator-). ## PARAMETERS ### -Expression Specifies the expression that is being timed. Enclose the expression in braces (`{}`). ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Objects bound to the **InputObject** parameter are optional input for the script block passed to the **Expression** parameter. Inside the script block, `$_` can be used to reference the current object in the pipeline. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe an object to this cmdlet. ## OUTPUTS ### System.TimeSpan This cmdlet returns a time span object representing the result. ## NOTES ## RELATED LINKS [Invoke-Command](../Microsoft.PowerShell.Core/Invoke-Command.md) [Trace-Command](Trace-Command.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Measure-Object.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/measure-object?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Measure-Object --- # Measure-Object ## SYNOPSIS Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files of text. ## SYNTAX ### GenericMeasure (Default) ``` Measure-Object [[-Property] <PSPropertyExpression[]>] [-InputObject <PSObject>] [-StandardDeviation] [-Sum] [-AllStats] [-Average] [-Maximum] [-Minimum] [<CommonParameters>] ``` ### TextMeasure ``` Measure-Object [[-Property] <PSPropertyExpression[]>] [-InputObject <PSObject>] [-Line] [-Word] [-Character] [-IgnoreWhiteSpace] [<CommonParameters>] ``` ## DESCRIPTION The `Measure-Object` cmdlet calculates the property values of certain types of object. `Measure-Object` performs three types of measurements, depending on the parameters in the command. The `Measure-Object` cmdlet performs calculations on the property values of objects. You can use `Measure-Object` to count objects or count objects with a specified **Property**. You can also use `Measure-Object` to calculate the **Minimum**, **Maximum**, **Sum**, **StandardDeviation** and **Average** of numeric values. For **String** objects, you can also use `Measure-Object` to count the number of lines, words, and characters. ## EXAMPLES ### Example 1: Count the files and folders in a directory This command counts the files and folders in the current directory. ```powershell Get-ChildItem | Measure-Object ``` ### Example 2: Measure the files in a directory This command displays the **Minimum**, **Maximum**, and **Sum** of the sizes of all files in the current directory, and the average size of a file in the directory. ```powershell Get-ChildItem | Measure-Object -Property Length -Minimum -Maximum -Sum -Average ``` ### Example 3: Measure text in a text file This command displays the number of characters, words, and lines in the Text.txt file. Without the **Raw** parameter, `Get-Content` outputs the file as an array of lines. The first command uses `Set-Content` to add some default text to a file. ```powershell "One", "Two", "Three", "Four" | Set-Content -Path C:\Temp\tmp.txt Get-Content C:\Temp\tmp.txt | Measure-Object -Character -Line -Word ``` ```Output Lines Words Characters Property ----- ----- ---------- -------- 4 4 15 ``` ### Example 4: Measure objects containing a specified Property This example counts the number of objects that have a **DisplayName** property. The first two commands retrieve all the services and processes on the local machine. The third command counts the combined number of services and processes. The last command combines the two collections and pipes the result to `Measure-Object`. The **System.Diagnostics.Process** object does not have a **DisplayName** property, and is left out of the final count. ```powershell $services = Get-Service $processes = Get-Process $services + $processes | Measure-Object $services + $processes | Measure-Object -Property DisplayName ``` ```Output Count : 682 Average : Sum : Maximum : Minimum : Property : Count : 290 Average : Sum : Maximum : Minimum : Property : DisplayName ``` ### Example 5: Measure the contents of a CSV file This command calculates the average years of service of the employees of a company. The `ServiceYrs.csv` file is a CSV file that contains the employee number and years of service of each employee. The first row in the table is a header row of **EmpNo**, **Years**. When you use `Import-Csv` to import the file, the result is a **PSCustomObject** with note properties of **EmpNo** and **Years**. You can use `Measure-Object` to calculate the values of these properties, just like any other property of an object. ```powershell Import-Csv D:\test\serviceyrs.csv | Measure-Object -Property Years -Minimum -Maximum -Average ``` ### Example 6: Measure Boolean values This example demonstrates how the `Measure-Object` can measure Boolean values. In this case, it uses the **PSIsContainer** **Boolean** property to measure the incidence of folders (vs. files) in the current directory. ```powershell Get-ChildItem | Measure-Object -Property PSIsContainer -Maximum -Sum -Minimum -Average ``` ```Output Count : 126 Average : 0.0634920634920635 Sum : 8 Maximum : 1 Minimum : 0 StandardDeviation : Property : PSIsContainer ``` ### Example 7: Measure strings The following example measures the number of lines, first a single string, then across several strings. The newline character <code>`n</code> separates strings into multiple lines. ```powershell # The newline character `n separates the string into separate lines, as shown in the output. "One`nTwo`nThree" "One`nTwo`nThree" | Measure-Object -Line ``` ```Output One Two Three Lines Words Characters Property ----- ----- ---------- -------- 3 ``` ```powershell # The first string counts as a single line. # The second string is separated into two lines by the newline character. "One", "Two`nThree" | Measure-Object -Line ``` ```Output Lines Words Characters Property ----- ----- ---------- -------- 3 ``` ```powershell # The Word switch counts the number of words in each InputObject # Each InputObject is treated as a single line. "One, Two", "Three", "Four Five" | Measure-Object -Word -Line ``` ```Output Lines Words Characters Property ----- ----- ---------- -------- 3 5 ``` ### Example 8: Measure all the values Beginning in PowerShell 6, the **AllStats** parameter of `Measure-Object` allows you to measure all the statistics together. ```powershell 1..5 | Measure-Object -AllStats ``` ```output Count : 5 Average : 3 Sum : 15 Maximum : 5 Minimum : 1 StandardDeviation : 1.58113883008419 Property : ``` ### Example 9: Measure using scriptblock properties Beginning in PowerShell 6, `Measure-Object` supports **ScriptBlock** properties. The following example demonstrates how to use a **ScriptBlock** property to determine the size, in MegaBytes, of all the files in a directory. ```powershell Get-ChildItem | Measure-Object -Sum {$_.Length/1MB} ``` ### Example 10: Measure hashtables Beginning in PowerShell 6, `Measure-Object` supports measurement of **hashtable** input. The following example determines the largest value for the `num` key of 3 **hashtable** objects. ```powershell @{num=3}, @{num=4}, @{num=5} | Measure-Object -Maximum Num ``` ```output Count : 3 Average : Sum : Maximum : 5 Minimum : StandardDeviation : Property : num ``` ### Example 11: Measure the Standard Deviation Beginning in PowerShell 6, `Measure-Object` supports the **StandardDeviation** parameter. The following example determines the _standard deviation_ for the CPU used by all processes. A large deviation would indicate a small number of processes consuming the most CPU. ```powershell Get-Process | Measure-Object -Average -StandardDeviation CPU ``` ```output Count : 303 Average : 163.032384488449 Sum : Maximum : Minimum : StandardDeviation : 859.444048419069 Property : CPU ``` ### Example 12: Measure using wildcards Beginning in PowerShell 6, `Measure-Object` supports measurement of objects by using wildcards in property names. The following example determines the maximum of any type of paged memory usage among a set of processes. ```powershell Get-Process | Measure-Object -Maximum *paged*memory*size ``` ```output Count : 303 Average : Sum : Maximum : 735784 Minimum : StandardDeviation : Property : NonpagedSystemMemorySize Count : 303 Average : Sum : Maximum : 352104448 Minimum : StandardDeviation : Property : PagedMemorySize Count : 303 Average : Sum : Maximum : 2201968 Minimum : StandardDeviation : Property : PagedSystemMemorySize Count : 303 Average : Sum : Maximum : 719032320 Minimum : StandardDeviation : Property : PeakPagedMemorySize ``` ## PARAMETERS ### -AllStats Indicates that the cmdlet displays all the statistics of the specified properties. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: GenericMeasure Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Average Indicates that the cmdlet displays the average value of the specified properties. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: GenericMeasure Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Character Indicates that the cmdlet counts the number of characters in the input objects. > [!NOTE] > The **Word**, **Char** and **Line** switches count _inside_ each input object, as well as _across_ > input objects. See Example 7. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: TextMeasure Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -IgnoreWhiteSpace Indicates that the cmdlet ignores white space in character counts. By default, white space is not ignored. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: TextMeasure Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects to be measured. Enter a variable that contains the objects, or type a command or expression that gets the objects. When you use the **InputObject** parameter with `Measure-Object`, instead of piping command results to `Measure-Object`, the **InputObject** value is treated as a single object. It is recommended that you use `Measure-Object` in the pipeline if you want to measure a collection of objects based on whether the objects have specific values in defined properties. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Line Indicates that the cmdlet counts the number of lines in the input objects. > [!NOTE] > The **Word**, **Char** and **Line** switches count _inside_ each input object, as well as _across_ > input objects. See Example 7. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: TextMeasure Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Maximum Indicates that the cmdlet displays the maximum value of the specified properties. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: GenericMeasure Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Minimum Indicates that the cmdlet displays the minimum value of the specified properties. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: GenericMeasure Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Property Specifies one or more properties to measure. If you do not specify any other measures, `Measure-Object` counts the objects that have the properties you specify. The value of the **Property** parameter can be a new calculated property. The calculated property must be a script block. For more information, see [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). ```yaml Type: Microsoft.PowerShell.Commands.PSPropertyExpression[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -StandardDeviation Indicates that the cmdlet displays the standard deviation of the values of the specified properties. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: GenericMeasure Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Sum Indicates that the cmdlet displays the sum of the values of the specified properties. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: GenericMeasure Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Word Indicates that the cmdlet counts the number of words in the input objects. > [!NOTE] > The **Word**, **Char** and **Line** switches count _inside_ each input object, as well as _across_ > input objects. See Example 7. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: TextMeasure Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.GenericMeasureInfo By default, this cmdlet returns a **GenericMeasureInfo** object. ### Microsoft.PowerShell.Commands.TextMeasureInfo When you use the **Word** parameter, this cmdlet returns a **TextMeasureInfo** object. ## NOTES PowerShell includes the following aliases for `Measure-Object`: - All platforms: - `measure` Starting in PowerShell 7.3, `Measure-Object` no longer returns an error when processing an object that is missing the property being measured unless you are running in **StrictMode**. In **StrictMode**, `Measure-Object` returns a `System.Management.Automation.PSArgumentException` when processing an object that is missing the specified property. ## RELATED LINKS [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md) [Compare-Object](Compare-Object.md) [ForEach-Object](../Microsoft.PowerShell.Core/ForEach-Object.md) [Group-Object](Group-Object.md) [New-Object](New-Object.md) [Select-Object](Select-Object.md) [Sort-Object](Sort-Object.md) [Tee-Object](Tee-Object.md) [Where-Object](../Microsoft.PowerShell.Core/Where-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Microsoft.PowerShell.Utility.md

--- Download Help Link: https://aka.ms/powershell75-help Help Version: 7.6.0.0 Locale: en-US Module Guid: 1da87e53-152b-403e-98dc-74d7b4d63d59 Module Name: Microsoft.PowerShell.Utility ms.date: 10/26/2022 schema: 2.0.0 title: Microsoft.PowerShell.Utility --- # Microsoft.PowerShell.Utility Module ## Description This section contains the help topics for the cmdlets that are installed with the Microsoft.PowerShell.Utility module. This module contains cmdlets that manage the basic features of PowerShell. ## Microsoft.PowerShell.Utility Cmdlets ### [Add-Member](Add-Member.md) Adds custom properties and methods to an instance of a PowerShell object. ### [Add-Type](Add-Type.md) Adds a Microsoft .NET class to a PowerShell session. ### [Clear-Variable](Clear-Variable.md) Deletes the value of a variable. ### [Compare-Object](Compare-Object.md) Compares two sets of objects. ### [ConvertFrom-CliXml](ConvertFrom-CliXml.md) Converts a CliXml-formatted string to a custom **PSObject**. ### [ConvertFrom-Csv](ConvertFrom-Csv.md) Converts object properties in character-separated value (CSV) format into CSV versions of the original objects. ### [ConvertFrom-Json](ConvertFrom-Json.md) Converts a JSON-formatted string to a custom object or a hash table. ### [ConvertFrom-Markdown](ConvertFrom-Markdown.md) Convert the contents of a string or a file to a **MarkdownInfo** object. ### [ConvertFrom-SddlString](ConvertFrom-SddlString.md) Converts a SDDL string to a custom object. ### [ConvertFrom-StringData](ConvertFrom-StringData.md) Converts a string containing one or more key and value pairs to a hash table. ### [ConvertTo-CliXml](ConvertTo-CliXml.md) Converts an object to a CliXml-formatted string. ### [ConvertTo-Csv](ConvertTo-Csv.md) Converts .NET objects into a series of character-separated value (CSV) strings. ### [ConvertTo-Html](ConvertTo-Html.md) Converts .NET objects into HTML that can be displayed in a Web browser. ### [ConvertTo-Json](ConvertTo-Json.md) Converts an object to a JSON-formatted string. ### [ConvertTo-Xml](ConvertTo-Xml.md) Creates an XML-based representation of an object. ### [Debug-Runspace](Debug-Runspace.md) Starts an interactive debugging session with a runspace. ### [Disable-PSBreakpoint](Disable-PSBreakpoint.md) Disables the breakpoints in the current console. ### [Disable-RunspaceDebug](Disable-RunspaceDebug.md) Disables debugging on one or more runspaces, and releases any pending debugger stop. ### [Enable-PSBreakpoint](Enable-PSBreakpoint.md) Enables the breakpoints in the current console. ### [Enable-RunspaceDebug](Enable-RunspaceDebug.md) Enables debugging on runspaces where any breakpoint is preserved until a debugger is attached. ### [Export-Alias](Export-Alias.md) Exports information about currently defined aliases to a file. ### [Export-Clixml](Export-Clixml.md) Creates an XML-based representation of an object or objects and stores it in a file. ### [Export-Csv](Export-Csv.md) Converts objects into a series of character-separated value (CSV) strings and saves the strings to a file. ### [Export-FormatData](Export-FormatData.md) Saves formatting data from the current session in a formatting file. ### [Export-PSSession](Export-PSSession.md) Exports commands from another session and saves them in a PowerShell module. ### [Format-Custom](Format-Custom.md) Uses a customized view to format the output. ### [Format-Hex](Format-Hex.md) Displays a file or other input as hexadecimal. ### [Format-List](Format-List.md) Formats the output as a list of properties in which each property appears on a new line. ### [Format-Table](Format-Table.md) Formats the output as a table. ### [Format-Wide](Format-Wide.md) Formats objects as a wide table that displays only one property of each object. ### [Get-Alias](Get-Alias.md) Gets the aliases for the current session. ### [Get-Culture](Get-Culture.md) Gets the current culture set in the operating system. ### [Get-Date](Get-Date.md) Gets the current date and time. ### [Get-Error](Get-Error.md) Gets and displays the most recent error messages from the current session. ### [Get-Event](Get-Event.md) Gets the events in the event queue. ### [Get-EventSubscriber](Get-EventSubscriber.md) Gets the event subscribers in the current session. ### [Get-FileHash](Get-FileHash.md) Computes the hash value for a file by using a specified hash algorithm. ### [Get-FormatData](Get-FormatData.md) Gets the formatting data in the current session. ### [Get-Host](Get-Host.md) Gets an object that represents the current host program. ### [Get-MarkdownOption](Get-MarkdownOption.md) Returns the current colors and styles used for rendering Markdown content in the console. ### [Get-Member](Get-Member.md) Gets the properties and methods of objects. ### [Get-PSBreakpoint](Get-PSBreakpoint.md) Gets the breakpoints that are set in the current session. ### [Get-PSCallStack](Get-PSCallStack.md) Displays the current call stack. ### [Get-Random](Get-Random.md) Gets a random number, or selects objects randomly from a collection. ### [Get-Runspace](Get-Runspace.md) Gets active runspaces within a PowerShell host process. ### [Get-RunspaceDebug](Get-RunspaceDebug.md) Shows runspace debugging options. ### [Get-SecureRandom](Get-SecureRandom.md) Gets a random number, or selects objects randomly from a collection. ### [Get-TraceSource](Get-TraceSource.md) Gets PowerShell components that are instrumented for tracing. ### [Get-TypeData](Get-TypeData.md) Gets the extended type data in the current session. ### [Get-UICulture](Get-UICulture.md) Gets the current UI culture settings in the operating system. ### [Get-Unique](Get-Unique.md) Returns unique items from a sorted list. ### [Get-Uptime](Get-Uptime.md) Get the **TimeSpan** since last boot. ### [Get-Variable](Get-Variable.md) Gets the variables in the current console. ### [Get-Verb](Get-Verb.md) Gets approved PowerShell verbs. ### [Group-Object](Group-Object.md) Groups objects that contain the same value for specified properties. ### [Import-Alias](Import-Alias.md) Imports an alias list from a file. ### [Import-Clixml](Import-Clixml.md) Imports a CLIXML file and creates corresponding objects in PowerShell. ### [Import-Csv](Import-Csv.md) Creates table-like custom objects from the items in a character-separated value (CSV) file. ### [Import-LocalizedData](Import-LocalizedData.md) Imports language-specific data into scripts and functions based on the UI culture that's selected for the operating system. ### [Import-PowerShellDataFile](Import-PowerShellDataFile.md) Imports values from a `.psd1` file without invoking its contents. ### [Import-PSSession](Import-PSSession.md) Imports commands from another session into the current session. ### [Invoke-Expression](Invoke-Expression.md) Runs commands or expressions on the local computer. ### [Invoke-RestMethod](Invoke-RestMethod.md) Sends an HTTP or HTTPS request to a RESTful web service. ### [Invoke-WebRequest](Invoke-WebRequest.md) Gets content from a web page on the internet. ### [Join-String](Join-String.md) Combines objects from the pipeline into a single string. ### [Measure-Command](Measure-Command.md) Measures the time it takes to run script blocks and cmdlets. ### [Measure-Object](Measure-Object.md) Calculates the numeric properties of objects, and the characters, words, and lines in string objects, such as files of text. ### [New-Alias](New-Alias.md) Creates a new alias. ### [New-Event](New-Event.md) Creates a new event. ### [New-Guid](New-Guid.md) Creates a GUID. ### [New-Object](New-Object.md) Creates an instance of a Microsoft .NET Framework or COM object. ### [New-TemporaryFile](New-TemporaryFile.md) Creates a temporary file. ### [New-TimeSpan](New-TimeSpan.md) Creates a TimeSpan object. ### [New-Variable](New-Variable.md) Creates a new variable. ### [Out-File](Out-File.md) Sends output to a file. ### [Out-GridView](Out-GridView.md) Sends output to an interactive table in a separate window. ### [Out-Printer](Out-Printer.md) Sends output to a printer. ### [Out-String](Out-String.md) Outputs input objects as a string. ### [Read-Host](Read-Host.md) Reads a line of input from the console. ### [Register-EngineEvent](Register-EngineEvent.md) Subscribes to events that are generated by the PowerShell engine and by the `New-Event` cmdlet. ### [Register-ObjectEvent](Register-ObjectEvent.md) Subscribes to the events that are generated by a Microsoft .NET Framework object. ### [Remove-Alias](Remove-Alias.md) Remove an alias from the current session. ### [Remove-Event](Remove-Event.md) Deletes events from the event queue. ### [Remove-PSBreakpoint](Remove-PSBreakpoint.md) Deletes breakpoints from the current console. ### [Remove-TypeData](Remove-TypeData.md) Deletes extended types from the current session. ### [Remove-Variable](Remove-Variable.md) Deletes a variable and its value. ### [Select-Object](Select-Object.md) Selects objects or object properties. ### [Select-String](Select-String.md) Finds text in strings and files. ### [Select-Xml](Select-Xml.md) Finds text in an XML string or document. ### [Send-MailMessage](Send-MailMessage.md) Sends an email message. ### [Set-Alias](Set-Alias.md) Creates or changes an alias for a cmdlet or other command in the current PowerShell session. ### [Set-Date](Set-Date.md) Changes the system time on the computer to a time that you specify. ### [Set-MarkdownOption](Set-MarkdownOption.md) Sets the colors and styles used for rendering Markdown content in the console. ### [Set-PSBreakpoint](Set-PSBreakpoint.md) Sets a breakpoint on a line, command, or variable. ### [Set-TraceSource](Set-TraceSource.md) Configures, starts, and stops a trace of PowerShell components. ### [Set-Variable](Set-Variable.md) Sets the value of a variable. Creates the variable if one with the requested name does not exist. ### [Show-Command](Show-Command.md) Displays PowerShell command information in a graphical window. ### [Show-Markdown](Show-Markdown.md) Shows a Markdown file or string in the console in a friendly way using VT100 escape sequences or in a browser using HTML. ### [Sort-Object](Sort-Object.md) Sorts objects by property values. ### [Start-Sleep](Start-Sleep.md) Suspends the activity in a script or session for the specified period of time. ### [Tee-Object](Tee-Object.md) Saves command output in a file or variable and also sends it down the pipeline. ### [Test-Json](Test-Json.md) Tests whether a string is a valid JSON document ### [Trace-Command](Trace-Command.md) Configures and starts a trace of the specified expression or command. ### [Unblock-File](Unblock-File.md) Unblocks files that were downloaded from the internet. ### [Unregister-Event](Unregister-Event.md) Cancels an event subscription. ### [Update-FormatData](Update-FormatData.md) Updates the formatting data in the current session. ### [Update-List](Update-List.md) Adds items to and removes items from a property value that contains a collection of objects. ### [Update-TypeData](Update-TypeData.md) Updates the extended type data in the session. ### [Wait-Debugger](Wait-Debugger.md) Stops a script in the debugger before running the next statement in the script. ### [Wait-Event](Wait-Event.md) Waits until a particular event is raised before continuing to run. ### [Write-Debug](Write-Debug.md) Writes a debug message to the console. ### [Write-Error](Write-Error.md) Writes an object to the error stream. ### [Write-Host](Write-Host.md) Writes customized output to a host. ### [Write-Information](Write-Information.md) Specifies how PowerShell handles information stream data for a command. ### [Write-Output](Write-Output.md) Writes the specified objects to the pipeline. ### [Write-Progress](Write-Progress.md) Displays a progress bar within a PowerShell command window. ### [Write-Verbose](Write-Verbose.md) Writes text to the verbose message stream. ### [Write-Warning](Write-Warning.md) Writes a warning message.

#File: reference/7.6/Microsoft.PowerShell.Utility/New-Alias.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 05/31/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/new-alias?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-Alias --- # New-Alias ## SYNOPSIS Creates a new alias. ## SYNTAX ``` New-Alias [-Name] <String> [-Value] <String> [-Description <String>] [-Option <ScopedItemOptions>] [-PassThru] [-Scope <String>] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `New-Alias` cmdlet creates a new alias in the current PowerShell session. Aliases created by using `New-Alias` are not saved after you exit the session or close PowerShell. You can use the `Export-Alias` cmdlet to save your alias information to a file. You can later use `Import-Alias` to retrieve that saved alias information. ## EXAMPLES ### Example 1: Create an alias for a cmdlet ```powershell New-Alias -Name "List" Get-ChildItem ``` This command creates an alias named List to represent the Get-ChildItem cmdlet. ### Example 2: Create a read-only alias for a cmdlet This command creates an alias named `C` to represent the `Get-ChildItem` cmdlet. It creates a description of "Quick gci alias" for the alias and makes it read-only. ```powershell New-Alias -Name "C" -Value Get-ChildItem -Description "Quick gci alias" -Option ReadOnly Get-Alias -Name "C" | Format-List * ``` ```Output HelpUri : https://go.microsoft.com/fwlink/?LinkID=2096492 ResolvedCommandName : Get-ChildItem DisplayName : C -> Get-ChildItem ReferencedCommand : Get-ChildItem ResolvedCommand : Get-ChildItem Definition : Get-ChildItem Options : ReadOnly Description : Quick gci alias OutputType : {System.IO.FileInfo, System.IO.DirectoryInfo} Name : C CommandType : Alias Source : Version : Visibility : Public ModuleName : Module : RemotingCapability : PowerShell Parameters : {[Path, System.Management.Automation.ParameterMetadata], [LiteralPath, System.Management.Automation.ParameterMetadata], [Filter, System.Management.Automation.ParameterMetadata], [Include, System.Management.Automation.ParameterMetadata]…} ``` The `Get-Alias` command piped to `Format-List` shows all of the information about the new alias. ### Example 3: Create an alias for a command with parameters ```powershell function Set-ParentDirectory {Set-Location -Path ..} New-Alias -Name .. -Value Set-ParentDirectory ``` The first command creates the function `Set-ParentDirectory`, which uses `Set-Location` to set the working location to the parent directory. The second command uses `New-Alias` to create an alias of `..` to call the `Set-ParentDirectory` function. Since the Value parameter requires a cmdlet, function, or executable value, you must create a custom function to create an alias that uses parameters. Running the alias `..` changes the current location to the parent directory. ## PARAMETERS ### -Description Specifies a description of the alias. You can type any string. If the description includes spaces, enclose it in quotation marks. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Indicates that the cmdlet acts like `Set-Alias` if the alias named already exists. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies the new alias. You can use any alphanumeric characters in an alias, but the first character cannot be a number. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Option Specifies the value of the **Options** property of the alias. Valid values are: - `None`: The alias has no constraints (default value) - `ReadOnly`: The alias can be deleted but cannot be changed except by using the **Force** parameter - `Constant`: The alias cannot be deleted or changed - `Private`: The alias is available only in the current scope - `AllScope`: The alias is copied to any new scopes that are created - `Unspecified`: The option is not specified These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **Option** parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. To see the **Options** property of all aliases in the session, type `Get-Alias | Format-Table -Property Name, Options -AutoSize`. ```yaml Type: System.Management.Automation.ScopedItemOptions Parameter Sets: (All) Aliases: Accepted values: None, ReadOnly, Constant, Private, AllScope, Unspecified Required: False Position: Named Default value: [System.Management.Automation.ScopedItemOptions]::None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Scope Specifies the scope of the new alias. The acceptable values for this parameter are: - `Global` - `Local` - `Script` - A number relative to the current scope (0 through the number of scopes, where `0` is the current scope and `1` is its parent). `Local` is the default. For more information, see [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Value Specifies the name of the cmdlet or command element that is being aliased. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.AliasInfo When you use the **PassThru** parameter, this cmdlet returns an **AliasInfo** object representing the new alias. ## NOTES PowerShell includes the following aliases for `New-Alias`: - All platforms: - `nal` - To create a new alias, use `Set-Alias` or `New-Alias`. To change an alias, use `Set-Alias`. To delete an alias, use `Remove-Alias`. ## RELATED LINKS [Export-Alias](Export-Alias.md) [Get-Alias](Get-Alias.md) [Import-Alias](Import-Alias.md) [Remove-Alias](Remove-Alias.md) [Set-Alias](Set-Alias.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/New-Event.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/new-event?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-Event --- # New-Event ## SYNOPSIS Creates a new event. ## SYNTAX ``` New-Event [-SourceIdentifier] <String> [[-Sender] <PSObject>] [[-EventArguments] <PSObject[]>] [[-MessageData] <PSObject>] [<CommonParameters>] ``` ## DESCRIPTION The `New-Event` cmdlet creates a new custom event. You can use custom events to notify users about state changes in your program and any change that your program can detect, including hardware or system conditions, application status, disk status, network status, or the completion of a background job. Custom events are automatically added to the event queue in your session whenever they are raised; you do not need to subscribe to them. However, if you want to forward an event to the local session or specify an action to respond to the event, use the `Register-EngineEvent` cmdlet to subscribe to the custom event. When you subscribe to a custom event, the event subscriber is added to your session. If you cancel the event subscription by using the `Unregister-Event` cmdlet, the event subscriber and custom event are deleted from the session. If you do not subscribe to the custom event, to delete the event, you must change the program conditions or close the PowerShell session. ## EXAMPLES ### Example 1: Create a new event in the event queue ``` PS C:\> New-Event -SourceIdentifier Timer -Sender Windows.Timer -MessageData "Test" ``` This command creates a new event in the PowerShell event queue. It uses a **Windows.Timer** object to send the event. ### Example 2: Raise an event in response to another event ``` PS C:\> function Enable-ProcessCreationEvent { $Query = New-Object System.Management.WqlEventQuery "__InstanceCreationEvent", (New-Object TimeSpan 0,0,1), "TargetInstance isa 'Win32_Process'" $ProcessWatcher = New-Object System.Management.ManagementEventWatcher $Query $Identifier = "WMI.ProcessCreated" Register-ObjectEvent $ProcessWatcher "EventArrived" -SupportEvent $Identifier -Action { [void] (New-Event -SourceId "PowerShell.ProcessCreated" -Sender $args[0] -EventArguments $args[1].SourceEventArgs.NewEvent.TargetInstance) } } ``` This sample function uses the `New-Event` cmdlet to raise an event in response to another event. The command uses the `Register-ObjectEvent` cmdlet to subscribe to the Windows Management Instrumentation (WMI) event that is raised when a new process is created. The command uses the **Action** parameter of the cmdlet to call the `New-Event` cmdlet, which creates the new event. Because the events that `New-Event` raises are automatically added to the PowerShell event queue, you do not need to register for that event. ## PARAMETERS ### -EventArguments Specifies an object that contains options for the event. ```yaml Type: System.Management.Automation.PSObject[] Parameter Sets: (All) Aliases: Required: False Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MessageData Specifies additional data associated with the event. The value of this parameter appears in the **MessageData** property of the event object. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: 3 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Sender Specifies the object that raises the event. The default is the PowerShell engine. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SourceIdentifier Specifies a name for the new event. This parameter is required, and it must be unique in the session. The value of this parameter appears in the **SourceIdentifier** property of the events. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSEventArgs ## NOTES No event sources available on the Linux or macOS platforms. The new custom event, the event subscription, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled. ## RELATED LINKS [Get-Event](Get-Event.md) [Register-EngineEvent](Register-EngineEvent.md) [Register-ObjectEvent](Register-ObjectEvent.md) [Remove-Event](Remove-Event.md) [Unregister-Event](Unregister-Event.md) [Wait-Event](Wait-Event.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/New-Guid.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/24/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/new-guid?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-Guid --- # New-Guid ## SYNOPSIS Creates a GUID. ## SYNTAX ### Default (Default) ``` New-Guid [<CommonParameters>] ``` ### Empty ``` New-Guid [-Empty] [<CommonParameters>] ``` ### InputObject ``` New-Guid [-InputObject <String>] [<CommonParameters>] ``` ## DESCRIPTION The `New-Guid` cmdlet creates a random globally unique identifier (GUID). If you need a unique ID in a script, you can create a GUID, as needed. ## EXAMPLES ### Example 1: Create a new GUID ```powershell New-Guid ``` This command creates a random GUID. Alternatively, you could store the output of this cmdlet in a variable to use elsewhere in a script. ### Example 2: Create an empty GUID ```powershell New-Guid -Empty ``` ```Output Guid ---- 00000000-0000-0000-0000-000000000000 ``` ### Example 3: Create a GUID from a string This example converts a string that contains a GUID to a GUID object. ```powershell New-Guid -InputObject "d61bbeca-0186-48fa-90e1-ff7aa5d33e2d" ``` ```Output Guid ---- d61bbeca-0186-48fa-90e1-ff7aa5d33e2d ``` ### Example 4: Convert strings from the pipeline to GUIDs This examples converts strings from the pipeline to GUID objects. ```powershell $guidStrings = ( '11c43ee8-b9d3-4e51-b73f-bd9dda66e29c', '0f8fad5bd9cb469fa16570867728950e', '{0x01234567, 0x89ab, 0xcdef,{0x01,0x23,0x45,0x67,0x89,0xab,0xcd,0xef}}' ) $guidStrings | New-Guid ``` ```Output Guid ---- 11c43ee8-b9d3-4e51-b73f-bd9dda66e29c 0f8fad5b-d9cb-469f-a165-70867728950e 01234567-89ab-cdef-0123-456789abcdef ``` ## PARAMETERS ### -Empty Indicates that this cmdlet creates an empty GUID. An empty GUID has all zeros in its string. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Empty Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject This parameter accepts a string representing a GUID and converts it to a GUID object. ```yaml Type: System.String Parameter Sets: InputObject Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ## OUTPUTS ### System.Guid This cmdlet returns a GUID. ## NOTES The cmdlet passes string input to the constructor of the **System.Guid** class. The constructor support strings in several formats. For more information, see [System.Guid(String)](/dotnet/api/system.guid.-ctor#system-guid-ctor(system-string)). When used without string input or the **Empty** parameter, the cmdlet creates a Version 4 Universally Unique Identifier (UUID). For more information, see [System.Guid.NewGuid](xref:System.Guid.NewGuid). ## RELATED LINKS

#File: reference/7.6/Microsoft.PowerShell.Utility/New-Object.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/new-object?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-Object --- # New-Object ## SYNOPSIS Creates an instance of a Microsoft .NET Framework or COM object. ## SYNTAX ### Net (Default) ``` New-Object [-TypeName] <String> [[-ArgumentList] <Object[]>] [-Property <IDictionary>] [<CommonParameters>] ``` ### Com ``` New-Object [-ComObject] <String> [-Strict] [-Property <IDictionary>] [<CommonParameters>] ``` ## DESCRIPTION The `New-Object` cmdlet creates an instance of a .NET Framework or COM object. You can specify either the type of a .NET Framework class or a ProgID of a COM object. By default, you type the fully qualified name of a .NET Framework class and the cmdlet returns a reference to an instance of that class. To create an instance of a COM object, use the **ComObject** parameter and specify the ProgID of the object as its value. ## EXAMPLES ### Example 1: Create a System.Version object This example creates a **System.Version** object using the "1.2.3.4" string as the constructor. ```powershell New-Object -TypeName System.Version -ArgumentList "1.2.3.4" ``` ```Output Major Minor Build Revision ----- ----- ----- -------- 1 2 3 4 ``` ### Example 2: Create an Internet Explorer COM object This example creates two instances of the COM object that represents the Internet Explorer application. The first instance uses the **Property** parameter hash table to call the **Navigate2** method and set the **Visible** property of the object to `$true` to make the application visible. The second instance gets the same results with individual commands. ```powershell $IE1 = New-Object -ComObject InternetExplorer.Application -Property @{Navigate2="www.microsoft.com"; Visible = $true} # The following command gets the same results as the example above. $IE2 = New-Object -ComObject InternetExplorer.Application` $IE2.Navigate2("www.microsoft.com")` $IE2.Visible = $true` ``` ### Example 3: Use the Strict parameter to generate a non-terminating error This example demonstrates that adding the **Strict** parameter causes the `New-Object` cmdlet to generate a non-terminating error when the COM object uses an interop assembly. ```powershell $A = New-Object -ComObject Word.Application -Strict -Property @{Visible = $true} ``` ```Output New-Object : The object written to the pipeline is an instance of the type "Microsoft.Office.Interop.Word.ApplicationClass" from the component's primary interop assembly. If this type exposes different members than the IDispatch members, scripts written to work with this object might not work if the primary interop assembly is not installed. At line:1 char:14 + $A = New-Object <<<< -ComObject Word.Application -Strict; $a.Visible=$true ``` ### Example 4: Create a COM object to manage Windows desktop This example shows how to create and use a COM object to manage your Windows desktop. The first command uses the **ComObject** parameter of the `New-Object` cmdlet to create a COM object with the **Shell.Application** ProgID. It stores the resulting object in the `$objShell` variable. The second command pipes the `$objShell` variable to the `Get-Member` cmdlet, which displays the properties and methods of the COM object. Among the methods is the **ToggleDesktop** method. The third command calls the **ToggleDesktop** method of the object to minimize the open windows on your desktop. ```powershell $objShell = New-Object -ComObject "Shell.Application" $objShell | Get-Member $objShell.ToggleDesktop() ``` ```Output TypeName: System.__ComObject#{866738b9-6cf2-4de8-8767-f794ebe74f4e} Name MemberType Definition ---- ---------- ---------- AddToRecent Method void AddToRecent (Variant, string) BrowseForFolder Method Folder BrowseForFolder (int, string, int, Variant) CanStartStopService Method Variant CanStartStopService (string) CascadeWindows Method void CascadeWindows () ControlPanelItem Method void ControlPanelItem (string) EjectPC Method void EjectPC () Explore Method void Explore (Variant) ExplorerPolicy Method Variant ExplorerPolicy (string) FileRun Method void FileRun () FindComputer Method void FindComputer () FindFiles Method void FindFiles () FindPrinter Method void FindPrinter (string, string, string) GetSetting Method bool GetSetting (int) GetSystemInformation Method Variant GetSystemInformation (string) Help Method void Help () IsRestricted Method int IsRestricted (string, string) IsServiceRunning Method Variant IsServiceRunning (string) MinimizeAll Method void MinimizeAll () NameSpace Method Folder NameSpace (Variant) Open Method void Open (Variant) RefreshMenu Method void RefreshMenu () ServiceStart Method Variant ServiceStart (string, Variant) ServiceStop Method Variant ServiceStop (string, Variant) SetTime Method void SetTime () ShellExecute Method void ShellExecute (string, Variant, Variant, Variant, Variant) ShowBrowserBar Method Variant ShowBrowserBar (string, Variant) ShutdownWindows Method void ShutdownWindows () Suspend Method void Suspend () TileHorizontally Method void TileHorizontally () TileVertically Method void TileVertically () ToggleDesktop Method void ToggleDesktop () TrayProperties Method void TrayProperties () UndoMinimizeALL Method void UndoMinimizeALL () Windows Method IDispatch Windows () WindowsSecurity Method void WindowsSecurity () WindowSwitcher Method void WindowSwitcher () Application Property IDispatch Application () {get} Parent Property IDispatch Parent () {get} ``` ### Example 5: Pass multiple arguments to a constructor This example shows how to create an object with a constructor that takes multiple parameters. The parameters must be put in an array when using **ArgumentList** parameter. ```powershell $array = @('One', 'Two', 'Three') $parameters = @{ TypeName = 'System.Collections.Generic.HashSet[string]' ArgumentList = ([string[]]$array, [System.StringComparer]::OrdinalIgnoreCase) } $set = New-Object @parameters ``` PowerShell binds each member of the array to a parameter of the constructor. > [!NOTE] > This example uses parameter splatting for readability. For more information, see > [about_Splatting](../Microsoft.PowerShell.Core/About/about_Splatting.md). ### Example 6: Calling a constructor that takes an array as a single parameter This example shows how to create an object with a constructor that takes a parameter that is an array or collection. The array parameter must be put in wrapped inside another array. ```powershell $array = @('One', 'Two', 'Three') # This command throws an exception. $set = New-Object -TypeName 'System.Collections.Generic.HashSet[string]' -ArgumentList $array # This command succeeds. $set = New-Object -TypeName 'System.Collections.Generic.HashSet[string]' -ArgumentList (,[string[]]$array) $set ``` ```Output New-Object : Cannot find an overload for "HashSet`1" and the argument count: "3". At line:1 char:8 + $set = New-Object -TypeName 'System.Collections.Generic.HashSet[strin ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [New-Object], MethodException + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand One Two Three ``` The first attempt to create the object in this example fails. PowerShell attempted to bind the three members of `$array` to parameters of the constructor but the constructor does not take three parameter. Wrapping `$array` in another array prevents PowerShell from attempting to bind the three members of `$array` to parameters of the constructor. ## PARAMETERS ### -ArgumentList Specifies an array of arguments to pass to the constructor of the .NET Framework class. If the constructor takes a single parameter that is an array, you must wrap that parameter inside another array. For example: `$cert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate -ArgumentList (,$bytes)` For more information about the behavior of **ArgumentList**, see [about_Splatting](../Microsoft.PowerShell.Core/About/about_Splatting.md#splatting-with-arrays). The alias for **ArgumentList** is **Args**. ```yaml Type: System.Object[] Parameter Sets: Net Aliases: Args Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComObject Specifies the programmatic identifier (ProgID) of the COM object. ```yaml Type: System.String Parameter Sets: Com Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Property Sets property values and invokes methods of the new object. Enter a hash table in which the keys are the names of properties or methods and the values are property values or method arguments. `New-Object` creates the object and sets each property value and invokes each method in the order that they appear in the hash table. If the new object is derived from the **PSObject** class, and you specify a property that does not exist on the object, `New-Object` adds the specified property to the object as a NoteProperty. If the object is not a **PSObject**, the command generates a non-terminating error. ```yaml Type: System.Collections.IDictionary Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Strict Indicates that the cmdlet generates a non-terminating error when a COM object that you attempt to create uses an interop assembly. This feature distinguishes actual COM objects from .NET Framework objects with COM-callable wrappers. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Com Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TypeName Specifies the fully qualified name of the .NET Framework class. You cannot specify both the **TypeName** parameter and the **ComObject** parameter. ```yaml Type: System.String Parameter Sets: Net Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Object This cmdlet returns the object that it creates. ## NOTES - `New-Object` provides the most commonly-used functionality of the VBScript CreateObject function. A statement like `Set objShell = CreateObject("Shell.Application")` in VBScript can be translated to `$objShell = New-Object -ComObject "Shell.Application"` in PowerShell. - `New-Object` expands upon the functionality available in the Windows Script Host environment by making it easy to work with .NET Framework objects from the command line and within scripts. ## RELATED LINKS [about_Object_Creation](../Microsoft.PowerShell.Core/About/about_Object_Creation.md) [Compare-Object](Compare-Object.md) [Group-Object](Group-Object.md) [Measure-Object](Measure-Object.md) [Select-Object](Select-Object.md) [Sort-Object](Sort-Object.md) [Tee-Object](Tee-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/New-TemporaryFile.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 03/16/2020 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/new-temporaryfile?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-TemporaryFile --- # New-TemporaryFile ## SYNOPSIS Creates a temporary file. ## SYNTAX ``` New-TemporaryFile [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION This cmdlet creates temporary files that you can use in scripts. The `New-TemporaryFile` cmdlet creates an empty file that has the `.tmp` file name extension. This cmdlet names the file `tmp<NNNN>.tmp`, where `<NNNN>` is a random hexadecimal number. The cmdlet creates the file in your **TEMP** folder. This cmdlet uses the [Path.GetTempPath()](/dotnet/api/system.io.path.gettemppath) method to find your **TEMP** folder. This method checks for the existence of environment variables in the following order and uses the first path found: - On Windows platforms: 1. The path specified by the TMP environment variable. 1. The path specified by the TEMP environment variable. 1. The path specified by the USERPROFILE environment variable. 1. The Windows directory. - On non-Windows platforms: Uses the path specified by the TMPDIR environment variable. ## EXAMPLES ### Example 1: Create a temporary file ```powershell $TempFile = New-TemporaryFile ``` This command generates a `.tmp` file in your temporary folder, and then stores a reference to the file in the `$TempFile` variable. You can use this file later in your script. ## PARAMETERS ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ## OUTPUTS ### System.IO.FileInfo This cmdlet returns a **FileInfo** object that represents the temporary file. ## NOTES ## RELATED LINKS

#File: reference/7.6/Microsoft.PowerShell.Utility/New-TimeSpan.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/new-timespan?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-TimeSpan --- # New-TimeSpan ## SYNOPSIS Creates a TimeSpan object. ## SYNTAX ### Date (Default) ``` New-TimeSpan [[-Start] <DateTime>] [[-End] <DateTime>] [<CommonParameters>] ``` ### Time ``` New-TimeSpan [-Days <Int32>] [-Hours <Int32>] [-Minutes <Int32>] [-Seconds <Int32>] [-Milliseconds <Int32>] [<CommonParameters>] ``` ## DESCRIPTION The `New-TimeSpan` cmdlet creates a **TimeSpan** object that represents a time interval. You can use a **TimeSpan** object to add or subtract time from **DateTime** objects. Without parameters, a `New-TimeSpan` command returns a **TimeSpan** object that represents a time interval of zero. ## EXAMPLES ### Example 1: Create a TimeSpan object for a specified duration This command creates a **TimeSpan** object with a duration of 1 hour and 25 minutes and stores it in a variable named `$TimeSpan`. It displays a representation of the **TimeSpan** object. ```powershell $TimeSpan = New-TimeSpan -Hours 1 -Minutes 25 $TimeSpan ``` ```Output Days : 0 Hours : 1 Minutes : 25 Seconds : 0 Milliseconds : 0 Ticks : 51000000000 TotalDays : 0.0590277777777778 TotalHours : 1.41666666666667 TotalMinutes : 85 TotalSeconds : 5100 TotalMilliseconds : 5100000 ``` ### Example 2: Create a TimeSpan object for a time interval This example creates a new **TimeSpan** object that represents the interval between the time that the command is run and January 1, 2010. This command doesn't require the **Start** parameter, because the default value of the **Start** parameter is the current date and time. ```powershell New-TimeSpan -End (Get-Date -Year 2010 -Month 1 -Day 1) ``` ### Example 3: Get the date 90 days from the current date ```powershell $90days = New-TimeSpan -Days 90 (Get-Date) + $90days ``` These commands return the date that is 90 days after the current date. ### Example 4: Discover the TimeSpan since a file was updated This command tells you how long it has been since the [about_Remote](../Microsoft.PowerShell.Core/About/about_Remote.md) help file was last updated. You can use this command format on any file, or any other object that has a **LastWriteTime** property. This command works because the **Start** parameter of `New-TimeSpan` has an alias of **LastWriteTime**. When you pipe an object that has a **LastWriteTime** property to `New-TimeSpan`, PowerShell uses the value of the **LastWriteTime** property as the value of the **Start** parameter. ```powershell Get-ChildItem $PSHOME\en-US\about_remote.help.txt | New-TimeSpan ``` ```Output Days : 321 Hours : 21 Minutes : 59 Seconds : 22 Milliseconds : 312 Ticks : 278135623127728 TotalDays : 321.916230471907 TotalHours : 7725.98953132578 TotalMinutes : 463559.371879547 TotalSeconds : 27813562.3127728 TotalMilliseconds : 27813562312.7728 ``` ## PARAMETERS ### -Days Specifies the days in the time span. The default value is 0. ```yaml Type: System.Int32 Parameter Sets: Time Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -End Specifies the end of a time span. The default value is the current date and time. ```yaml Type: System.DateTime Parameter Sets: Date Aliases: Required: False Position: 1 Default value: Current date and time Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Hours Specifies the hours in the time span. The default value is 0. ```yaml Type: System.Int32 Parameter Sets: Time Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Milliseconds Specifies the length of the time span in milliseconds. The default value is 0. ```yaml Type: System.Int32 Parameter Sets: Time Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Minutes Specifies the minutes in the time span. The default value is 0. ```yaml Type: System.Int32 Parameter Sets: Time Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Seconds Specifies the length of the time span in seconds. The default value is 0. ```yaml Type: System.Int32 Parameter Sets: Time Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Start Specifies the start of a time span. Enter a string that represents the date and time, such as "3/15/09" or a **DateTime** object, such as one from a `Get-Date` command. The default value is the current date and time. You can use **Start** or its alias, **LastWriteTime**. The **LastWriteTime** alias lets you pipe objects that have a **LastWriteTime** property, such as files in the file system (`[IO.FileInfo]`), to the **Start** parameter of `New-TimeSpan`. ```yaml Type: System.DateTime Parameter Sets: Date Aliases: LastWriteTime Required: False Position: 0 Default value: Current date and time Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.DateTime You can pipe a **DateTime** object representing the start time to this cmdlet. ## OUTPUTS ### System.TimeSpan This cmdlet returns an object representing the time span. ## NOTES ## RELATED LINKS [Get-Date](Get-Date.md) [Set-Date](Set-Date.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/New-Variable.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/new-variable?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-Variable --- # New-Variable ## SYNOPSIS Creates a new variable. ## SYNTAX ``` New-Variable [-Name] <String> [[-Value] <Object>] [-Description <String>] [-Option <ScopedItemOptions>] [-Visibility <SessionStateEntryVisibility>] [-Force] [-PassThru] [-Scope <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `New-Variable` cmdlet creates a new variable in PowerShell. You can assign a value to the variable while creating it or assign or change the value after it is created. You can use the parameters of `New-Variable` to set the properties of the variable, set the scope of a variable, and determine whether variables are public or private. Typically, you create a new variable by typing the variable name and its value, such as `$Var = 3`, but you can use the `New-Variable` cmdlet to use its parameters. ## EXAMPLES ### Example 1: Create a variable ``` New-Variable days ``` This command creates a new variable named days. You are not required to type the **Name** parameter. ### Example 2: Create a variable and assign it a value ``` New-Variable -Name "zipcode" -Value 98033 ``` This command creates a variable named zipcode and assigns it the value 98033. ### Example 3: Create a variable with the ReadOnly option ``` PS C:\> New-Variable -Name Max -Value 256 -Option ReadOnly PS C:\> New-Variable -Name max -Value 1024 New-Variable : A variable with name 'max' already exists. At line:1 char:1 + New-Variable -Name max -Value 1024 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceExists: (max:String) [New-Variable], SessionStateException + FullyQualifiedErrorId : VariableAlreadyExists,Microsoft.PowerShell.Commands.NewVariableCommand PS C:\> New-Variable -Name max -Value 1024 -Force ``` This example shows how to use the `ReadOnly` option of `New-Variable` to protect a variable from being overwritten. The first command creates a new variable named Max and sets its value to 256. It uses the **Option** parameter with a value of `ReadOnly`. The second command tries to create a second variable with the same name. This command returns an error, because the read-only option is set on the variable. The third command uses the **Force** parameter to override the read-only protection on the variable. In this case, the command to create a new variable with the same name succeeds. ### Example 4: Assign multiple options to a variable ```powershell New-Variable -Name 'TestVariable' -Value 'Test Value' -Option AllScope,Constant ``` This example creates a variable and assigns the `AllScope` and `Constant` options so the variable will be available in the current scope and any new scopes created and cannot be changed or deleted. ### Example 5: Create a private variable This command demonstrates the behavior of a private variable in a module. The module contains the `Get-Counter` cmdlet, which has a private variable named Counter. The command uses the **Visibility** parameter with a value of Private to create the variable. ``` PS C:\> New-Variable -Name counter -Visibility Private #Effect of private variable in a module. PS C:\> Get-Variable c* Name Value ---- ----- Culture en-US ConsoleFileName ConfirmPreference High CommandLineParameters {} PS C:\> $counter "Cannot access the variable '$counter' because it is a private variable" At line:1 char:1 + $counter + ~~~~~~~~ + CategoryInfo : PermissionDenied: (counter:String) [], SessionStateException + FullyQualifiedErrorId : VariableIsPrivate PS C:\> Get-Counter Name Value ---- ----- Counter1 3.1415 ... ``` The sample output shows the behavior of a private variable. The user who has loaded the module cannot view or change the value of the Counter variable, but the Counter variable can be read and changed by the commands in the module. ### Example 6: Create a variable with a space This example demonstrates that variables with spaces can be created. The variables can be accessed using the `Get-Variable` cmdlet or directly by delimiting a variable with braces. ``` PS C:\> New-Variable -Name 'with space' -Value 'abc123xyz' PS C:\> Get-Variable -Name 'with space' Name Value ---- ----- with space abc123xyz PS C:\> ${with space} abc123xyz ``` ## PARAMETERS ### -Description Specifies a description of the variable. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Indicates that the cmdlet creates a variable with the same name as an existing read-only variable. By default, you can overwrite a variable unless the variable has an option value of `ReadOnly` or `Constant`. For more information, see the **Option** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies a name for the new variable. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Option Specifies the value of the **Options** property of the variable. The acceptable values for this parameter are: - `None` - Sets no options. `None` is the default. - `ReadOnly` - Can be deleted. Cannot be changed, except by using the **Force** parameter. - `Private` - The variable is available only in the current scope. - `AllScope` - The variable is copied to any new scopes that are created. - `Constant` - Cannot be deleted or changed. `Constant` is valid only when you are creating a variable. You cannot change the options of an existing variable to `Constant`. These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **Option** parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. To see the Options property of all variables in the session, type `Get-Variable | Format-Table -Property Name, Options -AutoSize`. ```yaml Type: System.Management.Automation.ScopedItemOptions Parameter Sets: (All) Aliases: Accepted values: None, ReadOnly, Constant, Private, AllScope, Unspecified Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Scope Specifies the scope of the new variable. The acceptable values for this parameter are: - `Global` - Variables created in the global scope are accessible everywhere in a PowerShell process. - `Local` - The local scope refers to the current scope, this can be any scope depending on the context. `Local` is the default scope when the scope parameter is not specified. - `Script` - Variables created in the script scope are accessible only within the script file or module they are created in. - A number relative to the current scope (0 through the number of scopes, where 0 is the current scope, 1 is its parent, 2 the parent of the parent scope, and so on). Negative numbers cannot be used. > [!NOTE] > The parameter also accepts the value of `Private`. `Private` is not actually a scope but an > optional setting for a variable. However, using the `Private` value with this cmdlet does not > change the visibility of the variable. For more information, see > [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Value Specifies the initial value of the variable. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Visibility Determines whether the variable is visible outside of the session in which it was created. This parameter is designed for use in scripts and commands that will be delivered to other users. The acceptable values for this parameter are: - `Public` - The variable is visible. `Public` is the default. - `Private` - The variable is not visible. When a variable is private, it does not appear in lists of variables, such as those returned by `Get-Variable`, or in displays of the `Variable:` drive. Commands to read or change the value of a private variable return an error. However, the user can run commands that use a private variable if the commands were written in the session in which the variable was defined. ```yaml Type: System.Management.Automation.SessionStateEntryVisibility Parameter Sets: (All) Aliases: Accepted values: Public, Private Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Object You can pipe any object to `New-Variable`. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSVariable When you use the **PassThru** parameter, this cmdlet returns a **PSVariable** object representing the new variable. ## NOTES PowerShell includes the following aliases for `New-Variable`: - All platforms: - `nv` ## RELATED LINKS [Clear-Variable](Clear-Variable.md) [Get-Variable](Get-Variable.md) [Remove-Variable](Remove-Variable.md) [Set-Variable](Set-Variable.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Out-File.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 11/29/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/out-file?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Out-File --- # Out-File ## SYNOPSIS Sends output to a file. ## SYNTAX ### ByPath (Default) ``` Out-File [-FilePath] <string> [[-Encoding] <Encoding>] [-Append] [-Force] [-NoClobber] [-Width <int>] [-NoNewline] [-InputObject <psobject>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ByLiteralPath ``` Out-File [[-Encoding] <Encoding>] -LiteralPath <string> [-Append] [-Force] [-NoClobber] [-Width <int>] [-NoNewline] [-InputObject <psobject>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Out-File` cmdlet sends output to a file. It implicitly uses PowerShell's formatting system to write to the file. The file receives the same display representation as the terminal. This means that the output may not be ideal for programmatic processing unless all input objects are strings. Redirecting the output of a PowerShell command (cmdlet, function, script) using the redirection operator (`>`) is functionally equivalent to piping to `Out-File` with no extra parameters. PowerShell 7.4 changed the behavior of the redirection operator when used to redirect the **stdout** stream of a native command. For more information about redirection, see [about_Redirection](../Microsoft.PowerShell.Core/About/about_Redirection.md). ## EXAMPLES ### Example 1: Send output and create a file This example shows how to send a list of the local computer's processes to a file. If the file does not exist, `Out-File` creates the file in the specified path. ```powershell Get-Process | Out-File -FilePath .\Process.txt Get-Content -Path .\Process.txt ``` ```Output NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 29 22.39 35.40 10.98 42764 9 Application 53 99.04 113.96 0.00 32664 0 CcmExec 27 96.62 112.43 113.00 17720 9 Code ``` The `Get-Process` cmdlet gets the list of processes running on the local computer. The **Process** objects are sent down the pipeline to the `Out-File` cmdlet. `Out-File` uses the **FilePath** parameter and creates a file in the current directory named **Process.txt**. The `Get-Content` command gets content from the file and displays it in the PowerShell console. ### Example 2: Prevent an existing file from being overwritten This example prevents an existing file from being overwritten. By default, `Out-File` overwrites existing files. ```powershell Get-Process | Out-File -FilePath .\Process.txt -NoClobber ``` ```Output Out-File : The file 'C:\Test\Process.txt' already exists. At line:1 char:15 + Get-Process | Out-File -FilePath .\Process.txt -NoClobber + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` The `Get-Process` cmdlet gets the list of processes running on the local computer. The **Process** objects are sent down the pipeline to the `Out-File` cmdlet. `Out-File` uses the **FilePath** parameter and attempts to write to a file in the current directory named **Process.txt**. The **NoClobber** parameter prevents the file from being overwritten and displays a message that the file already exists. ### Example 3: Send output to a file in ASCII format This example shows how to encode output with a specific encoding type. ```powershell $Procs = Get-Process Out-File -FilePath .\Process.txt -InputObject $Procs -Encoding ascii -Width 50 ``` The `Get-Process` cmdlet gets the list of processes running on the local computer. The **Process** objects are stored in the variable, `$Procs`. `Out-File` uses the **FilePath** parameter and creates a file in the current directory named **Process.txt**. The **InputObject** parameter passes the process objects in `$Procs` to the file **Process.txt**. The **Encoding** parameter converts the output to **ASCII** format. The **Width** parameter limits each line in the file to 50 characters so some data might be truncated. ### Example 4: Use a provider and send output to a file This example shows how to use the `Out-File` cmdlet when you aren't in a **FileSystem** provider drive. Use the `Get-PSProvider` cmdlet to view the providers on your local computer. For more information, see [about_Providers](../Microsoft.Powershell.Core/About/about_Providers.md). ``` PS> Set-Location -Path Alias: PS> Get-Location Path ---- Alias:\ PS> Get-ChildItem | Out-File -FilePath C:\TestDir\AliasNames.txt PS> Get-Content -Path C:\TestDir\AliasNames.txt CommandType Name ----------- ---- Alias % -> ForEach-Object Alias ? -> Where-Object Alias ac -> Add-Content Alias cat -> Get-Content ``` The `Set-Location` command uses the **Path** parameter to set the current location to the registry provider `Alias:`. The `Get-Location` cmdlet displays the complete path for `Alias:`. `Get-ChildItem` sends objects down the pipeline to the `Out-File` cmdlet. `Out-File` uses the **FilePath** parameter to specify the complete path and filename for the output, **C:\TestDir\AliasNames.txt**. The `Get-Content` cmdlet uses the **Path** parameter and displays the file's content in the PowerShell console. ### Example 5: Set file output width for entire scope This example uses `$PSDefaultParameterValues` to set the `Width` parameter for all invocations of `Out-File` and the redirection operators (`>` and `>>`) to 2000. This ensures that everywhere within the current scope that you output table formatted data to file, PowerShell uses a line width of 2000 instead of a line width determined by the PowerShell host's console width. ```powershell function DemoDefaultOutFileWidth() { try { $PSDefaultParameterValues['Out-File:Width'] = 2000 $logFile = "$PWD\logfile.txt" Get-ChildItem Env:\ > $logFile Get-Service -ErrorAction Ignore | Format-Table -AutoSize | Out-File $logFile -Append Get-Process | Format-Table Id,SI,Name,Path,MainWindowTitle >> $logFile } finally { $PSDefaultParameterValues.Remove('Out-File:Width') } } DemoDefaultOutFileWidth ``` For more information about `$PSDefaultParameterValues`, see [about_Preference_Variables](../Microsoft.Powershell.Core/About/about_preference_variables.md#psdefaultparametervalues). ## PARAMETERS ### -Append Adds the output to the end of an existing file. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Encoding Specifies the type of encoding for the target file. The default value is `utf8NoBOM`. The acceptable values for this parameter are as follows: - `ascii`: Uses the encoding for the ASCII (7-bit) character set. - `ansi`: Uses the encoding for the for the current culture's ANSI code page. This option was added in PowerShell 7.4. - `bigendianunicode`: Encodes in UTF-16 format using the big-endian byte order. - `bigendianutf32`: Encodes in UTF-32 format using the big-endian byte order. - `oem`: Uses the default encoding for MS-DOS and console programs. - `unicode`: Encodes in UTF-16 format using the little-endian byte order. - `utf7`: Encodes in UTF-7 format. - `utf8`: Encodes in UTF-8 format. - `utf8BOM`: Encodes in UTF-8 format with Byte Order Mark (BOM) - `utf8NoBOM`: Encodes in UTF-8 format without Byte Order Mark (BOM) - `utf32`: Encodes in UTF-32 format. Beginning with PowerShell 6.2, the **Encoding** parameter also allows numeric IDs of registered code pages (like `-Encoding 1251`) or string names of registered code pages (like `-Encoding "windows-1251"`). For more information, see the .NET documentation for [Encoding.CodePage](/dotnet/api/system.text.encoding.codepage?view=netcore-2.2). Starting with PowerShell 7.4, you can use the `Ansi` value for the **Encoding** parameter to pass the numeric ID for the current culture's ANSI code page without having to specify it manually. > [!NOTE] > **UTF-7*** is no longer recommended to use. As of PowerShell 7.1, a warning is written if you > specify `utf7` for the **Encoding** parameter. ```yaml Type: System.Text.Encoding Parameter Sets: (All) Aliases: Accepted values: ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 Required: False Position: 1 Default value: UTF8NoBOM Accept pipeline input: False Accept wildcard characters: False ``` ### -FilePath Specifies the path to the output file. ```yaml Type: System.String Parameter Sets: ByPath Aliases: Path Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Overrides the read-only attribute and overwrites an existing read-only file. The **Force** parameter doesn't override security restrictions. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects to be written to the file. Enter a variable that contains the objects or type a command or expression that gets the objects. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to the output file. The **LiteralPath** parameter is used exactly as it's typed. Wildcard characters aren't accepted. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String Parameter Sets: ByLiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -NoClobber **NoClobber** prevents an existing file from being overwritten and displays a message that the file already exists. By default, if a file exists in the specified path, `Out-File` overwrites the file without warning. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: NoOverwrite Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NoNewline Specifies that the content written to the file doesn't end with a newline character. The string representations of the input objects are concatenated to form the output. No spaces or newlines are inserted between the output strings. No newline is added after the last output string. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Width Specifies the maximum number of characters in each line of output. Any additional characters are truncated, not wrapped. If this parameter isn't used, the width is determined by the characteristics of the host. The default for the PowerShell console is 80 characters. If you want to control the width for all invocations of `Out-File` as well as the redirection operators (`>` and `>>`), set `$PSDefaultParameterValues['Out-File:Width'] = 2000` before using `Out-File`. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES Input objects are automatically formatted as they would be in the terminal, but you can use a `Format-*` cmdlet to explicitly control the formatting of the output to the file. For example, `Get-Date | Format-List | Out-File out.txt` To send a PowerShell command's output to the `Out-File` cmdlet, use the pipeline. Alternatively, you can store data in a variable and use the **InputObject** parameter to pass data to the `Out-File` cmdlet. `Out-File` saves data to a file but it doesn't produce any output objects to the pipeline. PowerShell 7.2 added the ability to control how ANSI escape sequences are rendered. ANSI-decorated output that's passed to `Out-File` can be changed based on the setting of the `$PSStyle.OutputRendering` property. For more information, see [about_ANSI_Terminals](/powershell/module/microsoft.powershell.core/about/about_ansi_terminals). ## RELATED LINKS [about_Providers](../Microsoft.Powershell.Core/About/about_Providers.md) [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md) [Out-Default](../Microsoft.PowerShell.Core/Out-Default.md) [Out-Host](../Microsoft.PowerShell.Core/Out-Host.md) [Out-Null](../Microsoft.PowerShell.Core/Out-Null.md) [Out-String](Out-String.md) [Tee-Object](Tee-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Out-GridView.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 06/28/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/out-gridview?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Out-GridView --- # Out-GridView ## SYNOPSIS Sends output to an interactive table in a separate window. ## SYNTAX ### PassThru (Default) ``` Out-GridView [-InputObject <PSObject>] [-Title <String>] [-PassThru] [<CommonParameters>] ``` ### Wait ``` Out-GridView [-InputObject <PSObject>] [-Title <String>] [-Wait] [<CommonParameters>] ``` ### OutputMode ``` Out-GridView [-InputObject <PSObject>] [-Title <String>] [-OutputMode <OutputModeOption>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Out-GridView` cmdlet sends the output from a command to a grid view window where the output is displayed in an interactive table. Because this cmdlet requires a user interface, it does not work on Windows Server Core or Windows Nano Server. You can use the following features of the table to examine your data: - Hide, show, and reorder columns - Sort rows - Quick filter - Add criteria filter - Copy and paste For full instructions, see the [Notes](#notes) section of this article. > [!NOTE] > This cmdlet was reintroduced in PowerShell 7. This cmdlet is only available on Windows systems > that support the Windows Desktop. For a cross-platform version of this cmdlet, see the > [ConsoleGuiTools](https://www.powershellgallery.com/packages/Microsoft.PowerShell.ConsoleGuiTools) > module in the PowerShell Gallery. ## EXAMPLES ### Example 1: Output processes to a grid view This example gets the processes running on the local computer and sends them to a grid view window. ```powershell Get-Process | Out-GridView ``` ### Example 2: Use a variable to output processes to a grid view This example also gets the processes running on the local computer and sends them to a grid view window. ```powershell $P = Get-Process $P | Out-GridView ``` The output of the `Get-Process` cmdlet is saved in the `$P` variable. Then, `$P` is piped to `Out-GridView`. ### Example 3: Display a selected properties in a grid view This example displays selected properties of the running processes in a grid view. ```powershell Get-Process | Select-Object -Property Name, WorkingSet, PeakWorkingSet | Sort-Object -Property WorkingSet -Descending | Out-GridView ``` The output of `Get-Process` is piped to `Select-Object` to select the **Name**, **WorkingSet**, and **PeakWorkingSet** properties. Another pipeline operator sends the filtered objects to the `Sort-Object` cmdlet to sort them in descending order by the value of the **WorkingSet** property. Then, the sorted results are piped to `Out-GridView`. You can now use the features of the grid view to search, sort, and filter the data. ### Example 4: Save output to a variable, and then output a grid view This example saves cmdlet output in a variable then sends it to `Out-GridView`. ```powershell ($A = Get-ChildItem -Path $PSHOME -Recurse) | Out-GridView ``` `Get-ChildItem` gets all the files in the PowerShell installation directory and its subdirectories using the `$PSHOME` automatic variable. The parentheses in the command establish the order of operations. As a result, the output from the `Get-ChildItem` command is saved in the `$A` variable before it is sent to `Out-GridView`. ### Example 5: Output processes for a specified computer to a grid view This example displays the processes that are running on the Server01 computer in a grid view window. ```powershell Get-Process -ComputerName "Server01" | ogv -Title "Processes - Server01" ``` The example uses `ogv`, which is the alias for the `Out-GridView` cmdlet. The **Title** parameter specifies the window title. ### Example 6: Output data from remote computers to a grid view This example shows how to send data collected from remote computers to `Out-GridView`. ```powershell Invoke-Command -ComputerName S1, S2, S3 -ScriptBlock {Get-Culture} | Out-GridView ``` `Invoke-Command` runs `Get-Culture` on three remote computers. The resulting data is piped to `Out-GridView`. Notice that the script block that runs on the remote computer does not include the `Out-GridView` command. If it did, the command would fail when it tried to open a grid view window on each of the remote computers. ### Example 7: Pass multiple items through `Out-GridView` This example lets you select multiple processes from the `Out-GridView` window. The processes that you select are passed to the `Export-Csv` command and written to the `ProcessLog.csv` file. ```powershell Get-Process | Out-GridView -PassThru | Export-Csv -Path .\ProcessLog.csv ``` The **PassThru** parameter of `Out-GridView` lets you send multiple items down the pipeline. The **PassThru** parameter is equivalent to using the **Multiple** value of the **OutputMode** parameter. ### Example 8: Create a Windows shortcut to `Out-GridView` This example shows how to use the **Wait** parameter of `Out-GridView` to create a Windows shortcut to the `Out-GridView` window. ```powershell pwsh -Command "Get-Service | Out-GridView -Wait" ``` This command line can be used in a Windows shortcut. Without the **Wait** parameter, PowerShell would exit as soon as the `Out-GridView` window opened, which would close the `Out-GridView` window almost immediately. ## PARAMETERS ### -InputObject Specifies object that the cmdlet accepts as input for `Out-GridView`. When you use the **InputObject** parameter to send a collection of objects to `Out-GridView`, `Out-GridView` treats the collection as one collection object, and it displays one row that represents the collection. To display the each object in the collection, use a pipeline operator (`|`) to send objects to `Out-GridView`. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -OutputMode Specifies the items that the interactive window sends down the pipeline as input to other commands. By default, this cmdlet does not generate any output. To send items from the interactive window down the pipeline, click to select the items and then click OK. The values of this parameter determine how many items you can send down the pipeline. - `None`. No items. This is the default value. - `Single`. Zero items or one item. Use this value when the next command can take only one input object. - `Multiple`. Zero, one, or many items. Use this value when the next command can take multiple input objects. This value is equivalent to the **PassThru** parameter. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: Microsoft.PowerShell.Commands.OutputModeOption Parameter Sets: OutputMode Aliases: Accepted values: None, Single, Multiple Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Indicates that the cmdlet sends items from the interactive window down the pipeline as input to other commands. By default, this cmdlet does not generate any output. This parameter is equivalent to using the **Multiple** value of the **OutputMode** parameter. To send items from the interactive window down the pipeline, click to select the items and then click OK. Shift-click and Ctrl-click are supported. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: PassThru Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Title Specifies the text that appears in the title bar of the `Out-GridView` window. By default, the title bar displays the command that invokes `Out-GridView`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Wait Indicates that the cmdlet suppresses the command prompt and prevents Windows PowerShell from closing until the `Out-GridView` window is closed. By default, the command prompt returns when the `Out-GridView` window opens. This feature lets you use the `Out-GridView` cmdlets in Windows shortcuts. When `Out-GridView` is used in a shortcut without the **Wait** parameter, the `Out-GridView` window appears only momentarily before PowerShell closes. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Wait Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSObject When you use the **PassThru** parameter, this cmdlet returns objects representing the selected rows. ## NOTES PowerShell includes the following aliases for `Out-GridView`: - Windows: - `ogv` This cmdlet is only available on Windows platforms. This cmdlet is only available on Windows platforms. You cannot use a remote command to open a grid view window on another computer. The command output that you send to `Out-GridView` cannot be formatted using the `Format` cmdlets, such as `Format-Table` or `Format-Wide` cmdlets. To select properties, use the `Select-Object` cmdlet. Deserialized output from remote commands might not be formatted correctly in the grid view window. **Keyboard Shortcuts for** `Out-GridView` | Use this key: | To perform this action: | | --------------------------------------- | -------------------------------------------------------------------------------------------- | | <kbd>Tab</kbd> | Moves the cursor from the **Filter** box to the **Add criteria** menu to the table and back. | | <kbd>UpArrow</kbd> | Move up one row. Moves to column headers from first row of data. | | <kbd>DownArrow</kbd> | Move down one row. | | <kbd>LeftArrow</kbd> | In column header row, move left one column. | | <kbd>RightArrow</kbd> | In column header row, move right one column. | | <kbd>ContextMenuKey</kbd> | In column header row, displays the Select Columns option. | | <kbd>Enter</kbd> or <kbd>Spacebar</kbd> | In column header row, sort column data (toggle A-Z, Z-A). | **How to Use the Grid View Window Features** **To hide or show a column:** 1. Right-click any column header and click **Select Columns**. 2. In the **Select Columns** dialog box, use the arrow keys to move the columns between the Selected columns to the Available columns boxes. Only columns in the **Select Columns** box appear in the grid view window. **To reorder columns:** You can drag and drop columns into the desired location. Or use the following steps: 1. Right-click any column header and click **Select Columns**. 2. In the **Select Columns** dialog box, use the **Move up** and **Move down** buttons to reorder the columns. Columns at the top of the list appear to the left of columns at the bottom of the list in the grid view window. **How to Sort Table Data** - To sort the data, click a column header. - To change the sort order, click the column header again. Each time you click the same header, the sort order toggles between ascending to descending order. The current order is indicated by a triangle in the column header. **How to Select Table Data** - To select a row, select the row or use the up or down arrow to navigate to the row. - To select all rows (except for the header row), press <kbd>CTRL</kbd>+<kbd>A</kbd>. - To select consecutive rows, press and hold the <kbd>SHIFT</kbd> key while clicking the rows or using the arrow keys. - To select nonconsecutive rows, press the <kbd>CTRL</kbd> key and click to add a row to the selection. - You cannot select columns, and you cannot select the entire column header row. **How to Copy Rows** - To copy one or more rows from the table, select the rows and then press CTRL+C. You can paste the data into any text or spreadsheet program. You cannot copy columns or parts of rows and you cannot copy the column header row. **How to Search in the Table (Quick Filter)** Use the Filter box to search for data in the table. When you type in the box, only items that include the typed text appear in the table. - Search for text. To search for text in the table, in the Filter box, type the text to find. - Search for multiple words. To search for multiple words in the table, type the words separated by spaces. `Out-GridView` displays rows that include all the words (logical **AND**). - Search for literal phrases. To search for phrases that include spaces or special characters, enclose the phrase in quotation marks. `Out-GridView` displays rows that include an exact match for the phrase. - Search in columns. To search for text in one or more columns, use the following format: `<column>:<text> [<column>:<text>] ...` For example, to find "Net" in the **DisplayName** column, in the **Filter** box, type: `displayname:net` To find rows with "Net" in the **DisplayName** and **Name** columns, in the **Filter** box, type: `displayname:net name:net` - Turn off search. To display the entire table again, click the red X button in the top right corner of the **Filter** box or delete the text from the **Filter** box. **Use Criteria to Filter the Table** You can use rules or criteria to determine which items are displayed in the table. Items appear only when they satisfy all the criteria that you establish. The available criteria are determined by the properties of the objects displayed in the grid view window and the .NET Framework types of those properties. Each criterion has the following format: `<column> <operator> <value>` Criteria for different properties are connected by **AND**. Criteria for the same property are connected by **OR**. You cannot change the logical connectors. The criteria only affects the display. It does not delete items from the table. **How to Add Criteria** 1. To display the **Add criteria** menu button, in the upper right corner of the window, click the Expand arrow. 2. Click the **Add Criteria** menu button. 3. Click to select columns (properties). You can select one or many properties. 4. When you are finished selecting properties, click the **Add** button. 5. To cancel the additions, click **Cancel**. 6. To add more criteria, click the **Add Criteria** button again. **How to Edit a Criterion** - To change an operator, click the blue operator value, and then select a different operator from the drop-down list. - To enter or change a value, type a value in the value box. If you enter a value that is not valid, a circular X icon appears. To remove it, change the value. - To create an **OR** statement, add a criteria with the same property. **How to Delete Criteria** - To delete selected criteria, click the red X beside each criterion. - To delete all criteria, click the **Clear All** button. ## RELATED LINKS [Out-File](Out-File.md) [Out-Printer](Out-Printer.md) [Out-String](Out-String.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Out-Printer.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/out-printer?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Out-Printer --- # Out-Printer ## SYNOPSIS Sends output to a printer. ## SYNTAX ``` Out-Printer [[-Name] <String>] [-InputObject <PSObject>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Out-Printer` cmdlet sends output to the default printer or to an alternate printer, if one is specified. Since the cmdlet doesn't have any way to configure the print job, the resulting print job uses the default settings defined for the printer. > [!NOTE] > This cmdlet was reintroduced in PowerShell 7. This cmdlet is only available on Windows systems > that support the Windows Desktop. ## EXAMPLES ### Example 1 - Send a file to be printed on the default printer This example shows how to print a file, even though `Out-Printer` does not have a **Path** parameter. ```powershell Get-Content -Path ./readme.txt | Out-Printer ``` `Get-Content`gets the contents of the `readme.txt` file in the current directory and pipes it to `Out-Printer`, which sends it to the default printer. ### Example 2: Print a string to a remote printer This example prints `Hello, World` to the **Prt-6B Color** printer on Server01. ```powershell "Hello, World" | Out-Printer -Name "\\Server01\Prt-6B Color" ``` The **Name** parameter selects a specific printer, rather than the default. ### Example 3 - Print a help topic to the default printer This example prints the full version of the Help topic for `Get-CimInstance`. ```powershell $H = Get-Help -Full Get-CimInstance Out-Printer -InputObject $H ``` `Get-Help` gets the full version of the Help topic for `Get-CimInstance` and stores it in the `$H` variable. The **InputObject** parameter passes the value of `$H` to `Out-Printer`. ## PARAMETERS ### -InputObject Specifies the objects to be sent to the printer. Enter a variable that contains the objects, or type a command or expression that gets the objects. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Sends the output to the specified printer. The parameter name **Name** is optional. ```yaml Type: System.String Parameter Sets: (All) Aliases: PrinterName Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES This cmdlet is only available on Windows platforms. The cmdlets that contain the `Out` verb do not format objects. They just render them and send them to the specified display destination. If you send an unformatted object to an `Out` cmdlet, the cmdlet sends it to a formatting cmdlet before rendering it. `Out-Printer` sends data to the printer, but does not emit any output objects to the pipeline. If you pipe the output of `Out-Printer` to `Get-Member`, `Get-Member` reports that no objects have been specified. ## RELATED LINKS [Out-File](Out-File.md) [Out-String](Out-String.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Out-String.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/out-string?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Out-String --- # Out-String ## SYNOPSIS Outputs input objects as a string. ## SYNTAX ### NoNewLineFormatting (Default) ``` Out-String [-Width <Int32>] [-NoNewline] [-InputObject <PSObject>] [<CommonParameters>] ``` ### StreamFormatting ``` Out-String [-Stream] [-Width <Int32>] [-InputObject <PSObject>] [<CommonParameters>] ``` ## DESCRIPTION The `Out-String` cmdlet converts input objects into strings. By default, `Out-String` accumulates the strings and returns them as a single string, but you can use the **Stream** parameter to direct `Out-String` to return one line at a time or create an array of strings. This cmdlet lets you search and manipulate string output as you would in traditional shells when object manipulation is less convenient. PowerShell also adds the `oss` function that calls `Out-String -Stream` as a shorthand way to use `Out-String` in a pipeline. ## EXAMPLES ### Example 1: Get the current culture and convert the data to strings This example gets the regional settings for the current user and converts the object data to strings. ```powershell $C = Get-Culture | Select-Object -Property * Out-String -InputObject $C -Width 100 ``` ```Output Parent : en LCID : 1033 KeyboardLayoutId : 1033 Name : en-US IetfLanguageTag : en-US DisplayName : English (United States) NativeName : English (United States) EnglishName : English (United States) TwoLetterISOLanguageName : en ThreeLetterISOLanguageName : eng ThreeLetterWindowsLanguageName : ENU CompareInfo : CompareInfo - en-US TextInfo : TextInfo - en-US IsNeutralCulture : False CultureTypes : SpecificCultures, InstalledWin32Cultures, FrameworkCultures NumberFormat : System.Globalization.NumberFormatInfo DateTimeFormat : System.Globalization.DateTimeFormatInfo Calendar : System.Globalization.GregorianCalendar OptionalCalendars : {System.Globalization.GregorianCalendar, System.Globalization.GregorianCalendar} UseUserOverride : True IsReadOnly : False ``` The `$C` variable stores a **Selected.System.Globalization.CultureInfo** object. The object is the result of `Get-Culture` sending output down the pipeline to `Select-Object`. The **Property** parameter uses an asterisk (`*`) wildcard to specify all properties are contained in the object. `Out-String` uses the **InputObject** parameter to specify the **CultureInfo** object stored in the `$C` variable. The objects in `$C` are converted to a string. > [!NOTE] > To view the `Out-String` array, store the output to a variable and use an array index to view the > elements. For more information about the array index, see > [about_Arrays](../microsoft.powershell.core/about/about_arrays.md). > > `$str = Out-String -InputObject $C -Width 100` ### Example 2: Working with objects This example demonstrates the difference between working with objects and working with strings. The command displays an alias that includes the text **gcm**, the alias for `Get-Command`. ```powershell Get-Alias | Out-String -Stream | Select-String -Pattern "gcm" ``` ```Output Alias gcm -> Get-Command ``` `Get-Alias` gets the **System.Management.Automation.AliasInfo** objects, one for each alias, and sends the objects down the pipeline. `Out-String` uses the **Stream** parameter to convert each object to a string rather than concatenating all the objects into a single string. The **System.String** objects are sent down the pipeline and `Select-String` uses the **Pattern** parameter to find matches for the text **gcm**. > [!NOTE] > If you omit the **Stream** parameter, the command displays all the aliases because `Select-String` > finds the text **gcm** in the single string that `Out-String` returns. ### Example 3: Use the Width parameter to prevent truncation While most output from `Out-String` is wrapped to the next line, there are scenarios where the output is truncated by the formatting system before being passed to `Out-String`. You can avoid truncation using the **Width** parameter. ```powershell PS> @{TestKey = ('x' * 200)} | Out-String Name Value ---- ----- TestKey xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx... PS> @{TestKey = ('x' * 200)} | Out-String -Width 250 Name Value ---- ----- TestKey xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ``` ## PARAMETERS ### -InputObject Specifies the objects to be written to a string. Enter a variable that contains the objects, or type a command or expression that gets the objects. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -NoNewline Removes all newlines from output generated by the PowerShell formatter. Newlines that are part of the string objects are preserved. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: NoNewLineFormatting Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Stream By default, `Out-String` outputs a single string formatted as you would see it in the console including any blank headers or trailing newlines. The **Stream** parameter enables `Out-String` to output each line one by one. The only exception to this are multiline strings. In that case, `Out-String` will still output the string as a single, multiline string. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: StreamFormatting Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Width Specifies the number of characters in each line of output. Any additional characters are wrapped to the next line or truncated depending on the formatter cmdlet used. The **Width** parameter applies only to objects that are being formatted. If you omit this parameter, the width is determined by the characteristics of the host program. In terminal (console) windows, the current window width is used as the default value. PowerShell console windows default to a width of 80 characters on installation. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns the string that it creates from the input object. ## NOTES The cmdlets that contain the `Out` verb don't format objects. The `Out` cmdlets send objects to the formatter for the specified display destination. PowerShell 7.2 added the ability to control how ANSI escape sequences are rendered. ANSI-decorated output that is passed to `Out-String` can be altered based on the setting of the `$PSStyle.OutputRendering` property. For more information, see [about_ANSI_Terminals](/powershell/module/microsoft.powershell.core/about/about_ansi_terminals). ## RELATED LINKS [about_Formatting](../Microsoft.PowerShell.Core/About/about_Format.ps1xml.md) [Out-Default](../Microsoft.PowerShell.Core/Out-Default.md) [Out-File](Out-File.md) [Out-Host](../Microsoft.PowerShell.Core/Out-Host.md) [Out-Null](../Microsoft.PowerShell.Core/Out-Null.md) [Out-GridView](Out-GridView.md) [Out-Printer](Out-Printer.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Read-Host.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 05/22/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/read-host?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Read-Host --- # Read-Host ## SYNOPSIS Reads a line of input from the console. ## SYNTAX ### AsString (Default) ``` Read-Host [[-Prompt] <Object>] [-MaskInput] [<CommonParameters>] ``` ### AsSecureString ``` Read-Host [[-Prompt] <Object>] [-AsSecureString] [<CommonParameters>] ``` ## DESCRIPTION The `Read-Host` cmdlet reads a line of input from the console (stdin). You can use it to prompt a user for input. Because you can save the input as a secure string, you can use this cmdlet to prompt users for secure data, such as passwords. > [!NOTE] > `Read-Host` has a limit of 1022 characters it can accept as input from a user. ## EXAMPLES ### Example 1: Save console input to a variable This example displays the string "Please enter your age:" as a prompt. When a value is entered and the Enter key is pressed, the value is stored in the `$Age` variable. ```powershell $Age = Read-Host "Please enter your age" ``` ### Example 2: Save console input as a secure string This example displays the string "Enter a Password:" as a prompt. As a value is being entered, asterisks (`*`) appear on the console in place of the input. When the Enter key is pressed, the value is stored as a **SecureString** object in the `$pwd_secure_string` variable. ```powershell $pwd_secure_string = Read-Host "Enter a Password" -AsSecureString ``` ### Example 3: Mask input and as a plaintext string This example displays the string "Enter a Password:" as a prompt. As a value is being entered, asterisks (`*`) appear on the console in place of the input. When the Enter key is pressed, the value is stored as a plaintext **String** object in the `$pwd_string` variable. ```powershell $pwd_string = Read-Host "Enter a Password" -MaskInput ``` ### Example 4: Normalizing input This example prompts the user to input a list of cities separated by semi-colons. It shows the string's value as typed by the user. In the example, the user added spaces between some of the entries. This could lead to an error later in the script where the code expects an exact name. The example shows how you can convert an input string into an array of entries without any extra spaces. ```powershell $prompt = @( 'List the cities you want weather information for.' 'When specifying multiple cities, separate them with a semi-colon, like:' "'New York; Osan; Koforidua'" ) -join ' ' $cities = Read-Host $prompt "Input cities string: `n`t'$cities'" $splitCities = $cities -split ';' "Split cities array:" $splitCities | ForEach-Object -Process { "`t'$_'" } $normalizedCities = $splitCities | ForEach-Object -Process { $_.Trim() } "Normalized split cities array:" $normalizedCities | ForEach-Object -Process { "`t'$_'" } ``` ```output Input cities string: ' New York; Osan ;Koforidua ' Split cities array: ' New York' ' Osan ' 'Koforidua ' Normalized split cities array: 'New York' 'Osan' 'Koforidua' ``` The example uses the `-split` operator to convert the input string into an array of strings. Each string in the array includes the name of a different city. However, the split strings include extra spaces. The `Trim()` method removes the leading and trailing spaces from each string. ## PARAMETERS ### -AsSecureString Indicates that the cmdlet displays asterisks (`*`) in place of the characters that the user types as input. When you use this parameter, the output of the `Read-Host` cmdlet is a **SecureString** object (**System.Security.SecureString**). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: AsSecureString Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaskInput Indicates that the cmdlet displays asterisks (`*`) in place of the characters that the user types as input. When you use this parameter, the output of the `Read-Host` cmdlet is a **String** object. This allows you to safely prompt for a password that is returned as plaintext instead of **SecureString**. This parameter was added in PowerShell 7.1. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: AsString Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Prompt Specifies the text of the prompt. Type a string. If the string includes spaces, enclose it in quotation marks. PowerShell appends a colon (`:`) to the text that you enter. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.String By default, this cmdlet returns a string. ### System.Security.SecureString When you use **AsSecureString** parameter, this cmdlet returns a **SecureString**. ## NOTES This cmdlet only reads from the stdin stream of the host process. Usually, the stdin stream is connected to the keyboard of the host console. ## RELATED LINKS [Clear-Host](../microsoft.powershell.core/clear-host.md) [Get-Host](Get-Host.md) [Write-Host](Write-Host.md) [ConvertFrom-SecureString](../Microsoft.PowerShell.Security/ConvertFrom-SecureString.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Register-EngineEvent.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/13/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/register-engineevent?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Register-EngineEvent --- # Register-EngineEvent ## SYNOPSIS Subscribes to events that are generated by the PowerShell engine and by the `New-Event` cmdlet. ## SYNTAX ``` Register-EngineEvent [-SourceIdentifier] <String> [[-Action] <ScriptBlock>] [-MessageData <PSObject>] [-SupportEvent] [-Forward] [-MaxTriggerCount <Int32>] [<CommonParameters>] ``` ## DESCRIPTION The `Register-EngineEvent` cmdlet subscribes to events that are generated by the PowerShell engine and the `New-Event` cmdlet. Use the **SourceIdentifier** parameter to specify the event. You can use this cmdlet to subscribe to the **OnIdle** or **Exiting** engine events and events generated by the `New-Event` cmdlet. These events are automatically added to the event queue in your session without subscribing. However, subscribing lets you forward the events, specify an action to respond to the events, and cancel the subscription. When you subscribe to an event, an event subscriber is added to your session. To get the event subscribers in the session, use the `Get-EventSubscriber` cmdlet. To cancel the subscription, use the `Unregister-Event` cmdlet, which deletes the event subscriber from the session. When the subscribed event is raised, it is added to the event queue in your session. To get events in the event queue, use the `Get-Event` cmdlet. ## EXAMPLES ### Example 1: Register a PowerShell engine event on remote computers This example registers for a PowerShell engine event on two remote computers. ```powershell $S = New-PSSession -ComputerName "Server01, Server02" Invoke-Command -Session $S { Register-EngineEvent -SourceIdentifier ([System.Management.Automation.PSEngineEvent]::Exiting) -Forward } ``` `New-PSSession` creates a user-managed session (PSSession) on each of the remote computers.The `Invoke-Command` cmdlet runs the `Register-EngineEvent` command in the remote sessions. `Register-EngineEvent` uses the **SourceIdentifier** parameter to identify the event. The **Forward** parameter tell the engine to forward the events from the remote session to the local session. ### Example 2: Take a specified action when the Exiting event occurs This example shows how to run `Register-EngineEvent` to take a specific action when the **PowerShell.Exiting** event occurs. ```powershell Register-EngineEvent -SourceIdentifier PowerShell.Exiting -SupportEvent -Action { Get-History | Export-Clixml $HOME\history.clixml } ``` The **SupportEvent** parameter is added to hide the event subscription. When PowerShell exits, in this case, the command history from the exiting session is exported an XML file in the user's `$HOME` directory. ### Example 3: Create and subscribe to a user-defined event This example creates a subscription for events from the source **MyEventSource**. This is an arbitrary source that we are going to use to monitor the progress of a job. `Register-EngineEvent` is used to create the subscription. The script block for the **Action** parameter logs the event data to a text file. ```powershell Register-EngineEvent -SourceIdentifier MyEventSource -Action { "Event: {0}" -f $Event.MessageData | Out-File C:\temp\MyEvents.txt -Append } Start-Job -Name TestJob -ScriptBlock { while ($true) { Register-EngineEvent -SourceIdentifier MyEventSource -Forward Start-Sleep -Seconds 2 "Doing some work..." $newEventSplat = @{ SourceIdentifier = 'MyEventSource' MessageData = ("{0} - Work done..." -f (Get-Date)) } New-Event @newEventSplat } } Start-Sleep -Seconds 4 Get-EventSubscriber Get-Job ``` ```Output SubscriptionId : 12 SourceObject : EventName : SourceIdentifier : MyEventSource Action : System.Management.Automation.PSEventJob HandlerDelegate : SupportEvent : False ForwardEvent : False Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 18 MyEventSource Running True … 19 TestJob BackgroundJob Running True localhost … ``` `Register-EngineEvent` created Job Id 18. `Start-Job` created Job Id 19. In Example #4, we remove the event subscription and the jobs, then inspect the log file. ### Example 4: Unregister events and clean up jobs This is a continuation of Example 3. In this example we wait for 10 seconds to let several events occur. Then we unregister the event subscription. ```powershell PS> Start-Sleep -Seconds 10 PS> Get-EventSubscriber | Unregister-Event PS> Get-Job Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 18 MyEventSource Stopped False 19 TestJob BackgroundJob Running True localhost PS> Stop-Job -Id 19 PS> Get-Job | Remove-Job PS> Get-Content C:\temp\MyEvents.txt Event: 2/18/2020 2:36:19 PM - Work done... Event: 2/18/2020 2:36:21 PM - Work done... Event: 2/18/2020 2:36:23 PM - Work done... Event: 2/18/2020 2:36:25 PM - Work done... Event: 2/18/2020 2:36:27 PM - Work done... Event: 2/18/2020 2:36:29 PM - Work done... Event: 2/18/2020 2:36:31 PM - Work done... ``` The `Unregister-Event` cmdlet stops the job associated with the event subscription (Job Id 18). Job Id 19 is still running and creating new events. We use the **Job** cmdlets stop the job and remove the unneeded job objects. `Get-Content` displays the contents of the log file. ## PARAMETERS ### -Action Specifies commands to handle the events. The commands in the **Action** run when an event is raised, instead of sending the event to the event queue. Enclose the commands in braces (`{}`) to create a script block. The value of the **Action** parameter can include the `$Event`, `$EventSubscriber`, `$Sender`, `$EventArgs`, and `$args` automatic variables, which provide information about the event to the **Action** script block. For more information, see [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md). When you specify an action, `Register-EngineEvent` returns an event job object that represents that action. You can use the Job cmdlets to manage the event job. ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: (All) Aliases: Required: False Position: 101 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Forward Indicates that the cmdlet sends events for this subscription to the session on the local computer. Use this parameter when you are registering for events on a remote computer or in a remote session. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaxTriggerCount Specifies the maximum number of times that the action is executed for the event subscription. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MessageData This parameter is part of the base class for all Event cmdlets. The `Register-EngineEvent` doesn't use this parameter. Any data passed to this parameter is ignored. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SourceIdentifier Specifies the source identifier of the event to which you are subscribing. The source identifier must be unique in the current session. This parameter is required. The value of this parameter appears in the value of the **SourceIdentifier** property of the subscriber object and of all event objects associated with this subscription. The value is specific to the source of the event. This can be an arbitrary value you created to use with the `New-Event` cmdlet. The PowerShell engine supports the **PSEngineEvent** values **PowerShell.Exiting** and **PowerShell.OnIdle**. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 100 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SupportEvent Indicates that the cmdlet hides the event subscription. Add this parameter when the current subscription is part of a more complex event registration mechanism and it should not be discovered independently. To view or cancel a subscription that was created with the **SupportEvent** parameter, add the **Force** parameter to the `Get-EventSubscriber` or `Unregister-Event` cmdlets. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSEventJob When you use the **Action** parameter, this cmdlet returns a **PSEventJob** object. ## NOTES Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled. When subscribing to the **Exiting** event, the cmdlets that can be executed by the **Action** parameter are limited to the cmdlets in the **Microsoft.PowerShell.Core** and **Microsoft.PowerShell.Utility** modules. The **Exiting** event is only fired when the session is exited under the control of PowerShell. The event is not fired when the host application or terminal window is closed. The engine is considered to be idle if it is not running a pipeline. The **OnIdle** event is fired when PowerShell has been idle for 300 milliseconds (ms). > [!NOTE] > When PSReadLine is in use, the **OnIdle** event is fired when `ReadKey()` times out (no typing in > 300ms). The event could be signaled while the user is in the middle of editing a command line, for > example, the user is reading help to decide which parameter to use. Beginning in PSReadLine > 2.2.0-beta4, **OnIdle** behavior changed to signal the event only if there is a `ReadKey()` > timeout and the current editing buffer is empty. ## RELATED LINKS [Get-Event](Get-Event.md) [New-Event](New-Event.md) [Register-ObjectEvent](Register-ObjectEvent.md) [Remove-Event](Remove-Event.md) [Unregister-Event](Unregister-Event.md) [Wait-Event](Wait-Event.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Register-ObjectEvent.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/register-objectevent?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Register-ObjectEvent --- # Register-ObjectEvent ## SYNOPSIS Subscribes to the events that are generated by a Microsoft .NET Framework object. ## SYNTAX ``` Register-ObjectEvent [-InputObject] <PSObject> [-EventName] <String> [[-SourceIdentifier] <String>] [[-Action] <ScriptBlock>] [-MessageData <PSObject>] [-SupportEvent] [-Forward] [-MaxTriggerCount <Int32>] [<CommonParameters>] ``` ## DESCRIPTION The `Register-ObjectEvent` cmdlet subscribes to events that are generated by .NET objects on the local computer or on a remote computer. When the subscribed event is raised, it is added to the event queue in your session. To get events in the event queue, use the `Get-Event` cmdlet. You can use the parameters of `Register-ObjectEvent` to specify property values of the events that can help you to identify the event in the queue. You can also use the **Action** parameter to specify actions to take when a subscribed event is raised and the **Forward** parameter to send remote events to the event queue in the local session. When you subscribe to an event, an event subscriber is added to your session. To get the event subscribers in the session, use the `Get-EventSubscriber` cmdlet. To cancel the subscription, use the `Unregister-Event` cmdlet, which deletes the event subscriber from the session. ## EXAMPLES ### Example 1: Subscribe to events when a new process starts This example subscribes to events generated when a new process starts. The command uses the **ManagementEventWatcher** object to get **EventArrived** events. A query object specifies that the events are instance creation events for the **Win32_Process** class. ```powershell $queryParameters = '__InstanceCreationEvent', (New-Object TimeSpan 0,0,1), "TargetInstance isa 'Win32_Process'" $Query = New-Object System.Management.WqlEventQuery -ArgumentList $queryParameters $ProcessWatcher = New-Object System.Management.ManagementEventWatcher $Query Register-ObjectEvent -InputObject $ProcessWatcher -EventName "EventArrived" ``` ### Example 2: Specify an action to respond to an event When you specify an action, events that are raised are not added to the event queue. Instead, the action responds to the event. In this example, when an instance creation event is raised indicating that a new process is started, a new **ProcessCreated** event is raised. ```powershell $queryParameters = '__InstanceCreationEvent', (New-Object TimeSpan 0,0,1), "TargetInstance isa 'Win32_Process'" $Query = New-Object System.Management.WqlEventQuery -ArgumentList $queryParameters $ProcessWatcher = New-Object System.Management.ManagementEventWatcher $query $newEventArgs = @{ SourceIdentifier = 'PowerShell.ProcessCreated' Sender = $Sender EventArguments = $EventArgs.NewEvent.TargetInstance } $Action = { New-Event @newEventArgs } Register-ObjectEvent -InputObject $ProcessWatcher -EventName "EventArrived" -Action $Action ``` ```Output Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 5 3db2d67a-efff-... NotStarted False New-Event @newEventArgs ``` The action uses the `$Sender` and `$EventArgs` automatic variables which are populated only for event actions. The `Register-ObjectEvent` command returns a job object that represents the action, which runs as a background job. You can use the Job cmdlets, such as `Get-Job` and `Receive-Job`, to manage the background job. For more information, see [about_Jobs](../Microsoft.PowerShell.Core/About/about_Jobs.md). ### Example 3: Subscribe to object events on remote computers This example shows how to subscribe to object events on remote computers. This example uses the `Enable-ProcessCreationEvent` function that is defined in the `ProcessCreationEvent.ps1` script file. This script is available to all computers in the example. ```powershell # ProcessCreationEvent.ps1 function Enable-ProcessCreationEvent { $queryParameters = "__InstanceCreationEvent", (New-Object TimeSpan 0,0,1), "TargetInstance isa 'Win32_Process'" $Query = New-Object System.Management.WqlEventQuery -ArgumentList $queryParameters $objectEventArgs = @{ Input = New-Object System.Management.ManagementEventWatcher $Query EventName = 'EventArrived' SourceIdentifier = 'WMI.ProcessCreated' MessageData = 'Test' Forward = $true } Register-ObjectEvent @objectEventArgs } $S = New-PSSession -ComputerName "Server01, Server02" Invoke-Command -Session $S -FilePath ProcessCreationEvent.ps1 Invoke-Command -Session $S { Enable-ProcessCreationEvent } ``` The first we create **PSSessions** on two remote computers and save them in the `$S` variable. Next, the `Invoke-Command` cmdlet run the `ProcessCreationEvent.ps1` script in the each of the PSSessions in `$S`. This action creates the `Enable-ProcessCreationEvent` function in the remote sessions. Finally, we run the `Enable-ProcessCreationEvent` function in the remote sessions. The function includes a `Register-ObjectEvent` command that subscribes to instance creation events on the **Win32_Process** object through the **ManagementEventWatcher** object and its **EventArrived** event. ### Example 4: Use the dynamic module in the PSEventJob object This example shows how to use the dynamic module in the **PSEventJob** object that is created when you include an **Action** in an event registration. First we create and and enable a timer object, then set the interval of the timer to 500 (milliseconds). The `Register-ObjectEvent` cmdlet registers the **Elapsed** event of the timer object. The **PSEventJob** object is saved in the `$Job` variable and is also available in the **Action** property of the event subscriber. For more information, see [Get-EventSubscriber](Get-EventSubscriber.md). Whenever the timer interval elapses, an event is raised and the action is executed. In this case, the `Get-Random` cmdlet generates a random number between 0 and 100 and saves it in the `$Random` variable. ```powershell $Timer = New-Object Timers.Timer $Timer.Interval = 500 $Timer.Enabled = $true $objectEventArgs = @{ InputObject = $Timer EventName = 'Elapsed' SourceIdentifier = 'Timer.Random' Action = {$Random = Get-Random -Min 0 -Max 100} } $Job = Register-ObjectEvent @objectEventArgs $Job | Format-List -Property * & $Job.Module {$Random} & $Job.Module {$Random} ``` ```Output State : Running Module : __DynamicModule_53113769-31f2-42dc-830b-8749325e28d6 StatusMessage : HasMoreData : True Location : Command : $Random = Get-Random -Min 0 -Max 100 JobStateInfo : Running Finished : System.Threading.ManualResetEvent InstanceId : 47b5ec9f-bfe3-4605-860a-4674e5d44ca8 Id : 7 Name : Timer.Random ChildJobs : {} PSBeginTime : 6/27/2019 10:19:06 AM PSEndTime : PSJobTypeName : Output : {} Error : {} Progress : {} Verbose : {} Debug : {} Warning : {} Information : {} 60 47 ``` The **PSEventJob** has a **Module** property that contains a dynamic script module that implements the action. Using the call operator (`&`), we invoke the command in the module to display the value of the `$Random` variable. For more information about modules, see [about_Modules](../Microsoft.PowerShell.Core/About/about_Modules.md). ## PARAMETERS ### -Action Specifies the commands to handle the event. The commands in the **Action** run when an event is raised, instead of sending the event to the event queue. Enclose the commands in braces ( { } ) to create a script block. The value of the **Action** parameter can include the `$Event`, `$EventSubscriber`, `$Sender`, `$EventArgs`, and `$args` automatic variables. These variables provide information about the event to the **Action** script block. For more information, see [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md). When you specify an action, `Register-ObjectEvent` returns an event job object that represents that action. You can use the Job cmdlets to manage the event job. ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: (All) Aliases: Required: False Position: 101 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -EventName Specifies the event to which you are subscribing. The value of this parameter must be the name of the event that the .NET object exposes. For example, the **ManagementEventWatcher** class has events named **EventArrived** and **Stopped**. To find the event name of an event, use the `Get-Member` cmdlet. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Forward Indicates that the cmdlet sends events for this subscription to a remote session. Use this parameter when you are registering for events on a remote computer or in a remote session. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the .NET object that generates the events. Enter a variable that contains the object, or type a command or expression that gets the object. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaxTriggerCount Specifies the maximum number of times an event can be triggered. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MessageData Specifies any additional data to be associated with this event subscription. The value of this parameter appears in the MessageData property of all events associated with this subscription. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SourceIdentifier Specifies a name that you select for the subscription. The name that you select must be unique in the current session. The default value is the GUID that PowerShell assigns. The value of this parameter appears in the value of the **SourceIdentifier** property of the subscriber object and all event objects associated with this subscription. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 100 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SupportEvent Indicates that the cmdlet hides the event subscription. Use this parameter when the current subscription is part of a more complex event registration mechanism and should not be discovered independently. To view or cancel a subscription that was created with the **SupportEvent** parameter, use the **Force** parameter of the `Get-EventSubscriber` and `Unregister-Event` cmdlets. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSEventJob When you use the **Action** parameter, this cmdlet returns a **PSEventJob** object. ## NOTES Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled. ## RELATED LINKS [Get-Event](Get-Event.md) [New-Event](New-Event.md) [Register-EngineEvent](Register-EngineEvent.md) [Remove-Event](Remove-Event.md) [Unregister-Event](Unregister-Event.md) [Wait-Event](Wait-Event.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Remove-Alias.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 03/07/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/remove-alias?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-Alias --- # Remove-Alias ## SYNOPSIS Remove an alias from the current session. ## SYNTAX ### Default (Default) ``` Remove-Alias [-Name] <String[]> [-Scope <String>] [-Force] [<CommonParameters>] ``` ## DESCRIPTION The `Remove-Alias` cmdlet removes an alias from the current PowerShell session. To remove an alias with the **Option** property set to **ReadOnly**, use the **Force** parameter. The `Remove-Alias` cmdlet was introduced in PowerShell 6.0. ## EXAMPLES ### Example 1 - Remove an alias This example removes an alias named `del` that represents the `Remove-Item` cmdlet. ```powershell Remove-Alias -Name del ``` ### Example 2 - Remove all non-Constant aliases This example removes all aliases from the current PowerShell session, except for aliases with the **Options** property set to **Constant**. After the command is run, the aliases are available in other PowerShell sessions or new PowerShell sessions. ```powershell Get-Alias | Where-Object { $_.Options -ne "Constant" } | Remove-Alias -Force ``` `Get-Alias` gets all the aliases in the PowerShell session and sends the objects down the pipeline. `Where-Object` uses a script block, and the automatic variable (`$_`) and **Options** property represent the current pipeline object. The `-ne` (not equal) operator selects objects that don't have an **Options** value set to **Constant**. `Remove-Alias` uses the **Force** parameter to remove aliases, including read-only aliases, from the PowerShell session. The **Force** parameter can't remove **Constant** aliases. ## PARAMETERS ### -Force Indicates that the cmdlet removes an alias, including aliases with the **Option** property set to **ReadOnly**. The **Force** parameter can't remove an alias with an **Option** property set to **Constant**. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies the name of the alias to remove. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Scope Affects only the aliases in the specified scope. The default scope is **Local**. For more information, see [about_Scopes](../microsoft.powershell.core/about/about_scopes.md). The acceptable values for this parameter are: - `Global` - `Local` - `Script` - A number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent) ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Local Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String[] You can pipe an alias object to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES Changes only affect the current scope. To remove an alias from all sessions, add a `Remove-Alias` command to your PowerShell profile. For more information, see [about_Aliases](../microsoft.powershell.core/about/about_aliases.md). ## RELATED LINKS [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md) [Export-Alias](Export-Alias.md) [Get-Alias](Get-Alias.md) [Import-Alias](Import-Alias.md) [New-Alias](New-Alias.md) [Set-Alias](Set-Alias.md) [Where-Object](../Microsoft.PowerShell.Core/Where-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Remove-Event.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/remove-event?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-Event --- # Remove-Event ## SYNOPSIS Deletes events from the event queue. ## SYNTAX ### BySource (Default) ``` Remove-Event [-SourceIdentifier] <String> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ByIdentifier ``` Remove-Event [-EventIdentifier] <Int32> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Remove-Event` cmdlet deletes events from the event queue in the current session. This cmdlet deletes only the events currently in the queue. To cancel event registrations or unsubscribe, use the `Unregister-Event` cmdlet. ## EXAMPLES ### Example 1: Remove an event by source identifier ``` PS C:\> Remove-Event -SourceIdentifier "ProcessStarted" ``` This command deletes events with a source identifier of Process Started from the event queue. ### Example 2: Remove an event by event identifier ``` PS C:\> Remove-Event -EventIdentifier 30 ``` This command deletes the event with an event ID of 30 from the event queue. ### Example 3: Remove all events ``` PS C:\> Get-Event | Remove-Event ``` This command deletes all events from the event queue. ## PARAMETERS ### -EventIdentifier Specifies the event identifier for which the cmdlet deletes. An **EventIdentifier** or **SourceIdentifier** parameter is required in every command. ```yaml Type: System.Int32 Parameter Sets: ByIdentifier Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -SourceIdentifier Specifies the source identifier for which this cmdlet deletes events from. Wildcards are not permitted. An **EventIdentifier** or **SourceIdentifier** parameter is required in every command. ```yaml Type: System.String Parameter Sets: BySource Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSEventArgs You can pipe events from `Get-Event` to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES No event sources available on the Linux or macOS platforms. Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled. ## RELATED LINKS [Get-Event](Get-Event.md) [New-Event](New-Event.md) [Register-EngineEvent](Register-EngineEvent.md) [Register-ObjectEvent](Register-ObjectEvent.md) [Remove-Event](Remove-Event.md) [Unregister-Event](Unregister-Event.md) [Wait-Event](Wait-Event.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Remove-PSBreakpoint.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/20/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/remove-psbreakpoint?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-PSBreakpoint --- # Remove-PSBreakpoint ## SYNOPSIS Deletes breakpoints from the current console. ## SYNTAX ### Breakpoint (Default) ``` Remove-PSBreakpoint [-Breakpoint] <Breakpoint[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Id ``` Remove-PSBreakpoint [-Id] <Int32[]> [-Runspace <Runspace>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Remove-PSBreakpoint` cmdlet deletes a breakpoint. Enter a breakpoint object or a breakpoint ID. When you remove a breakpoint, the breakpoint object is no longer available or functional. If you have saved a breakpoint object in a variable, the reference still exists, but the breakpoint does not function. `Remove-PSBreakpoint` is one of several cmdlets designed for debugging PowerShell scripts. For more information about the PowerShell debugger, see [about_Debuggers](../microsoft.powershell.core/about/about_debuggers.md). ## EXAMPLES ### Example 1: Remove all breakpoints This command deletes all of the breakpoints in the current console. ```powershell Get-PSBreakpoint | Remove-PSBreakpoint ``` ### Example 2: Remove a specified breakpoint This command deletes a breakpoint. ```powershell $B = Set-PSBreakpoint -Script "sample.ps1" -Variable "Name" $B | Remove-PSBreakpoint ``` The `Set-PSBreakpoint` cmdlet creates a breakpoint on the `$Name` variable in the `Sample.ps1` script and saves the breakpoint object in the `$B` variable. The `Remove-PSBreakpoint` cmdlet deletes the new breakpoint. It uses a pipeline operator (`|`) to send the breakpoint object in the `$B` variable to the `Remove-PSBreakpoint` cmdlet. As a result of this command, if you run the script, it runs to completion without stopping. Also, the `Get-PSBreakpoint` cmdlet does not return this breakpoint. ### Example 3: Remove a breakpoint by ID This command deletes the breakpoint with breakpoint ID 2. ```powershell Remove-PSBreakpoint -Id 2 ``` ### Example 4: Use a function to remove all breakpoints This simple function deletes all the breakpoints in the current session. ```powershell function del-psb { Get-PSBreakpoint | Remove-PSBreakpoint } ``` It uses the `Get-PSBreakpoint` cmdlet to get the breakpoints. Then, it uses a pipeline operator (`|`) to send the breakpoints to the `Remove-PSBreakpoint` cmdlet, which deletes them. ### Example 5: Remove a breakpoint in a runspace In this example, a job is started and a breakpoint is set to break when the `Set-PSBreakpoint` is run. The runspace is stored in a variable and passed to the `Get-PSBreakpoint` command with the **Runspace** parameter. The output of `Get-PSBreakpoint` is piped to `Remove-PSBreakpoint` to remove the breakpoint in the runspace. ```powershell Start-Job -ScriptBlock { Set-PSBreakpoint -Command Start-Sleep Start-Sleep -Seconds 10 } $runspace = Get-Runspace -Id 1 Get-PSBreakpoint -Runspace $runspace | Remove-Breakpoint -Runspace $runspace ``` ## PARAMETERS ### -Breakpoint Specifies the breakpoints to delete. Enter a variable that contains breakpoint objects or a command that gets breakpoint objects, such as a `Get-PSBreakpoint` command. You can also pipe breakpoint objects to `Remove-PSBreakpoint`. ```yaml Type: System.Management.Automation.Breakpoint[] Parameter Sets: Breakpoint Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Id Specifies breakpoint IDs for which this cmdlet deletes breakpoints. ```yaml Type: System.Int32[] Parameter Sets: Id Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Runspace Specifies the Id of a **Runspace** object so you can interact with breakpoints in the specified runspace. This parameter was added in PowerShell 7.2. ```yaml Type: Runspace Parameter Sets: Id Aliases: RunspaceId Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.Breakpoint[] You can pipe breakpoint objects to this cmdlet. ### System.Int32[] ### System.Management.Automation.Runspaces.Runspace ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Remove-PSBreakpoint`: - All platforms: - `rbp` ## RELATED LINKS [Disable-PSBreakpoint](Disable-PSBreakpoint.md) [Enable-PSBreakpoint](Enable-PSBreakpoint.md) [Get-PSBreakpoint](Get-PSBreakpoint.md) [Get-PSCallStack](Get-PSCallStack.md) [Set-PSBreakpoint](Set-PSBreakpoint.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Remove-TypeData.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/remove-typedata?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-TypeData --- # Remove-TypeData ## SYNOPSIS Deletes extended types from the current session. ## SYNTAX ### RemoveTypeDataSet (Default) ``` Remove-TypeData -TypeData <TypeData> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### RemoveTypeSet ``` Remove-TypeData [-TypeName] <String> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### RemoveFileSet ``` Remove-TypeData -Path <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Remove-TypeData` cmdlet deletes extended type data from the current session. This cmdlet affects only the current session and sessions that are created in the current session. You can add properties and methods to objects in PowerShell by defining them in `Update-TypeData` commands and `Types.ps1xml` files. `Remove-TypeData` deletes those extended properties and methods from the current session. `Remove-TypeData` does not delete the `Types.ps1xml` files or delete any extended type definitions from the `Types.ps1xml` files. For more information about `Types.ps1xml` files, see [about_Types.ps1xml](../Microsoft.PowerShell.Core/about/about_Types.ps1xml.md). This cmdlet was introduced in Windows PowerShell 3.0. ## EXAMPLES ### Example 1: Remove type data for a specified type This example deletes all type data for the **System.Array** type from the session, including type data that was added by a `Types.ps1xml` file and dynamic type data that was added to the session by using the `Update-TypeData` cmdlet. ```powershell Remove-TypeData -TypeName System.Array ``` ### Example 2: Remove an extended data type from a session This example shows the effect of removing extended type data from a session. The first `Get-TypeData` gets extended type data for the **System.DateTime** type. The output shows that a **DateTime** property has been added to all **System.DateTime** objects in PowerShell. The `Get-Date` cmdlet returns a **System.DateTime** object. The command uses dot notation to get the value of the **DateTime** property of the **System.DateTime** object that `Get-Date` returns. ```powershell Get-TypeData System.DateTime (Get-Date).DateTime Get-TypeData System.DateTime | Remove-TypeData (Get-Date).DateTime ``` ```Output TypeName Members -------- ------- System.DateTime {[DateTime, System.Management.Automation.Runspaces.ScriptPropertyData]} Friday, January 20, 2012 9:01:00 PM ``` The next `Get-TypeData` cmdlet to get all extended type data for the **System.DateTime** type and pipes that to the `Remove-TypeData` cmdlet to delete the extended type data. The last `Get-Date` cmdlet shows the effect of deleting the extended type data for the **System.DateTime** type. Because the **System.DateTime** property no longer exists, a command to get its value returns nothing. ### Example 3: Remove extended types for modules This example removes all extended type data for module objects. When you pipe an object to `Remove-TypeData`, `Remove-TypeData` gets the name of the object type and removes all type data for all objects of that type. ```powershell Get-Module | Remove-TypeData ``` ### Example 4: Remove extended types from specified modules This example uses the **Path** parameter of the `Remove-TypeData` cmdlet to remove the extended types that are defined in the `Types.ps1xml` files that are added by the **PSScheduledJob** and **PSWorkflow** modules. This command does not affect dynamic type data that is added by using the `Update-TypeData` cmdlet. The command succeeds only when the modules have been imported into the current session. ```powershell Remove-TypeData -Path "$PSHOME\Modules\PSScheduledJob", "$PSHOME\Modules\PSWorkflow\PSWorkflow.types.ps1xml" ``` For more information about modules, see [about_Modules](../Microsoft.PowerShell.Core/About/about_Modules.md). ### Example 5: Remove extended types from a remote session This example removes extended types from a remote session. The command uses the `Invoke-Command` cmdlet to remove extended type data for all CIM types in the sessions in the `$S` variable. ```powershell Invoke-Command -Session $S {Get-TypeData -TypeName *CIM* | Remove-TypeData} ``` ## PARAMETERS ### -Path Specifies an array of files that this cmdlet deletes from the session extended type data. This parameter is required. Enter the paths and file names of one or more `Types.ps1xml` files. Wildcards are not supported. If you omit the path, the default location is the current directory. ```yaml Type: System.String[] Parameter Sets: RemoveFileSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TypeData Specifies the type data that this cmdlet deletes from the session. This parameter is required. Enter a variable that contains **TypeData** objects (**System.Management.Automation.Runspaces.TypeData**) or a command that gets **TypeData** objects, such as a `Get-TypeData` command. You can also pipe **TypeData** objects to `Remove-TypeData`. ```yaml Type: System.Management.Automation.Runspaces.TypeData Parameter Sets: RemoveTypeDataSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -TypeName Specifies the types that this cmdlet deletes all extended type data for. For types in the System namespace, enter the short name. Otherwise, the full type name is required. Wildcards are not supported. You can pipe type names to `Remove-TypeData`. When you pipe an object to `Remove-TypeData`, `Remove-TypeData` gets the type name of the object and removes all type data for the object type. ```yaml Type: System.String Parameter Sets: RemoveTypeSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.Runspaces.TypeData You can pipe a **TypeData** object, such as the ones that the `Get-TypeData` cmdlet returns, to this cmdlet. ### System.String You can pipe a string containing the type name to this cmdlet. When you pipe an object to this cmdlet, it gets the type name of the object and removes all type data for the object type. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES `Remove-TypeData` can remove only the extended type data in the current session. It cannot remove extended type data that is on the computer, but has not been added to the current session, such as extended types that are defined in modules that have not been imported into the current session. ## RELATED LINKS [Get-TypeData](Get-TypeData.md) [Update-TypeData](Update-TypeData.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Remove-Variable.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/remove-variable?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-Variable --- # Remove-Variable ## SYNOPSIS Deletes a variable and its value. ## SYNTAX ``` Remove-Variable [-Name] <String[]> [-Include <String[]>] [-Exclude <String[]>] [-Force] [-Scope <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Remove-Variable` cmdlet deletes a variable and its value from the scope in which it is defined, such as the current session. You cannot use this cmdlet to delete variables that are set as constants or those that are owned by the system. ## EXAMPLES ### Example 1: Remove a variable ```powershell Remove-Variable Smp ``` This command deletes the `$Smp` variable. ## PARAMETERS ### -Exclude Specifies an array of items that this cmdlet omits from the operation. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as "s*". Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Indicates that the cmdlet removes a variable even if it is read-only. Even using the **Force** parameter, the cmdlet cannot remove a constant. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies an array of items that this cmdlet deletes in the operation. The value of this parameter qualifies the **Name** parameter. Enter a name element or pattern, such as s*. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Name Specifies the name of the variable to be removed. The parameter name (**Name**) is optional. Wildcards are permitted ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Scope Gets only the variables in the specified scope. The acceptable values for this parameter are: - Global - Local - Script - A number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent) Local is the default. For more information, see [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSVariable You can pipe a variable object to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Remove-Variable`: - All platforms: - `rv` - Changes affect only the current scope, such as a session. To delete a variable from all sessions, add a `Remove-Variable` command to your PowerShell profile. ## RELATED LINKS [Clear-Variable](Clear-Variable.md) [Get-Variable](Get-Variable.md) [New-Variable](New-Variable.md) [Set-Variable](Set-Variable.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Select-Object.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 06/19/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/select-object?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Select-Object --- # Select-Object ## SYNOPSIS Selects objects or object properties. ## SYNTAX ### DefaultParameter (Default) ``` Select-Object [-InputObject <PSObject>] [[-Property] <Object[]>] [-ExcludeProperty <String[]>] [-ExpandProperty <String>] [-Unique] [-CaseInsensitive] [-Last <Int32>] [-First <Int32>] [-Skip <Int32>] [-Wait] [<CommonParameters>] ``` ### SkipLastParameter ``` Select-Object [-InputObject <PSObject>] [[-Property] <Object[]>] [-ExcludeProperty <String[]>] [-ExpandProperty <String>] [-Unique] [-CaseInsensitive] [-Skip <Int32>] [-SkipLast <Int32>] [<CommonParameters>] ``` ### IndexParameter ``` Select-Object [-InputObject <PSObject>] [-Unique] [-CaseInsensitive] [-Wait] [-Index <Int32[]>] [<CommonParameters>] ``` ### SkipIndexParameter ``` Select-Object [-InputObject <PSObject>] [-Unique] [-CaseInsensitive] [-SkipIndex <Int32[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Select-Object` cmdlet selects specified properties of an object or set of objects. It can also select unique objects, a specified number of objects, or objects in a specified position in an array. To select objects from a collection, use the **First**, **Last**, **Unique**, **Skip**, and **Index** parameters. To select object properties, use the **Property** parameter. When you select properties, `Select-Object` returns new objects that have only the specified properties. Beginning in Windows PowerShell 3.0, `Select-Object` includes an optimization feature that prevents commands from creating and processing objects that aren't used. When you use `Select-Object` with the **First** or **Index** parameters in a command pipeline, PowerShell stops the command that generates the objects as soon as the selected number of objects is reached. To turn off this optimizing behavior, use the **Wait** parameter. ## EXAMPLES ### Example 1: Select objects by property This example creates objects that have the **Name**, **Id**, and working set (**WS**) properties of process objects. ```powershell Get-Process | Select-Object -Property ProcessName, Id, WS ``` ### Example 2: Select objects by property and format the results This example gets information about the modules used by the processes on the computer. It uses `Get-Process` cmdlet to get the process on the computer. It uses the `Select-Object` cmdlet to output an array of `[System.Diagnostics.ProcessModule]` instances as contained in the **Modules** property of each `System.Diagnostics.Process` instance output by `Get-Process`. The **Property** parameter of the `Select-Object` cmdlet selects the process names. This adds a `ProcessName` **NoteProperty** to every `[System.Diagnostics.ProcessModule]` instance and populates it with the value of current process's **ProcessName** property. Finally, `Format-List` cmdlet is used to display the name and modules of each process in a list. ```powershell Get-Process Explorer | Select-Object -Property ProcessName -ExpandProperty Modules | Format-List ``` ```Output ProcessName : explorer ModuleName : explorer.exe FileName : C:\WINDOWS\explorer.exe BaseAddress : 140697278152704 ModuleMemorySize : 3919872 EntryPointAddress : 140697278841168 FileVersionInfo : File: C:\WINDOWS\explorer.exe InternalName: explorer OriginalFilename: EXPLORER.EXE.MUI FileVersion: 10.0.17134.1 (WinBuild.160101.0800) FileDescription: Windows Explorer Product: Microsoft Windows Operating System ProductVersion: 10.0.17134.1 ... ``` ### Example 3: Select processes using the most memory This example gets the five processes that are using the most memory. The `Get-Process` cmdlet gets the processes on the computer. The `Sort-Object` cmdlet sorts the processes according to memory (working set) usage, and the `Select-Object` cmdlet selects only the last five members of the resulting array of objects. The **Wait** parameter isn't required in commands that include the `Sort-Object` cmdlet because `Sort-Object` processes all objects and then returns a collection. The `Select-Object` optimization is available only for commands that return objects individually as they're processed. ```powershell Get-Process | Sort-Object -Property WS | Select-Object -Last 5 ``` ```Output Handles NPM(K) PM(K) WS(K) VS(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 2866 320 33432 45764 203 222.41 1292 svchost 577 17 23676 50516 265 50.58 4388 WINWORD 826 11 75448 76712 188 19.77 3780 Ps 1367 14 73152 88736 216 61.69 676 Ps 1612 44 66080 92780 380 900.59 6132 INFOPATH ``` ### Example 4: Select unique characters from an array This example uses the **Unique** parameter of `Select-Object` to get unique characters from an array of characters. ```powershell "a","b","c","a","A","a" | Select-Object -Unique ``` ```Output a b c A ``` ### Example 5: Using `-Unique` with other parameters The **Unique** parameter filters values after other `Select-Object` parameters are applied. For example, if you use the **First** parameter to select the first number of items in an array, **Unique** is only applied to the selected values and not the entire array. ```powershell "a","a","b","c" | Select-Object -First 2 -Unique ``` ```Output a ``` In this example, **First** selects `"a","a"` as the first 2 items in the array. **Unique** is applied to `"a","a"` and returns `a` as the unique value. ### Example 6: Select unique strings using the `-CaseInsensitive` parameter This example uses case-insensitive comparisons to get unique strings from an array of strings. ```powershell "aa", "Aa", "Bb", "bb" | Select-Object -Unique -CaseInsensitive ``` ```Output aa Bb ``` ### Example 7: Select newest and oldest events in the event log This example gets the first (newest) and last (oldest) events in the Windows PowerShell event log. `Get-WinEvent` gets all events in the Windows PowerShell log and saves them in the `$a` variable. Then, `$a` is piped to the `Select-Object` cmdlet. The `Select-Object` command uses the **Index** parameter to select events from the array of events in the `$a` variable. The index of the first event is 0. The index of the last event is the number of items in `$a` minus 1. ```powershell $a = Get-WinEvent -LogName "Windows PowerShell" $a | Select-Object -Index 0, ($a.Count - 1) ``` ### Example 8: Select all but the first object This example creates a new PSSession on each of the computers listed in the Servers.txt files, except for the first one. `Select-Object` selects all but the first computer in a list of computer names. The resulting list of computers is set as the value of the **ComputerName** parameter of the `New-PSSession` cmdlet. ```powershell New-PSSession -ComputerName (Get-Content Servers.txt | Select-Object -Skip 1) ``` ### Example 9: Rename files and select several to review This example adds a "-ro" suffix to the base names of text files that have the read-only attribute and then displays the first five files so the user can see a sample of the effect. `Get-ChildItem` uses the **ReadOnly** dynamic parameter to get read-only files. The resulting files are piped to the `Rename-Item` cmdlet, which renames the file. It uses the **PassThru** parameter of `Rename-Item` to send the renamed files to the `Select-Object` cmdlet, which selects the first 5 for display. The **Wait** parameter of `Select-Object` prevents PowerShell from stopping the `Get-ChildItem` cmdlet after it gets the first five read-only text files. Without this parameter, only the first five read-only files would be renamed. ```powershell Get-ChildItem *.txt -ReadOnly | Rename-Item -NewName {$_.BaseName + "-ro.txt"} -PassThru | Select-Object -First 5 -Wait ``` ### Example 10: Show the intricacies of the -ExpandProperty parameter This example shows the intricacies of the **ExpandProperty** parameter. Note that the output generated was an array of `[System.Int32]` instances. The instances conform to standard formatting rules of the **Output View**. This is true for any _Expanded_ properties. If the outputted objects have a specific standard format, the expanded property might not be visible. ```powershell # Create a custom object to use for the Select-Object example. $object = [pscustomobject]@{Name="CustomObject";Expand=@(1,2,3,4,5)} # Use the ExpandProperty parameter to Expand the property. $object | Select-Object -ExpandProperty Expand -Property Name ``` ```Output 1 2 3 4 5 ``` ```powershell # The output did not contain the Name property, but it was added successfully. # Use Get-Member to confirm the Name property was added and populated. $object | Select-Object -ExpandProperty Expand -Property Name | Get-Member ``` ```Output TypeName: System.Int32 Name MemberType Definition ---- ---------- ---------- CompareTo Method int CompareTo(System.Object value), int CompareTo(int value), ... Equals Method bool Equals(System.Object obj), bool Equals(int obj), bool IEq... GetHashCode Method int GetHashCode() GetType Method type GetType() GetTypeCode Method System.TypeCode GetTypeCode(), System.TypeCode IConvertible.Ge... ToBoolean Method bool IConvertible.ToBoolean(System.IFormatProvider provider) ToByte Method byte IConvertible.ToByte(System.IFormatProvider provider) ToChar Method char IConvertible.ToChar(System.IFormatProvider provider) ToDateTime Method datetime IConvertible.ToDateTime(System.IFormatProvider provider) ToDecimal Method decimal IConvertible.ToDecimal(System.IFormatProvider provider) ToDouble Method double IConvertible.ToDouble(System.IFormatProvider provider) ToInt16 Method int16 IConvertible.ToInt16(System.IFormatProvider provider) ToInt32 Method int IConvertible.ToInt32(System.IFormatProvider provider) ToInt64 Method long IConvertible.ToInt64(System.IFormatProvider provider) ToSByte Method sbyte IConvertible.ToSByte(System.IFormatProvider provider) ToSingle Method float IConvertible.ToSingle(System.IFormatProvider provider) ToString Method string ToString(), string ToString(string format), string ToS... ToType Method System.Object IConvertible.ToType(type conversionType, System... ToUInt16 Method uint16 IConvertible.ToUInt16(System.IFormatProvider provider) ToUInt32 Method uint32 IConvertible.ToUInt32(System.IFormatProvider provider) ToUInt64 Method uint64 IConvertible.ToUInt64(System.IFormatProvider provider) Name NoteProperty string Name=CustomObject ``` ### Example 11: Create custom properties on objects The following example demonstrates using `Select-Object` to add a custom property to any object. When you specify a property name that doesn't exist, `Select-Object` creates that property as a **NoteProperty** on each object passed. ```powershell $customObject = 1 | Select-Object -Property MyCustomProperty $customObject.MyCustomProperty = "New Custom Property" $customObject ``` ```Output MyCustomProperty ---------------- New Custom Property ``` ### Example 12: Create calculated properties for each InputObject This example demonstrates using `Select-Object` to add calculated properties to your input. Passing a **ScriptBlock** to the **Property** parameter causes `Select-Object` to evaluate the expression on each object passed and add the results to the output. Within the **ScriptBlock**, you can use the `$_` variable to reference the current object in the pipeline. By default, `Select-Object` uses the **ScriptBlock** string as the name of the property. Using a **Hashtable**, you can label the output of your **ScriptBlock** as a custom property added to each object. You can add multiple calculated properties to each object passed to `Select-Object`. ```powershell # Create a calculated property called $_.StartTime.DayOfWeek Get-Process | Select-Object -Property ProcessName,{$_.StartTime.DayOfWeek} ``` ```Output ProcessName $_.StartTime.DayOfWeek ---- ---------------------- alg Wednesday ati2evxx Wednesday ati2evxx Thursday ... ``` ```powershell # Add a custom property to calculate the size in KiloBytes of each FileInfo # object you pass in. Use the pipeline variable to divide each file's length by # 1 KiloBytes $size = @{Label="Size(KB)";Expression={$_.Length/1KB}} # Create an additional calculated property with the number of Days since the # file was last accessed. You can also shorten the key names to be 'l', and 'e', # or use Name instead of Label. $days = @{l="Days";e={((Get-Date) - $_.LastAccessTime).Days}} # You can also shorten the name of your label key to 'l' and your expression key # to 'e'. Get-ChildItem $PSHOME -File | Select-Object Name, $size, $days ``` ```Output Name Size(KB) Days ---- -------- ---- Certificate.format.ps1xml 12.5244140625 223 Diagnostics.Format.ps1xml 4.955078125 223 DotNetTypes.format.ps1xml 134.9833984375 223 ``` ### Example 13: Select hashtable keys without using calculated properties Beginning in PowerShell 6, `Select-Object` supports selecting the keys of **hashtable** input as properties. The following example selects the `weight` and `name` keys on an input hashtable and displays the output. ```powershell @{ name = 'a' ; weight = 7 } | Select-Object -Property name, weight ``` ```output name weight ---- ------ a 7 ``` ### Example 14: ExpandProperty alters the original object This example demonstrates the side-effect of using the **ExpandProperty** parameter. When you use **ExpandProperty**, `Select-Object` adds the selected properties to the original object as **NoteProperty** members. ```powershell PS> $object = [pscustomobject]@{ name = 'USA' children = [pscustomobject]@{ name = 'Southwest' } } PS> $object name children ---- -------- USA @{name=Southwest} # Use the ExpandProperty parameter to expand the children property PS> $object | Select-Object @{n="country"; e={$_.name}} -ExpandProperty children name country ---- ------- Southwest USA # The original object has been altered PS> $object name children ---- -------- USA @{name=Southwest; country=USA} ``` As you can see, the **country** property was added to the **children** object after using the **ExpandProperty** parameter. ### Example 15: Create a new object with expanded properties without altering the input object You can avoid the side-effect of using the **ExpandProperty** parameter by creating a new object and copying the properties from the input object. ```powershell PS> $object = [pscustomobject]@{ name = 'USA' children = [pscustomobject]@{ name = 'Southwest' } } PS> $object name children ---- -------- USA @{name=Southwest} # Create a new object with selected properties PS> $newObject = [pscustomobject]@{ country = $object.name children = $object.children } PS> $newObject country children ------- -------- USA @{name=Southwest} # $object remains unchanged PS> $object name children ---- -------- USA @{name=Southwest} ``` ## PARAMETERS ### -CaseInsensitive By default, when you use the **Unique** parameter the cmdlet uses case-sensitive comparisons. When you use this parameter, the cmdlet uses case-insensitive comparisons. This parameter was added in PowerShell 7.4. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ExcludeProperty Specifies the properties that this cmdlet excludes from the operation. Wildcards are permitted. Beginning in PowerShell 6, it's no longer required to include the **Property** parameter for **ExcludeProperty** to work. ```yaml Type: System.String[] Parameter Sets: DefaultParameter, SkipLastParameter Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -ExpandProperty Specifies a property to select, and indicates that an attempt should be made to expand that property. If the input object pipeline doesn't have the property named, `Select-Object` returns an error. - If the specified property is an array, each value of the array is included in the output. - If the specified property is an object, the objects properties are expanded for every **InputObject** In either case, the output objects' **Type** matches the expanded property's **Type**. > [!NOTE] > There is a side-effect when using **ExpandProperty**. The `Select-Object` adds the selected > properties to the original object as **NoteProperty** members. If the **Property** parameter is specified, `Select-Object` attempts to add each selected property as a **NoteProperty** to every outputted object. > [!WARNING] > If you receive an error that a property can't be processed because a property with that name > already exists, consider the following. Note that when using **ExpandProperty**, `Select-Object` > can't replace an existing property. This means: > > - If the expanded object has a property of the same name, the command returns an error. > - If the _Selected_ object has a property of the same name as an _Expanded_ object's property, the > command returns an error. ```yaml Type: System.String Parameter Sets: DefaultParameter, SkipLastParameter Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -First Specifies the number of objects to select from the beginning of an array of input objects. ```yaml Type: System.Int32 Parameter Sets: DefaultParameter Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Index Selects objects from an array based on their index values. Enter the indexes in a comma-separated list. Indexes in an array begin with 0, where 0 represents the first value and (n-1) represents the last value. ```yaml Type: System.Int32[] Parameter Sets: IndexParameter Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies objects to send to the cmdlet through the pipeline. This parameter enables you to pipe objects to `Select-Object`. When you pass objects to the **InputObject** parameter, instead of using the pipeline, `Select-Object` treats the **InputObject** as a single object, even if the value is a collection. It is recommended that you use the pipeline when passing collections to `Select-Object`. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Last Specifies the number of objects to select from the end of an array of input objects. ```yaml Type: System.Int32 Parameter Sets: DefaultParameter Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Property Specifies the properties to select. These properties are added as **NoteProperty** members to the output objects. Wildcards are permitted. If the input object doesn't have the property named, the value of the new **NoteProperty** is set to `$null`. The value of the **Property** parameter can be a new calculated property. To create a calculated, property, use a hash table. Valid keys are: - Name (or Label) - `<string>` - Expression - `<string>` or `<script block>` For more information, see [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). ```yaml Type: System.Object[] Parameter Sets: DefaultParameter, SkipLastParameter Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Skip Skips (doesn't select) the specified number of items. By default, the **Skip** parameter counts from the beginning of the collection of objects. If the command uses the **Last** parameter, it counts from the end of the collection. Unlike the **Index** parameter, which starts counting at 0, the **Skip** parameter begins at 1. Beginning in PowerShell 7.4, you can use the **Skip** parameter with the **SkipLast** parameter to skip items from both the beginning and end of the collection. ```yaml Type: System.Int32 Parameter Sets: DefaultParameter Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipIndex Skips (doesn't select) the objects from an array based on their index values. Enter the indexes in a comma-separated list. Indexes in an array begin with 0, where 0 represents the first value and (n-1) represents the last value. This parameter was introduced in Windows PowerShell 6.0. ```yaml Type: System.Int32[] Parameter Sets: SkipIndexParameter Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipLast Skips (doesn't select) the specified number of items from the end of the list or array. Works in the same way as using **Skip** together with **Last** parameter. Unlike the **Index** parameter, which starts counting at 0, the **SkipLast** parameter begins at 1. Beginning in PowerShell 7.4, you can use the **Skip** parameter with the **SkipLast** parameter to skip items from both the beginning and end of the collection. ```yaml Type: System.Int32 Parameter Sets: SkipLastParameter Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Unique Specifies that if a subset of the input objects has identical properties and values, only a single member of the subset should be selected. **Unique** selects values _after_ other filtering parameters are applied. This parameter is case-sensitive. As a result, strings that differ only in character casing are considered to be unique. Add the **CaseInsensitive** parameter to perform case-insensitive comparisons. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Wait Indicates that the cmdlet turns off optimization. PowerShell runs commands in the order that they appear in the command pipeline and lets them generate all objects. By default, if you include a `Select-Object` command with the **First** or **Index** parameters in a command pipeline, PowerShell stops the command that generates the objects as soon as the selected number of objects is generated. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: DefaultParameter, IndexParameter Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.Management.Automation.PSObject You can pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSObject This cmdlet returns the input objects with only the selected properties. ## NOTES PowerShell includes the following aliases for `Select-Object`: - All platforms: - `select` The optimization feature of `Select-Object` is available only for commands that write objects to the pipeline as they're processed. It has no effect on commands that buffer processed objects and write them as a collection. Writing objects immediately is a cmdlet design best practice. For more information, see _Write Single Records to the Pipeline_ in [Strongly Encouraged Development Guidelines](/powershell/scripting/developer/windows-powershell). ## RELATED LINKS [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md) [Group-Object](Group-Object.md) [Sort-Object](Sort-Object.md) [Where-Object](../Microsoft.PowerShell.Core/Where-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Select-String.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 06/07/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/select-string?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Select-String --- # Select-String ## SYNOPSIS Finds text in strings and files. ## SYNTAX ### File (Default) ``` Select-String [-Culture <String>] [-Pattern] <String[]> [-Path] <String[]> [-SimpleMatch] [-CaseSensitive] [-Quiet] [-List] [-NoEmphasis] [-Include <String[]>] [-Exclude <String[]>] [-NotMatch] [-AllMatches] [-Encoding <Encoding>] [-Context <Int32[]>] [<CommonParameters>] ``` ### ObjectRaw ``` Select-String [-Culture <String>] -InputObject <PSObject> [-Pattern] <String[]> -Raw [-SimpleMatch] [-CaseSensitive] [-List] [-NoEmphasis] [-Include <String[]>] [-Exclude <String[]>] [-NotMatch] [-AllMatches] [-Encoding <Encoding>] [-Context <Int32[]>] [<CommonParameters>] ``` ### Object ``` Select-String [-Culture <String>] -InputObject <PSObject> [-Pattern] <String[]> [-SimpleMatch] [-CaseSensitive] [-Quiet] [-List] [-NoEmphasis] [-Include <String[]>] [-Exclude <String[]>] [-NotMatch] [-AllMatches] [-Encoding <Encoding>] [-Context <Int32[]>] [<CommonParameters>] ``` ### FileRaw ``` Select-String [-Culture <String>] [-Pattern] <String[]> [-Path] <String[]> -Raw [-SimpleMatch] [-CaseSensitive] [-List] [-NoEmphasis] [-Include <String[]>] [-Exclude <String[]>] [-NotMatch] [-AllMatches] [-Encoding <Encoding>] [-Context <Int32[]>] [<CommonParameters>] ``` ### LiteralFileRaw ``` Select-String [-Culture <String>] [-Pattern] <String[]> -LiteralPath <String[]> -Raw [-SimpleMatch] [-CaseSensitive] [-List] [-NoEmphasis] [-Include <String[]>] [-Exclude <String[]>] [-NotMatch] [-AllMatches] [-Encoding <Encoding>] [-Context <Int32[]>] [<CommonParameters>] ``` ### LiteralFile ``` Select-String [-Culture <String>] [-Pattern] <String[]> -LiteralPath <String[]> [-SimpleMatch] [-CaseSensitive] [-Quiet] [-List] [-NoEmphasis] [-Include <String[]>] [-Exclude <String[]>] [-NotMatch] [-AllMatches] [-Encoding <Encoding>] [-Context <Int32[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Select-String` cmdlet uses regular expression matching to search for text patterns in input strings and files. You can use `Select-String` similar to `grep` in Unix or `findstr.exe` in Windows. `Select-String` is based on lines of text. By default, `Select-String` finds the first match in each line and, for each match, it displays the file name, line number, and all text in the line containing the match. You can direct `Select-String` to find multiple matches per line, display text before and after the match, or display a Boolean value (True or False) that indicates whether a match is found. `Select-String` can display all the text matches or stop after the first match in each input file. `Select-String` can be used to display all text that doesn't match the specified pattern. You can also specify that `Select-String` should expect a particular character encoding, such as when you're searching files of Unicode text. `Select-String` uses the byte-order-mark (BOM) to detect the encoding format of the file. If the file has no BOM, it assumes the encoding is UTF8. ## EXAMPLES ### Example 1: Find a case-sensitive match This example does a case-sensitive match of the text that was sent down the pipeline to the `Select-String` cmdlet. ```powershell 'Hello', 'HELLO' | Select-String -Pattern 'HELLO' -CaseSensitive -SimpleMatch ``` The text strings **Hello** and **HELLO** are sent down the pipeline to the `Select-String` cmdlet. `Select-String` uses the **Pattern** parameter to specify **HELLO**. The **CaseSensitive** parameter specifies that the case must match only the upper-case pattern. **SimpleMatch** is an optional parameter and specifies that the string in the pattern isn't interpreted as a regular expression. `Select-String` displays **HELLO** in the PowerShell console. ### Example 2: Find matches in text files This command searches all files with the `.txt` file name extension in the current directory. The output displays the lines in those files that include the specified string. ```powershell Get-Alias | Out-File -FilePath .\Alias.txt Get-Command | Out-File -FilePath .\Command.txt Select-String -Path .\*.txt -Pattern 'Get-' ``` ```Output Alias.txt:8:Alias cat -> Get-Content Alias.txt:28:Alias dir -> Get-ChildItem Alias.txt:43:Alias gal -> Get-Alias Command.txt:966:Cmdlet Get-Acl Command.txt:967:Cmdlet Get-Alias ``` In this example, `Get-Alias` and `Get-Command` are used with the `Out-File` cmdlet to create two text files in the current directory, **Alias.txt** and **Command.txt**. `Select-String` uses the **Path** parameter with the asterisk (`*`) wildcard to search all files in the current directory with the file name extension `.txt`. The **Pattern** parameter specifies the text to match **Get-**. `Select-String` displays the output in the PowerShell console. The file name and line number precede each line of content that contains a match for the **Pattern** parameter. ### Example 3: Find a pattern match In this example, multiple files are searched to find matches for the specified pattern. The pattern uses a regular expression quantifier. For more information, see [about_Regular_Expressions](../Microsoft.PowerShell.Core/About/About_Regular_Expressions.md). ```powershell Select-String -Path "$PSHOME\en-US\*.txt" -Pattern '\?' ``` ```Output C:\Program Files\PowerShell\6\en-US\default.help.txt:27: beginning at https://go.microsoft.com/fwlink/?LinkID=108518. C:\Program Files\PowerShell\6\en-US\default.help.txt:50: or go to: https://go.microsoft.com/fwlink/?LinkID=210614 ``` The `Select-String` cmdlet uses two parameters, **Path** and **Pattern**. The **Path** parameter uses the variable `$PSHOME` that specifies the PowerShell directory. The remainder of the path includes the subdirectory **en-US** and specifies each `*.txt` file in the directory. The **Pattern** parameter specifies to match a question mark (`?`) in each file. A backslash (`\`) is used as an escape character and is necessary because the question mark (`?`) is a regular expression quantifier. `Select-String` displays the output in the PowerShell console. The file name and line number precede each line of content that contains a match for the **Pattern** parameter. ### Example 4: Use Select-String in a function This example creates a function to search for a pattern in the PowerShell help files. For this example, the function only exists in the PowerShell session. When the PowerShell session is closed, the function is deleted. For more information, see [about_Functions](../Microsoft.PowerShell.Core/About/about_Functions.md). ```powershell function Search-Help { $PSHelp = "$PSHOME\en-US\*.txt" Select-String -Path $PSHelp -Pattern 'About_' } Search-Help ``` ```powershell C:\Program Files\PowerShell\7\en-US\default.help.txt:67: The titles of conceptual topics begin with "About_". C:\Program Files\PowerShell\7\en-US\default.help.txt:70: Get-Help About_<topic-name> C:\Program Files\PowerShell\7\en-US\default.help.txt:93: Get-Help About_Modules : Displays help about PowerShell modules. C:\Program Files\PowerShell\7\en-US\default.help.txt:97: about_Updatable_Help ``` The function is created on the PowerShell command line. The `function` keyword uses the name `Search-Help`. Press **Enter** to begin adding statements to the function. From the `>>` prompt, add each statement and press **Enter** as shown in the example. After the closing bracket is added, you're returned to a PowerShell prompt. The function contains two commands. The `$PSHelp` variable stores the path to the PowerShell help files. `$PSHOME` is the PowerShell installation directory with the subdirectory **en-US** that specifies each `*.txt` file in the directory. The `Select-String` command in the function uses the **Path** and **Pattern** parameters. The **Path** parameter uses the `$PSHelp` variable to get the path. The **Pattern** parameter uses the string **About_** as the search criteria. To run the function, type `Search-Help`. The function's `Select-String` command displays the output in the PowerShell console. ### Example 5: Search for a string in a Windows event log This example searches for a string in a Windows event log. The variable `$_` represents the current object in the pipeline. For more information, see [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md). ```powershell $Events = Get-WinEvent -LogName Application -MaxEvents 50 $Events | Select-String -InputObject {$_.Message} -Pattern 'Failed' ``` The `Get-WinEvent` cmdlet uses the **LogName** parameter to specify the Application log. The **MaxEvents** parameter gets the 50 most recent events from the log. The log content is stored in the variable named `$Events`. The `$Events` variable is sent down the pipeline to the `Select-String` cmdlet. `Select-String` uses the **InputObject** parameter. The `$_` variable represents the current object and `Message` is a property of the event. The **Pattern** parameter specifies the string **Failed** and searches for matches in `$_.Message`. `Select-String` displays the output in the PowerShell console. ### Example 6: Find a string in subdirectories This example searches a directory and all of its subdirectories for a specific text string. ```powershell Get-ChildItem -Path C:\Windows\System32\*.txt -Recurse | Select-String -Pattern 'Microsoft' -CaseSensitive ``` `Get-ChildItem` uses the **Path** parameter to specify **C:\Windows\System32\*.txt**. The **Recurse** parameter includes the subdirectories. The objects are sent down the pipeline to `Select-String`. `Select-String` uses the **Pattern** parameter and specifies the string **Microsoft**. The **CaseSensitive** parameter is used to match the exact case of the string. `Select-String` displays the output in the PowerShell console. > [!NOTE] > Dependent upon your permissions, you might see **Access denied** messages in the output. ### Example 7: Find strings that do not match a pattern This example shows how to exclude lines of data that don't match a pattern. ```powershell Get-Command | Out-File -FilePath .\Command.txt Select-String -Path .\Command.txt -Pattern 'Get', 'Set' -NotMatch ``` The `Get-Command` cmdlet sends objects down the pipeline to the `Out-File` to create the **Command.txt** file in the current directory. `Select-String` uses the **Path** parameter to specify the **Command.txt** file. The **Pattern** parameter specifies **Get** and **Set** as the search pattern. The **NotMatch** parameter excludes **Get** and **Set** from the results. `Select-String` displays the output in the PowerShell console that doesn't include **Get** or **Set**. ### Example 8: Find lines before and after a match This example shows how to get the lines before and after the matched pattern. ```powershell Get-Command | Out-File -FilePath .\Command.txt Select-String -Path .\Command.txt -Pattern 'Get-Computer' -Context 2, 3 ``` ```Output Command.txt:986:Cmdlet Get-CmsMessage 6.1.0.0 Microsoft.PowerShell.Security Command.txt:987:Cmdlet Get-Command 6.1.2.0 Microsoft.PowerShell.Core > Command.txt:988:Cmdlet Get-ComputerInfo 6.1.0.0 Microsoft.PowerShell.Management Command.txt:990:Cmdlet Get-Content 6.1.0.0 Microsoft.PowerShell.Management Command.txt:991:Cmdlet Get-ControlPanelItem 3.1.0.0 Microsoft.PowerShell.Management Command.txt:992:Cmdlet Get-Credential 6.1.0.0 Microsoft.PowerShell.Security ``` The `Get-Command` cmdlet sends objects down the pipeline to the `Out-File` to create the **Command.txt** file in the current directory. `Select-String` uses the **Path** parameter to specify the **Command.txt** file. The **Pattern** parameter specifies `Get-Computer` as the search pattern. The **Context** parameter uses two values, before and after, and marks pattern matches in the output with an angle bracket (`>`). The **Context** parameter outputs the two lines before the first pattern match and three lines after the last pattern match. ### Example 9: Find all pattern matches This example shows how the **AllMatches** parameter finds each pattern match in a line of text. By default, `Select-String` only finds the first occurrence of a pattern in a line of text. This example uses object properties that are found with the `Get-Member` cmdlet. ```powershell $A = Get-ChildItem -Path "$PSHOME\en-US\*.txt" | Select-String -Pattern 'PowerShell' $A ``` ```Output C:\Program Files\PowerShell\7\en-US\default.help.txt:3: PowerShell Help System C:\Program Files\PowerShell\7\en-US\default.help.txt:6: Displays help about PowerShell cmdlets and concepts. C:\Program Files\PowerShell\7\en-US\default.help.txt:9: PowerShell Help describes PowerShell cmdlets ``` ```powershell $A.Matches ``` ```Output Groups : {0} Success : True Name : 0 Captures : {0} Index : 4 Length : 10 Value : PowerShell ``` ```powershell $A.Matches.Length ``` ```Output 8 ``` ```powershell $B = Get-ChildItem -Path "$PSHOME\en-US\*.txt" | Select-String -Pattern 'PowerShell' -AllMatches $B.Matches.Length ``` ```Output 9 ``` The `Get-ChildItem` cmdlet uses the **Path** parameter. The **Path** parameter uses the variable `$PSHOME` that specifies the PowerShell directory. The remainder of the path includes the subdirectory **en-US** and specifies each `*.txt` file in the directory. The `Get-ChildItem` objects are stored in the `$A` variable. The `$A` variable is sent down the pipeline to the `Select-String` cmdlet. `Select-String` uses the **Pattern** parameter to search each file for the string **PowerShell**. From the PowerShell command line, the `$A` variable contents are displayed. There's a line that contains two occurrences of the string **PowerShell**. The `$A.Matches` property lists the first occurrence of the pattern **PowerShell** on each line. The `$A.Matches.Length` property counts the first occurrence of the pattern **PowerShell** on each line. The `$B` variable uses the same `Get-ChildItem` and `Select-String` cmdlets, but adds the **AllMatches** parameter. **AllMatches** finds each occurrence of the pattern **PowerShell** on each line. The objects stored in the `$A` and `$B` variables are identical. The `$B.Matches.Length` property increases because for each line, every occurrence of the pattern **PowerShell** is counted. ### Example 10 - Convert pipeline objects to strings using `Out-String` The `ToString()` result of the piped object isn't the same rich string representation produced by PowerShell's formatting system. So, you may need to pipe the objects to `Out-String` first. Piping to `Out-String` converts the formatted output into a single multi-line string object. This means that when `Select-String` finds a match it outputs the whole multiline string. ```powershell PS> $hash = @{ Name = 'foo' Category = 'bar' } # !! NO output, due to .ToString() conversion $hash | Select-String -Pattern 'foo' # Out-String converts the output to a single multi-line string object PS> $hash | Out-String | Select-String -Pattern 'foo' Name Value ---- ----- Name foo Category bar # Out-String -Stream converts the output to a multiple single-line string objects PS> $hash | Out-String -Stream | Select-String -Pattern 'foo' Name foo ``` Piping to `Out-String -Stream` converts the formatted output into a multiple single-line string objects. This means that when `Select-String` finds a match it outputs only the matching line. ## PARAMETERS ### -AllMatches Indicates that the cmdlet searches for more than one match in each line of text. Without this parameter, `Select-String` finds only the first match in each line of text. When `Select-String` finds more than one match in a line of text, it still emits only one **MatchInfo** object for the line, but the **Matches** property of the object contains all the matches. > [!NOTE] > This parameter is ignored when used in combination with the **SimpleMatch** parameter. If you wish > to return all matches and the pattern that you are searching for contains regular expression > characters, you must escape those characters rather than using **SimpleMatch**. See > [about_Regular_Expressions](../Microsoft.PowerShell.Core/About/about_Regular_Expressions.md) for > more information about escaping regular expressions. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -CaseSensitive Indicates that the cmdlet matches are case-sensitive. By default, matches aren't case-sensitive. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Context Captures the specified number of lines before and after the line that matches the pattern. If you enter one number as the value of this parameter, that number determines the number of lines captured before and after the match. If you enter two numbers as the value, the first number determines the number of lines before the match and the second number determines the number of lines after the match. For example, `-Context 2,3`. In the default display, lines with a match are indicated by a right angle bracket (`>`) (ASCII 62) in the first column of the display. Unmarked lines are the context. The **Context** parameter doesn't change the number of objects generated by `Select-String`. `Select-String` generates one [MatchInfo](/dotnet/api/microsoft.powershell.commands.matchinfo) object for each match. The context is stored as an array of strings in the **Context** property of the object. When the output of a `Select-String` command is sent down the pipeline to another `Select-String` command, the receiving command searches only the text in the matched line. The matched line is the value of the **Line** property of the **MatchInfo** object, not the text in the context lines. As a result, the **Context** parameter isn't valid on the receiving `Select-String` command. When the context includes a match, the **MatchInfo** object for each match includes all the context lines, but the overlapping lines appear only once in the display. ```yaml Type: System.Int32[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Culture Specifies a culture name to match the specified pattern. The **Culture** parameter must be used with the **SimpleMatch** parameter. The default behavior uses the culture of the current PowerShell runspace (session). To get a list of all supported cultures, use `Get-Culture -ListAvailable` command. In addition, this parameter accepts the following arguments: - CurrentCulture, that is default; - Ordinal, that is non-linguistic binary comparison; - Invariant, that is culture independent comparison. With `Select-String -Culture Ordinal -CaseSensitive -SimpleMatch` command you gets fastest binary comparison. The **Culture** parameter uses tab completion to scroll through the list of arguments that specify the available cultures. To list all available arguments, use the following command: `(Get-Command Select-String).Parameters.Culture.Attributes.ValidValues` For more information about .NET CultureInfo.Name property, see [CultureInfo.Name](/dotnet/api//system.globalization.cultureinfo.name). The **Culture** parameter was introduced in PowerShell 7. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Culture of the current PowerShell session Accept pipeline input: False Accept wildcard characters: False ``` ### -Encoding Specifies the type of encoding for the target file. The default value is `utf8NoBOM`. The acceptable values for this parameter are as follows: - `ascii`: Uses the encoding for the ASCII (7-bit) character set. - `ansi`: Uses the encoding for the for the current culture's ANSI code page. This option was added in PowerShell 7.4. - `bigendianunicode`: Encodes in UTF-16 format using the big-endian byte order. - `bigendianutf32`: Encodes in UTF-32 format using the big-endian byte order. - `oem`: Uses the default encoding for MS-DOS and console programs. - `unicode`: Encodes in UTF-16 format using the little-endian byte order. - `utf7`: Encodes in UTF-7 format. - `utf8`: Encodes in UTF-8 format. - `utf8BOM`: Encodes in UTF-8 format with Byte Order Mark (BOM) - `utf8NoBOM`: Encodes in UTF-8 format without Byte Order Mark (BOM) - `utf32`: Encodes in UTF-32 format. Beginning with PowerShell 6.2, the **Encoding** parameter also allows numeric IDs of registered code pages (like `-Encoding 1251`) or string names of registered code pages (like `-Encoding "windows-1251"`). For more information, see the .NET documentation for [Encoding.CodePage](/dotnet/api/system.text.encoding.codepage?view=netcore-2.2). Starting with PowerShell 7.4, you can use the `Ansi` value for the **Encoding** parameter to pass the numeric ID for the current culture's ANSI code page without having to specify it manually. > [!NOTE] > **UTF-7*** is no longer recommended to use. As of PowerShell 7.1, a warning is written if you > specify `utf7` for the **Encoding** parameter. ```yaml Type: System.Text.Encoding Parameter Sets: (All) Aliases: Accepted values: ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 Required: False Position: Named Default value: UTF8NoBOM Accept pipeline input: False Accept wildcard characters: False ``` ### -Exclude Exclude the specified items. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Include Includes the specified items. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -InputObject Specifies the text to be searched. Enter a variable that contains the text, or type a command or expression that gets the text. Using the **InputObject** parameter isn't the same as sending strings down the pipeline to `Select-String`. When you pipe more than one string to the `Select-String` cmdlet, it searches for the specified text in each string and returns each string that contains the search text. When you use the **InputObject** parameter to submit a collection of strings, `Select-String` treats the collection as a single combined string. `Select-String` returns the strings as a unit if it finds the search text in any string. **FileInfo** objects are treated as a path to a file. When file paths are specified, `Select-String` searches the contents of the file, not the `ToString()` representation of the object. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: Object, ObjectRaw Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -List Only the first instance of matching text is returned from each input file. This is the most efficient way to retrieve a list of files that have contents matching the regular expression. By default, `Select-String` returns a **MatchInfo** object for each match it finds. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to the files to be searched. The value of the **LiteralPath** parameter is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. For more information, see [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md). ```yaml Type: System.String[] Parameter Sets: LiteralFileRaw, LiteralFile Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -NoEmphasis By default, `Select-String` highlights the string that matches the pattern you searched for with the **Pattern** parameter. The **NoEmphasis** parameter disables the highlighting. The emphasis uses negative colors based on your PowerShell background and text colors. For example, if your PowerShell colors are a black background with white text. The emphasis is a white background with black text. This parameter was introduced in PowerShell 7. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -NotMatch The **NotMatch** parameter finds text that doesn't match the specified pattern. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to the files to search. Wildcards are permitted. The default location is the local directory. Specify files in the directory, such as `log1.txt`, `*.doc`, or `*.*`. If you specify only a directory, the command fails. ```yaml Type: System.String[] Parameter Sets: File, FileRaw Aliases: Required: True Position: 1 Default value: Local directory Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Pattern Specifies the text to find on each line. The pattern value is treated as a regular expression. To learn about regular expressions, see [about_Regular_Expressions](../Microsoft.PowerShell.Core/About/about_Regular_Expressions.md). ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Quiet Indicates that the cmdlet returns a simple response instead of a **MatchInfo** object. The returned value is `$true` if the pattern is found or `$null` if the pattern is not found. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: File, Object, LiteralFile Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Raw Causes the cmdlet to output only the matching strings, rather than **MatchInfo** objects. This is the results in behavior that's the most similar to the Unix **grep** or Windows **findstr.exe** commands. This parameter was introduced in PowerShell 7. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ObjectRaw, FileRaw, LiteralFileRaw Aliases: Required: True Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -SimpleMatch Indicates that the cmdlet uses a simple match rather than a regular expression match. In a simple match, `Select-String` searches the input for the text in the **Pattern** parameter. It doesn't interpret the value of the **Pattern** parameter as a regular expression statement. Also, when **SimpleMatch** is used, the **Matches** property of the **MatchInfo** object returned is empty. > [!NOTE] > When this parameter is used with the **AllMatches** parameter, the **AllMatches** is ignored. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe any object that has a `ToString()` method to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.MatchInfo By default, this cmdlet returns a **MatchInfo** object for each match found. ### System.Boolean When you use the **Quiet** parameter, this cmdlet returns a **Boolean** value indicating whether the pattern was found. ### System.String When you use the **Raw** parameter, this cmdlet returns a set of **String** objects that match the pattern. ## NOTES PowerShell includes the following aliases for `Select-String`: - All platforms: - `sls` `Select-String` is similar to `grep` in Unix or `findstr.exe` in Windows. The `sls` alias for the `Select-String` cmdlet was introduced in PowerShell 3.0. > [!NOTE] > According to > [Approved Verbs for PowerShell Commands](/powershell/scripting/developer/cmdlet/approved-verbs-for-windows-powershell-commands), > the official alias prefix for `Select-*` cmdlets is `sc`, not `sl`. Therefore, the proper alias > for `Select-String` should be `scs`, not `sls`. This is an exception to this rule. When piping objects to `Select-String`: - **FileInfo** objects are treated as a path to a file. When file paths are specified, `Select-String` searches the contents of the file, not the `ToString()` representation of the object. - The `ToString()` result of the piped object isn't the same rich string representation produced by PowerShell's formatting system. So, you may need to pipe the objects to `Out-String` first. For more information, see Example 10. To use `Select-String`, type the text that you want to find as the value of the **Pattern** parameter. To specify the text to be searched, use the following criteria: - Type the text in a quoted string, and then pipe it to `Select-String`. - Store a text string in a variable, and then specify the variable as the value of the **InputObject** parameter. - If the text is stored in files, use the **Path** parameter to specify the path to the files. By default, `Select-String` interprets the value of the **Pattern** parameter as a regular expression. For more information, see [about_Regular_Expressions](../Microsoft.PowerShell.Core/About/about_Regular_Expressions.md). You can use the **SimpleMatch** parameter to override the regular expression matching. The **SimpleMatch** parameter finds instances of the value of the **Pattern** parameter in the input. The default output of `Select-String` is a **MatchInfo** object, which includes detailed information about the matches. The information in the object is useful when you're searching for text in files, because **MatchInfo** objects have properties such as **Filename** and **Line**. When the input isn't from the file, the value of these parameters is **InputStream**. If you don't need the information in the **MatchInfo** object, use the **Quiet** parameter. The **Quiet** parameter returns a Boolean value (True or False) to indicate whether it found a match, instead of a **MatchInfo** object. When matching phrases, `Select-String` uses the current culture that is set for the system. To find the current culture, use the `Get-Culture` cmdlet. To find the properties of a **MatchInfo** object, type the following command: `Select-String -Path test.txt -Pattern 'test' | Get-Member | Format-List -Property *` ## RELATED LINKS [about_Automatic_Variables](../Microsoft.PowerShell.Core/About/about_Automatic_Variables.md) [about_Comparison_Operators](../Microsoft.PowerShell.Core/About/about_Comparison_Operators.md) [about_Functions](../Microsoft.PowerShell.Core/About/about_Functions.md) [about_Quoting_Rules](../Microsoft.Powershell.Core/About/about_Quoting_Rules.md) [about_Regular_Expressions](../Microsoft.PowerShell.Core/About/about_Regular_Expressions.md) [Get-Alias](Get-Alias.md) [Get-ChildItem](../Microsoft.PowerShell.Management/Get-ChildItem.md) [Get-Command](../Microsoft.PowerShell.Core/Get-Command.md) [Get-Member](Get-Member.md) [Get-WinEvent](../Microsoft.PowerShell.Diagnostics/Get-WinEvent.md) [Out-File](Out-File.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Select-Xml.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 06/01/2021 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/select-xml?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Select-Xml --- # Select-Xml ## SYNOPSIS Finds text in an XML string or document. ## SYNTAX ### Xml (Default) ``` Select-Xml [-XPath] <string> [-Xml] <XmlNode[]> [-Namespace <hashtable>] [<CommonParameters>] ``` ### Path ``` Select-Xml [-XPath] <string> [-Path] <string[]> [-Namespace <hashtable>] [<CommonParameters>] ``` ### LiteralPath ``` Select-Xml [-XPath] <string> -LiteralPath <string[]> [-Namespace <hashtable>] [<CommonParameters>] ``` ### Content ``` Select-Xml [-XPath] <string> -Content <string[]> [-Namespace <hashtable>] [<CommonParameters>] ``` ## DESCRIPTION The `Select-Xml` cmdlet lets you use XPath queries to search for text in XML strings and documents. Enter an XPath query, and use the **Content**, **Path**, or **Xml** parameter to specify the XML to be searched. ## EXAMPLES ### Example 1: Select AliasProperty nodes This example gets the alias properties in the `Types.ps1xml`. For information about this file, see [about_Types.ps1xml](../Microsoft.PowerShell.Core/About/about_Types.ps1xml.md). The first command saves the path to the `Types.ps1xml` file in the `$Path` variable. The second command saves the XML path to the **AliasProperty** node in the `$XPath` variable. The `Select-Xml` cmdlet gets the **AliasProperty** nodes that are identified by the XPath statement from the `Types.ps1xml` file. The command uses a pipeline operator (`|`) to send the **AliasProperty** nodes to the `Select-Object` cmdlet. The **ExpandProperty** parameter expands the **Node** object and returns its **Name** and **ReferencedMemberName** properties. ```powershell $Path = "$PSHOME\Types.ps1xml" $XPath = "/Types/Type/Members/AliasProperty" Select-Xml -Path $Path -XPath $Xpath | Select-Object -ExpandProperty Node ``` ```Output Name ReferencedMemberName ---- -------------------- Count Length Name Key Name ServiceName RequiredServices ServicesDependedOn ProcessName Name Handles Handlecount VM VirtualSize WS WorkingSetSize Name ProcessName Handles Handlecount VM VirtualMemorySize WS WorkingSet PM PagedMemorySize NPM NonpagedSystemMemorySize Name __Class Namespace ModuleName ``` The result shows the Name and **ReferencedMemberName** of each alias property in the `Types.ps1xml` file. For example, there is a **Count** property that is an alias of the **Length** property. ### Example 2: Input an XML document This example shows how to use the **XML** parameter to provide an XML document to the `Select-Xml` cmdlet. The `Get-Content` cmdlet gets the content of the `Types.ps1xml` file and saves it in the `$Types` variable. The `[xml]` casts the variable as an XML object. The `Select-Xml` cmdlet gets the **MethodName** nodes in the `Types.ps1xml` file. The command uses the **Xml** parameter to specify the XML content in the `$Types` variable and the **XPath** parameter to specify the path to the **MethodName** node. ```powershell [xml]$Types = Get-Content $PSHOME\Types.ps1xml Select-Xml -Xml $Types -XPath "//MethodName" ``` ### Example 3: Search PowerShell Help files This example shows how to use the `Select-Xml` cmdlet to search the PowerShell XML-based cmdlet help files. In this example, we'll search for the cmdlet name that serves as a title for each help file and the path to the help file. The `$Namespace` variable contains a hash table that represents the XML namespace that is used for the help files. The `$Path` variable contains the path to the PowerShell help files. If there are no help files in this path on your computer, use the `Update-Help` cmdlet to download the help files. For more information about Updatable Help, see [about_Updatable_Help](../Microsoft.PowerShell.Core/About/about_Updatable_Help.md). The `Select-Xml` cmdlet searches the XML files for cmdlet names by finding `Command:Name` element anywhere in the files. The results are stored in the `$Xml` variable. `Select-Xml` returns a **SelectXmlInfo** object that has a **Node** property, which is a **System.Xml.XmlElement** object. The **Node** property has an **InnerXml** property that contains the actual XML that is retrieved. The `$Xml` variable is piped to the `Format-Table` cmdlet. The `Format-Table` command uses a calculated property to get the **Node.InnerXml** property of each object in the `$Xml` variable, trim the white space before and after the text, and display it in the table, along with the **Path** to the source file. ```powershell $Namespace = @{ command = "http://schemas.microsoft.com/maml/dev/command/2004/10" maml = "http://schemas.microsoft.com/maml/2004/10" dev = "http://schemas.microsoft.com/maml/dev/2004/10" } $Path = "$PSHOME\en-US\*dll-Help.xml" $Xml = Select-Xml -Path $Path -Namespace $Namespace -XPath "//command:name" $Xml | Format-Table @{Label="Name"; Expression= {($_.Node.InnerXml).Trim()}}, Path -AutoSize ``` ```Output Name Path ---- ---- Export-Counter C:\Windows\system32\WindowsPowerShell\v1.0\en-US\Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml Get-Counter C:\Windows\system32\WindowsPowerShell\v1.0\en-US\Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml Get-WinEvent C:\Windows\system32\WindowsPowerShell\v1.0\en-US\Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml Import-Counter C:\Windows\system32\WindowsPowerShell\v1.0\en-US\Microsoft.PowerShell.Commands.Diagnostics.dll-Help.xml Add-Computer C:\Windows\system32\WindowsPowerShell\v1.0\en-US\Microsoft.PowerShell.Commands.Management.dll-Help.xml Add-Content C:\Windows\system32\WindowsPowerShell\v1.0\en-US\Microsoft.PowerShell.Commands.Management.dll-Help.xml Checkpoint-Computer C:\Windows\system32\WindowsPowerShell\v1.0\en-US\Microsoft.PowerShell.Commands.Management.dll-Help.xml ... ``` ### Example 4: Different ways to input XML This example shows two different ways to send XML to the `Select-Xml` cmdlet. The first command saves a here-string that contains XML in the `$Xml` variable. For more information about here-strings, see [about_Quoting_Rules](../Microsoft.PowerShell.Core/About/about_Quoting_Rules.md). `Select-Xml` uses the **Content** parameter to specify the XML in the `$Xml` variable. The third command is the same as the second, except that tt uses a pipeline operator (`|`) to send the XML in the `$Xml` variable to the `Select-Xml` cmdlet. ```powershell $Xml = @" <?xml version="1.0" encoding="utf-8"?> <Book> <projects> <project name="Book1" date="2009-01-20"> <editions> <edition language="English">En.Book1.com</edition> <edition language="German">Ge.Book1.Com</edition> <edition language="French">Fr.Book1.com</edition> <edition language="Polish">Pl.Book1.com</edition> </editions> </project> </projects> </Book> "@ Select-Xml -Content $Xml -XPath "//edition" | foreach {$_.Node.InnerXml} En.Book1.com Ge.Book1.Com Fr.Book1.com Pl.Book1.com $Xml | Select-Xml -XPath "//edition" | foreach {$_.Node.InnerXml} En.Book1.com Ge.Book1.Com Fr.Book1.com Pl.Book1.com ``` ### Example 5: Use the default xmlns namespace This example shows how to use the `Select-Xml` cmdlet with XML documents that use the default xmlns namespace. The example gets the titles of Windows PowerShell ISE user-created snippet files. For information about snippets, see [New-IseSnippet](xref:ISE.New-IseSnippet). The `$SnippetNamespace` variable contains a hash table for the default namespace that snippet XML files use. The hash table value is the XMLNS schema URI in the snippet XML. The hash table key name, **snip**, is arbitrary. You can use any name that is not reserved, but you cannot use **xmlns**. The `Select-Xml` cmdlet gets the content of the **Title** element of each snippet. It uses the **Path** parameter to specify the Snippets directory and the **Namespace** parameter to specify the namespace in the `$SnippetNamespace` variable. The value of the **XPath** parameter is the `snip:Title`. The results are piped to the `ForEach-Object` cmdlet, which gets the title from the value of the **InnerXml** property of the node. ```powershell $SnippetNamespace = @{snip = "http://schemas.microsoft.com/PowerShell/Snippets"} Select-Xml -Path $HOME\Documents\WindowsPowerShell\Snippets -Namespace $SnippetNamespace -XPath "//snip:Title" | ForEach-Object {$_.Node.InnerXml} ``` ## PARAMETERS ### -Content Specifies a string that contains the XML to search. You can also pipe strings to `Select-Xml`. ```yaml Type: System.String[] Parameter Sets: Content Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -LiteralPath Specifies the paths and file names of the XML files to search. Unlike **Path**, the value of the **LiteralPath** parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Namespace Specifies a hash table of the namespaces used in the XML. Use the format`@{<namespaceName> = <namespaceValue>}`. When the XML uses the default namespace, which begins with xmlns, use an arbitrary key for the namespace name. You cannot use xmlns. In the XPath statement, prefix each node name with the namespace name and a colon, such as `//namespaceName:Node`. ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path and file names of the XML files to search. Wildcard characters are permitted. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Xml Specifies one or more XML nodes. An XML document will be processed as a collection of XML nodes. If you pipe an XML document to `Select-Xml`, each document node will be searched separately as it comes through the pipeline. ```yaml Type: System.Xml.XmlNode[] Parameter Sets: Xml Aliases: Node Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -XPath Specifies an XPath search query. The query language is case-sensitive. This parameter is required. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String or System.Xml.XmlNode You can pipe a path or XML node to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Commands.SelectXmlInfo ## NOTES XPath is a standard language that is designed to identify parts of an XML document. For more information about the XPath language, see [XPath Reference](/dotnet/standard/data/xml/select-nodes-using-xpath-navigation) and the Selection Filters section of [Event Selection](/previous-versions//aa385231(v=vs.85)). ## RELATED LINKS [ConvertTo-Xml](ConvertTo-Xml.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Send-MailMessage.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 06/18/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/send-mailmessage?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Send-MailMessage --- # Send-MailMessage ## SYNOPSIS Sends an email message. ## SYNTAX ### All ``` Send-MailMessage [-Attachments <String[]>] [-Bcc <String[]>] [[-Body] <String>] [-BodyAsHtml] [-Encoding <Encoding>] [-Cc <String[]>] [-DeliveryNotificationOption <DeliveryNotificationOptions>] -From <String> [[-SmtpServer] <String>] [-Priority <MailPriority>] [-ReplyTo <String[]>] [[-Subject] <String>] [-To] <String[]> [-Credential <PSCredential>] [-UseSsl] [-Port <Int32>] [<CommonParameters>] ``` ## DESCRIPTION The `Send-MailMessage` cmdlet sends an email message from within PowerShell. You must specify a Simple Mail Transfer Protocol (SMTP) server or the `Send-MailMessage` command fails. Use the **SmtpServer** parameter or set the `$PSEmailServer` variable to a valid SMTP server. The value assigned to `$PSEmailServer` is the default SMTP setting for PowerShell. For more information, see [about_Preference_Variables](../Microsoft.PowerShell.Core/About/about_Preference_Variables.md). > [!WARNING] > The `Send-MailMessage` cmdlet is obsolete. This cmdlet doesn't guarantee secure connections to > SMTP servers. While there is no immediate replacement available in PowerShell, we recommend you do > not use `Send-MailMessage`. For more information, see > [Platform Compatibility note DE0005](https://aka.ms/SendMailMessage). ## EXAMPLES ### Example 1: Send an email from one person to another person This example sends an email message from one person to another person. The **From**, **To**, and **Subject** parameters are required by `Send-MailMessage`. This example uses the default `$PSEmailServer` variable for the SMTP server, so the **SmtpServer** parameter is not needed. ```powershell $sendMailMessageSplat = @{ From = 'User01 <user01@fabrikam.com>' To = 'User02 <user02@fabrikam.com>' Subject = 'Test mail' } Send-MailMessage @sendMailMessageSplat ``` The `Send-MailMessage` cmdlet uses the **From** parameter to specify the message's sender. The **To** parameter specifies the message's recipient. The **Subject** parameter uses the text string **Test mail** as the message because the optional **Body** parameter isn't included. ### Example 2: Send an attachment This example sends an email message with an attachment. ```powershell $sendMailMessageSplat = @{ From = 'User01 <user01@fabrikam.com>' To = 'User02 <user02@fabrikam.com>', 'User03 <user03@fabrikam.com>' Subject = 'Sending the Attachment' Body = "Forgot to send the attachment. Sending now." Attachments = '.\data.csv' Priority = 'High' DeliveryNotificationOption = 'OnSuccess', 'OnFailure' SmtpServer = 'smtp.fabrikam.com' } Send-MailMessage @sendMailMessageSplat ``` The `Send-MailMessage` cmdlet uses the **From** parameter to specify the message's sender. The **To** parameter specifies the message's recipients. The **Subject** parameter describes the content of the message. The **Body** parameter is the content of the message. The **Attachments** parameter specifies the file in the current directory that's attached to the email message. The **Priority** parameter sets the message to `High` priority. The **DeliveryNotificationOption** parameter specifies two values, `OnSuccess` and `OnFailure`. The sender will receive email notifications to confirm the success or failure of the message delivery. The **SmtpServer** parameter sets the SMTP server to `smtp.fabrikam.com`. ### Example 3: Send email to a mailing list This example sends an email message to a mailing list. ```powershell $sendMailMessageSplat = @{ From = 'User01 <user01@fabrikam.com>' To = 'ITGroup <itdept@fabrikam.com>' Cc = 'User02 <user02@fabrikam.com>' Bcc = 'ITMgr <itmgr@fabrikam.com>' Subject = "Don't forget today's meeting!" Credential = 'domain01\admin01' UseSsl = $true } Send-MailMessage @sendMailMessageSplat ``` The `Send-MailMessage` cmdlet uses the **From** parameter to specify the message's sender. The **To** parameter specifies the message's recipients. The **Cc** parameter sends a copy of the message to the specified recipient. The **Bcc** parameter sends a blind copy of the message. A blind copy is an email address that's hidden from the other recipients. The **Subject** parameter is the message because the optional **Body** parameter isn't included. The **Credential** parameter specifies a domain administrator's credentials are used to send the message. The **UseSsl** parameter specifies that Secure Socket Layer (SSL) creates a secure connection. ## PARAMETERS ### -Attachments Specifies the path and file names of files to be attached to the email message. You can use this parameter or pipe the paths and file names to `Send-MailMessage`. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: PsPath Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Bcc Specifies the email addresses that receive a copy of the mail but aren't listed as recipients of the message. Enter names (optional) and the email address, such as `Name <someone@fabrikam.com>`. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Body Specifies the content of the email message. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 2 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -BodyAsHtml Specifies that the value of the **Body** parameter contains HTML. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: BAH Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Cc Specifies the email addresses to which a carbon copy (CC) of the email message is sent. Enter names (optional) and the email address, such as `Name <someone@fabrikam.com>`. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as **User01** or **Domain01\User01**. Or, enter a **PSCredential** object, such as one from the `Get-Credential` cmdlet. Credentials are stored in a [PSCredential](/dotnet/api/system.management.automation.pscredential) object and the password is stored as a [SecureString](/dotnet/api/system.security.securestring). > [!NOTE] > For more information about **SecureString** data protection, see > [How secure is SecureString?](/dotnet/api/system.security.securestring#how-secure-is-securestring). ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Current user Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -DeliveryNotificationOption Specifies the delivery notification options for the email message. You can specify multiple values. None is the default value. The alias for this parameter is **DNO**. The delivery notifications are sent to the address in the **From** parameter. The acceptable values for this parameter are as follows: - `None`: No notification. - `OnSuccess`: Notify if the delivery is successful. - `OnFailure`: Notify if the delivery is unsuccessful. - `Delay`: Notify if the delivery is delayed. - `Never`: Never notify. These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **DeliveryNotification** parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. ```yaml Type: System.Net.Mail.DeliveryNotificationOptions Parameter Sets: (All) Aliases: DNO Accepted values: None, OnSuccess, OnFailure, Delay, Never Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Encoding Specifies the type of encoding for the target file. The default value is `utf8NoBOM`. The acceptable values for this parameter are as follows: - `ascii`: Uses the encoding for the ASCII (7-bit) character set. - `ansi`: Uses the encoding for the for the current culture's ANSI code page. This option was added in PowerShell 7.4. - `bigendianunicode`: Encodes in UTF-16 format using the big-endian byte order. - `bigendianutf32`: Encodes in UTF-32 format using the big-endian byte order. - `oem`: Uses the default encoding for MS-DOS and console programs. - `unicode`: Encodes in UTF-16 format using the little-endian byte order. - `utf7`: Encodes in UTF-7 format. - `utf8`: Encodes in UTF-8 format. - `utf8BOM`: Encodes in UTF-8 format with Byte Order Mark (BOM) - `utf8NoBOM`: Encodes in UTF-8 format without Byte Order Mark (BOM) - `utf32`: Encodes in UTF-32 format. Beginning with PowerShell 6.2, the **Encoding** parameter also allows numeric IDs of registered code pages (like `-Encoding 1251`) or string names of registered code pages (like `-Encoding "windows-1251"`). For more information, see the .NET documentation for [Encoding.CodePage](/dotnet/api/system.text.encoding.codepage?view=netcore-2.2). Starting with PowerShell 7.4, you can use the `Ansi` value for the **Encoding** parameter to pass the numeric ID for the current culture's ANSI code page without having to specify it manually. > [!NOTE] > **UTF-7*** is no longer recommended to use. As of PowerShell 7.1, a warning is written if you > specify `utf7` for the **Encoding** parameter. ```yaml Type: System.Text.Encoding Parameter Sets: (All) Aliases: BE Accepted values: ASCII, BigEndianUnicode, BigEndianUTF32, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 Required: False Position: Named Default value: ASCII Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -From The **From** parameter is required. This parameter specifies the sender's email address. Enter a name (optional) and email address, such as `Name <someone@fabrikam.com>`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Port Specifies an alternate port on the SMTP server. The default value is 25, which is the default SMTP port. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 25 Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Priority Specifies the priority of the email message. Normal is the default. The acceptable values for this parameter are Normal, High, and Low. ```yaml Type: System.Net.Mail.MailPriority Parameter Sets: (All) Aliases: Accepted values: Normal, High, Low Required: False Position: Named Default value: Normal Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ReplyTo Specifies additional email addresses (other than the From address) to use to reply to this message. Enter names (optional) and the email address, such as `Name <someone@fabrikam.com>`. This parameter was introduced in PowerShell 6.2. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -SmtpServer Specifies the name of the SMTP server that sends the email message. The default value is the value of the `$PSEmailServer` preference variable. If the preference variable isn't set and this parameter isn't used, the `Send-MailMessage` command fails. ```yaml Type: System.String Parameter Sets: (All) Aliases: ComputerName Required: False Position: 3 Default value: $PSEmailServer Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Subject The **Subject** parameter isn't required. This parameter specifies the subject of the email message. ```yaml Type: System.String Parameter Sets: (All) Aliases: sub Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -To The **To** parameter is required. This parameter specifies the recipient's email address. Enter names (optional) and the email address, such as `Name <someone@fabrikam.com>`. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -UseSsl The Secure Sockets Layer (SSL) protocol is used to establish a secure connection to the remote computer to send mail. By default, SSL isn't used. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe the path and file names of attachments to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES The `Send-MailMessage` cmdlet is obsolete. For more information, see [Platform Compatibility note DE0005](https://aka.ms/SendMailMessage). This cmdlet doesn't guarantee secure connections to SMTP servers. _DE0005_ suggests using the third-party library, [MailKit](https://github.com/jstedfast/MailKit). If you are using Exchange Online, you can use the [Send-MgUserMail](/powershell/module/microsoft.graph.users.actions/send-mgusermail) from the Microsoft Graph PowerShell SDK. ## RELATED LINKS [about_Preference_Variables](../Microsoft.PowerShell.Core/About/about_Preference_Variables.md) [Get-Credential](../Microsoft.PowerShell.Security/Get-Credential.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Set-Alias.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 10/25/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/set-alias?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-Alias --- # Set-Alias ## SYNOPSIS Creates or changes an alias for a cmdlet or other command in the current PowerShell session. ## SYNTAX ### Default (Default) ``` Set-Alias [-Name] <string> [-Value] <string> [-Description <string>] [-Option <ScopedItemOptions>] [-PassThru] [-Scope <string>] [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Set-Alias` cmdlet creates or changes an alias for a cmdlet or a command, such as a function, script, file, or other executable. An alias is an alternate name that refers to a cmdlet or command. For example, `sal` is the alias for the `Set-Alias` cmdlet. For more information, see [about_Aliases](../Microsoft.PowerShell.Core/About/about_Aliases.md). A cmdlet can have multiple aliases, but an alias can only be associated with one cmdlet. You can use `Set-Alias` to reassign an existing alias to another cmdlet, or change an alias's properties, such as the description. An alias that's created or changed by `Set-Alias` isn't permanent and is only available during the current PowerShell session. When the PowerShell session is closed, the alias is removed. ## EXAMPLES ### Example 1: Create an alias for a cmdlet This command creates an alias to a cmdlet in the current PowerShell session. ``` PS> Set-Alias -Name list -Value Get-ChildItem PS> Get-Alias -Name list CommandType Name ----------- ---- Alias list -> Get-ChildItem ``` The `Set-Alias` cmdlet creates an alias in the current PowerShell session. The **Name** parameter specifies the alias's name, `list`. The **Value** parameter specifies the cmdlet that the alias runs. To run the alias, type `list` on the PowerShell command line. ### Example 2: Reassign an existing alias to a different cmdlet This command reassigns an existing alias to run a different cmdlet. ``` PS> Get-Alias -Name list CommandType Name ----------- ---- Alias list -> Get-ChildItem PS> Set-Alias -Name list -Value Get-Location PS> Get-Alias -Name list CommandType Name ----------- ---- Alias list -> Get-Location ``` The `Get-Alias` cmdlet uses the **Name** parameter to display the `list` alias. The `list` alias is associated with the `Get-ChildItem` cmdlet. When the `list` alias is run, the items in the current directory are displayed. The `Set-Alias` cmdlet uses the **Name** parameter to specify the `list` alias. The **Value** parameter associates the alias to the `Get-Location` cmdlet. The `Get-Alias` cmdlet uses the **Name** parameter to display the `list` alias. The `list` alias is associated with the `Get-Location` cmdlet. When the `list` alias is run, the current directory's location is displayed. ### Example 3: Create and change a read-only alias This command creates a read-only alias. The read-only option prevents unintended changes to an alias. To change or delete a read-only alias, use the **Force** parameter. ```powershell Set-Alias -Name loc -Value Get-Location -Option ReadOnly -PassThru | Format-List -Property * ``` ```Output DisplayName : loc -> Get-Location Definition : Get-Location Options : ReadOnly Description : Name : loc CommandType : Alias ``` ```powershell $Parameters = @{ Name = 'loc' Value = (Get-Location) Option = 'ReadOnly' Description = 'Displays the current directory' Force = $true PassThru = $true } Set-Alias @Parameters | Format-List -Property * ``` ```Output DisplayName : loc -> Get-Location Definition : Get-Location Options : ReadOnly Description : Displays the current directory Name : loc CommandType : Alias ``` The `Set-Alias` cmdlet creates an alias in the current PowerShell session. The **Name** parameter specifies the alias's name, `loc`. The **Value** parameter specifies the `Get-Location` cmdlet that the alias runs. The **Option** parameter specifies the **ReadOnly** value. The **PassThru** parameter represents the alias object and sends the object down the pipeline to the `Format-List` cmdlet. `Format-List` uses the **Property** parameter with an asterisk (`*`) so that every property is displayed. The example output shows a partial list of those properties. The `loc` alias is changed with the addition of two parameters. **Description** adds text to explain the alias's purpose. The **Force** parameter is needed because the `loc` alias is read-only. If the **Force** parameter isn't used, the change fails. ### Example 4: Create an alias to an executable file This example creates an alias to an executable file on the local computer. ``` PS> Set-Alias -Name np -Value C:\Windows\notepad.exe PS> Get-Alias -Name np CommandType Name ----------- ---- Alias np -> notepad.exe ``` The `Set-Alias` cmdlet creates an alias in the current PowerShell session. The **Name** parameter specifies the alias's name, `np`. The **Value** parameter specifies the path and application name `C:\Windows\notepad.exe`. The `Get-Alias` cmdlet uses the **Name** parameter to show that the `np` alias is associated with `notepad.exe`. To run the alias, type `np` on the PowerShell command line to open `notepad.exe`. ### Example 5: Create an alias for a command with parameters This example shows how to assign an alias to a command with parameters. You can create an alias for a cmdlet, such as `Set-Location`. You can't create an alias for a command with parameters and values, such as `Set-Location -Path C:\Windows\System32`. To create an alias for a command, create a function that includes the command, and then create an alias to the function. For more information, see [about_Functions](../Microsoft.PowerShell.Core/about/about_Functions.md). ``` function CD32 {Set-Location -Path C:\Windows\System32} Set-Alias -Name Go -Value CD32 ``` A function named `CD32` is created. The function uses the `Set-Location` cmdlet with the **Path** parameter to specify the directory, `C:\Windows\System32`. The `Set-Alias` cmdlet creates an alias to the function in the current PowerShell session. The **Name** parameter specifies the alias's name, `Go`. The **Value** parameter specifies the function's name, `CD32`. To run the alias, type `Go` on the PowerShell command line. The `CD32` function runs and changes to the directory `C:\Windows\System32`. ### Example 6: Update options for an existing alias This example shows how to assign multiple options using the **Option** parameter. Continuing from the previous example, set the alias `Go` as `ReadOnly` and `Private`. ```powershell Set-Alias -Name Go -Option ReadOnly, Private ``` The alias `Go` should already exist. After running the command, the alias can't be changed without using the **Force** parameter and is only available in the current scope. ## PARAMETERS ### -Description Specifies a description of the alias. You can type any string. If the description includes spaces, enclose it in single quotation marks. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Use the **Force** parameter to change or delete an alias that has the **Option** parameter set to **ReadOnly**. The **Force** parameter can't change or delete an alias with the **Option** parameter set to **Constant**. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies the name of a new alias. An alias name can contain alphanumeric characters and hyphens. Alias names can't be numeric, such as 123. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Option Sets the **Option** property value of the alias. Values such as `ReadOnly` and `Constant` protect an alias from unintended changes. To see the **Option** property of all aliases in the session, type `Get-Alias | Format-Table -Property Name, Options -AutoSize`. The acceptable values for this parameter are as follows: - `AllScope` - The alias is copied to any new scopes that are created. - `Constant` - Can't be changed or deleted. - `None` - Sets no options and is the default. - `Private` - The alias is available only in the current scope. - `ReadOnly` - Can't be changed or deleted unless the **Force** parameter is used. - `Unspecified` These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **Option** parameter as an array of values or as a comma-separated string of those values. The cmdlet combines the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. ```yaml Type: System.Management.Automation.ScopedItemOptions Parameter Sets: (All) Aliases: Accepted values: AllScope, Constant, None, Private, ReadOnly, Unspecified Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns an object that represents the alias. Use a format cmdlet such as `Format-List` to display the object. By default, `Set-Alias` doesn't generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Scope Specifies the scope this alias is valid in. The default value is **Local**. For more information, see [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md). The acceptable values are as follows: - `Global` - `Local` - `Private` - `Numbered scopes` - `Script` ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: Global, Local, Private, Numbered scopes, Script Required: False Position: Named Default value: Local Accept pipeline input: False Accept wildcard characters: False ``` ### -Value Specifies the name of the cmdlet or command that the alias runs. The **Value** parameter is the alias's **Definition** property. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.AliasInfo When you use the **PassThru** parameter, this cmdlet returns an **AliasInfo** object representing the alias. ## NOTES PowerShell includes the following aliases for `Set-Alias`: - All platforms: - `sal` PowerShell includes built-in aliases that are available in each PowerShell session. The `Get-Alias` cmdlet displays the aliases available in a PowerShell session. To create an alias, use the cmdlets `Set-Alias` or `New-Alias`. In PowerShell 6, to delete an alias, use the `Remove-Alias` cmdlet. `Remove-Item` is accepted for backwards compatibility such as for scripts created with prior versions of PowerShell. Use a command such as `Remove-Item -Path Alias:AliasName`. To create an alias that's available in each PowerShell session, add it to your PowerShell profile. For more information, see [about_Profiles](../Microsoft.PowerShell.Core/About/about_Profiles.md). An alias can be saved and reused in another PowerShell session by doing an export and import. To save an alias to a file, use `Export-Alias`. To add a saved alias to a new PowerShell session, use `Import-Alias`. ## RELATED LINKS [about_Aliases](../Microsoft.PowerShell.Core/About/about_Aliases.md) [about_Functions](../Microsoft.PowerShell.Core/about/about_Functions.md) [about_Profiles](../Microsoft.PowerShell.Core/About/about_Profiles.md) [about_Scopes](../Microsoft.PowerShell.Core/About/about_Scopes.md) [Export-Alias](Export-Alias.md) [Get-Alias](Get-Alias.md) [Import-Alias](Import-Alias.md) [New-Alias](New-Alias.md) [Remove-Alias](Remove-Alias.md) [Remove-Item](../Microsoft.PowerShell.Management/Remove-Item.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Set-Date.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 06/10/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/set-date?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-Date --- # Set-Date ## SYNOPSIS Changes the system time on the computer to a time that you specify. ## SYNTAX ### Date (Default) ``` Set-Date [-Date] <DateTime> [-DisplayHint <DisplayHintType>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Adjust ``` Set-Date [-Adjust] <TimeSpan> [-DisplayHint <DisplayHintType>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Set-Date` cmdlet changes the system date and time on the computer to a date and time that you specify. You can specify a new date and/or time by typing a string or by passing a **DateTime** or **TimeSpan** object to `Set-Date`. To specify a new date or time, use the **Date** parameter. To specify a change interval, use the **Adjust** parameter. You must have administrative rights to change the system date and time. On Windows, start PowerShell with the **Run as administrator** option. ## EXAMPLES ### Example 1: Add three days to the system date This command adds three days to the current system date. It doesn't affect the time. The command uses the **Date** parameter to specify the date. The `Get-Date` cmdlet returns the current date as a **DateTime** object. The **DateTime** object's **AddDays** method adds a specified number of days (`3`) to the current **DateTime** object. ```powershell Set-Date -Date (Get-Date).AddDays(3) ``` ### Example 2: Set the system clock back 10 minutes This example sets the current system time back by 10 minutes. The **Adjust** parameter allows you to specify an interval of change (minus ten minutes) in the standard time format for the locale. The **DisplayHint** parameter tells PowerShell to display only the time, but it doesn't affect the **DateTime** object that `Set-Date` returns. ```powershell Set-Date -Adjust -0:10:0 -DisplayHint Time ``` ### Example 3: Set the date and time to a variable value These commands change the system date and time on local computer to the date and time saved in the variable `$T`. The first command gets the date and stores it in `$T`. The second command uses the **Date** parameter to pass the **DateTime** object in `$T` to the `Set-Date` cmdlet. ```powershell $T = Get-Date Set-Date -Date $T ``` ### Example 4: Add 90 minutes to the system clock These commands advance the system time on the local computer by 90 minutes. The first command uses the `New-TimeSpan` cmdlet to create a **TimeSpan** object with a 90-minute interval, and saves it in the `$90mins` variable. The second command uses the **Adjust** parameter of `Set-Date` to adjust the date by the value of the **TimeSpan** object in the `$90mins` variable. ```powershell $90mins = New-TimeSpan -Minutes 90 Set-Date -Adjust $90mins ``` ### 5: Change to a specific date and time The following example sets the date and time to a specific value. ```powershell PS> Get-Date Monday, June 10, 2024 2:05:48 PM PS> Set-Date '6/11/2024 2:05:48 PM' Tuesday, June 11, 2024 2:05:48 PM ``` ## PARAMETERS ### -Adjust Specifies the value for which this cmdlet adds or subtracts from the current date and time. You can type an adjustment in standard date and time format for your locale or use the **Adjust** parameter to pass a **TimeSpan** object from `New-TimeSpan` to `Set-Date`. ```yaml Type: System.TimeSpan Parameter Sets: Adjust Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Date Changes the date and time to the specified values. You can type a new date in the short date format and a time in the standard time format for your locale. Or, you can pass a **DateTime** object from `Get-Date`. If you specify a date, but not a time, `Set-Date` changes the time to midnight on the specified date. If you specify only a time, it doesn't change the date. ```yaml Type: System.DateTime Parameter Sets: Date Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -DisplayHint Specifies which elements of the date and time are displayed. The acceptable values for this parameter are: - `Date` - displays only the date. - `Time` - displays only the time. - `DateTime` - displays the date and time. This parameter affects only the display. It doesn't affect the **DateTime** object that `Get-Date` retrieves. ```yaml Type: Microsoft.PowerShell.Commands.DisplayHintType Parameter Sets: (All) Aliases: Accepted values: Date, Time, DateTime Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.DateTime You can pipe a date to this cmdlet. ## OUTPUTS ### System.DateTime This cmdlet returns an object that represents the date that it set. ## NOTES - Use this cmdlet cautiously when changing the date and time on the computer. The change might prevent the computer from receiving system-wide events and updates that are triggered by a date or time. Use the **WhatIf** and **Confirm** parameters to avoid errors. - You can use standard .NET methods with the **DateTime** and **TimeSpan** objects used with `Set-Date`, such as **AddDays**, **AddMonths**, and **FromFileTime**. For more information, see [DateTime Methods](/dotnet/api/system.datetime) and [TimeSpan Methods](/dotnet/api/system.timespan) in the .NET SDK. ## RELATED LINKS [Get-Date](Get-Date.md) [New-TimeSpan](New-TimeSpan.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Set-MarkdownOption.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/30/2020 online version: https://learn.microsoft.com/powershell/module/Microsoft.PowerShell.Utility/Set-MarkdownOption?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-MarkdownOption --- # Set-MarkdownOption ## SYNOPSIS Sets the colors and styles used for rendering Markdown content in the console. ## SYNTAX ### IndividualSetting (Default) ``` Set-MarkdownOption [-Header1Color <String>] [-Header2Color <String>] [-Header3Color <String>] [-Header4Color <String>] [-Header5Color <String>] [-Header6Color <String>] [-Code <String>] [-ImageAltTextForegroundColor <String>] [-LinkForegroundColor <String>] [-ItalicsForegroundColor <String>] [-BoldForegroundColor <String>] [-PassThru] [<CommonParameters>] ``` ### Theme ``` Set-MarkdownOption [-PassThru] -Theme <String> [<CommonParameters>] ``` ### InputObject ``` Set-MarkdownOption [-PassThru] [-InputObject] <PSObject> [<CommonParameters>] ``` ## DESCRIPTION Sets the colors and styles used for rendering Markdown content in the console. These styles are defined using ANSI escape codes that change the color and style of the Markdown text being rendered. For more information about Markdown, see the [CommonMark](https://commonmark.org/) website. > [!NOTE] > The string values used in the settings are the characters that follow the **Escape** character > (`[char]0x1B`) for the ANSI escape sequence. Do not include the **Escape** character in the > string. For more information about ANSI escape codes work, see > [ANSI_escape_code](https://en.wikipedia.org/wiki/ANSI_escape_code). ## EXAMPLES ### Example 1 - Switch to the Light Theme This example selects the **Light** theme and displays the new configuration using the **PassThru** parameter. ```powershell Set-MarkdownOption -Theme Light -PassThru ``` ```Output Header1 : [7m Header2 : [4;33m Header3 : [4;34m Header4 : [4;35m Header5 : [4;36m Header6 : [4;30m Code : [48;2;155;155;155;38;2;30;30;30m Link : [4;38;5;117m Image : [33m EmphasisBold : [1m EmphasisItalics : [36m ``` ### Example 2 - Customize the color and style settings This example changes the escape code for the Markdown headers. The default configuration for headers renders them as underlined text of various colors. This change removes the underline style. ```powershell $mdOptions = Get-MarkdownOption $mdOptions.Header2 = '[93m' $mdOptions.Header3 = '[94m' $mdOptions.Header4 = '[95m' $mdOptions.Header5 = '[96m' $mdOptions.Header6 = '[97m' Set-MarkdownOption -InputObject $mdOptions -PassThru ``` ```Output Header1 : [7m Header2 : [93m Header3 : [94m Header4 : [95m Header5 : [96m Header6 : [97m Code : [48;2;155;155;155;38;2;30;30;31m Link : [4;38;5;117m Image : [33m EmphasisBold : [1m EmphasisItalics : [36m ``` ## PARAMETERS ### -BoldForegroundColor Sets the foreground color for rendering bold Markdown text. ```yaml Type: System.String Parameter Sets: IndividualSetting Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Code Sets the color for rendering code blocks and spans in Markdown text. ```yaml Type: System.String Parameter Sets: IndividualSetting Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Header1Color Sets the color for rendering Header1 blocks in Markdown text. ```yaml Type: System.String Parameter Sets: IndividualSetting Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Header2Color Sets the color for rendering Header2 blocks in Markdown text. ```yaml Type: System.String Parameter Sets: IndividualSetting Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Header3Color Sets the color for rendering Header3 blocks in Markdown text. ```yaml Type: System.String Parameter Sets: IndividualSetting Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Header4Color Sets the color for rendering Header4 blocks in Markdown text. ```yaml Type: System.String Parameter Sets: IndividualSetting Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Header5Color Sets the color for rendering Header5 blocks in Markdown text. ```yaml Type: System.String Parameter Sets: IndividualSetting Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Header6Color Sets the color for rendering Header6 blocks in Markdown text. ```yaml Type: System.String Parameter Sets: IndividualSetting Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ImageAltTextForegroundColor Sets the foreground color for rendering the alternate text of an image element in Markdown text. ```yaml Type: System.String Parameter Sets: IndividualSetting Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject A **PSMarkdownOptionInfo** object containing the configuration to be set. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: InputObject Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -ItalicsForegroundColor Sets the foreground color for rendering the italics in Markdown text. ```yaml Type: System.String Parameter Sets: IndividualSetting Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LinkForegroundColor Sets the foreground color for rendering hyperlinks in Markdown text. ```yaml Type: System.String Parameter Sets: IndividualSetting Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Causes the cmdlet to output a **PSMarkdownOptionInfo** object containing the new configuration. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Theme Selects a theme containing predefined color settings. The possible values are **Dark** and **Light**. ```yaml Type: System.String Parameter Sets: Theme Aliases: Accepted values: Dark, Light Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject ## OUTPUTS ### Microsoft.PowerShell.MarkdownRender.PSMarkdownOptionInfo ## NOTES The string values used to define the color and style must match the regular expression `^\[*[0-9;]*?m{1}`. ## RELATED LINKS [Get-MarkdownOption](Get-MarkdownOption.md) [ConvertFrom-Markdown](ConvertFrom-Markdown.md) [Show-Markdown](Show-Markdown.md) [ANSI_escape_code](https://en.wikipedia.org/wiki/ANSI_escape_code) [CommonMark](https://commonmark.org/)

#File: reference/7.6/Microsoft.PowerShell.Utility/Set-PSBreakpoint.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/20/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/set-psbreakpoint?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-PSBreakpoint --- # Set-PSBreakpoint ## SYNOPSIS Sets a breakpoint on a line, command, or variable. ## SYNTAX ### Line (Default) ``` Set-PSBreakpoint [-Action <ScriptBlock>] [[-Column] <Int32>] [-Line] <Int32[]> [-Script] <String[]> [-Runspace <Runspace>] [<CommonParameters>] ``` ### Command ``` Set-PSBreakpoint [-Action <ScriptBlock>] -Command <String[]> [[-Script] <String[]>] [-Runspace <Runspace>] [<CommonParameters>] ``` ### Variable ``` Set-PSBreakpoint [-Action <ScriptBlock>] [[-Script] <String[]>] -Variable <String[]> [-Mode <VariableAccessMode>] [-Runspace <Runspace>] [<CommonParameters>] ``` ## DESCRIPTION The `Set-PSBreakpoint` cmdlet sets a breakpoint in a script or in any command run in the current session. You can use `Set-PSBreakpoint` to set a breakpoint before executing a script or running a command, or during debugging, when stopped at another breakpoint. `Set-PSBreakpoint` cannot set a breakpoint on a remote computer. To debug a script on a remote computer, copy the script to the local computer and then debug it locally. Each `Set-PSBreakpoint` command creates one of the following three types of breakpoints: - Line breakpoint - Sets breakpoints at particular line and column coordinates. - Command breakpoint - Sets breakpoints on commands and functions. - Variable breakpoint - Sets breakpoints on variables. You can set a breakpoint on multiple lines, commands, or variables in a single `Set-PSBreakpoint` command, but each `Set-PSBreakpoint` command sets only one type of breakpoint. At a breakpoint, PowerShell temporarily stops executing and gives control to the debugger. The command prompt changes to `DBG\>`, and a set of debugger commands become available for use. However, you can use the **Action** parameter to specify an alternate response, such as conditions for the breakpoint or instructions to perform additional tasks such as logging or diagnostics. The `Set-PSBreakpoint` cmdlet is one of several cmdlets designed for debugging PowerShell scripts. For more information about the PowerShell debugger, see [about_Debuggers](../Microsoft.PowerShell.Core/About/about_Debuggers.md). ## EXAMPLES ### Example 1: Set a breakpoint on a line This example sets a breakpoint at line 5 in the Sample.ps1 script. When the script runs, execution stops immediately before line 5 would execute. ```powershell Set-PSBreakpoint -Script "sample.ps1" -Line 5 ``` ```output Column : 0 Line : 5 Action : Enabled : True HitCount : 0 Id : 0 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 ``` When you set a new breakpoint by line number, the `Set-PSBreakpoint` cmdlet generates a line breakpoint object (**System.Management.Automation.LineBreakpoint**) that includes the breakpoint ID and hit count. ### Example 2: Set a breakpoint on a function This example creates a command breakpoint on the `Increment` function in the Sample.ps1 cmdlet. The script stops executing immediately before each call to the specified function. ```powershell Set-PSBreakpoint -Command "Increment" -Script "sample.ps1" ``` ```Output Command : Increment Action : Enabled : True HitCount : 0 Id : 1 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 ``` The result is a command breakpoint object. Before the script runs, the value of the **HitCount** property is 0. ### Example 3: Set a breakpoint on a variable This example sets a breakpoint on the **Server** variable in the Sample.ps1 script. It uses the **Mode** parameter with a value of **ReadWrite** to stop execution when the value of the variable is read and just before the value changes. ```powershell Set-PSBreakpoint -Script "sample.ps1" -Variable "Server" -Mode ReadWrite ``` ### Example 4: Set a breakpoint on every command that begins with specified text This example sets a breakpoint on every command in the Sample.ps1 script that begins with "write", such as `Write-Host`. ```powershell Set-PSBreakpoint -Script Sample.ps1 -Command "write*" ``` ### Example 5: Set a breakpoint depending on the value of a variable This example stops execution at the `DiskTest` function in the `Test.ps1` script only when the value of the `$Disk` variable is greater than 2. ```powershell Set-PSBreakpoint -Script "test.ps1" -Command "DiskTest" -Action { if ($Disk -gt 2) { break } } ``` The value of the **Action** is a script block that tests the value of the `$Disk` variable in the function. The action uses the `break` keyword to stop execution if the condition is met. The alternative (and the default) is **Continue**. ### Example 6: Set a breakpoint on a function This example sets a breakpoint on the `CheckLog` function. Because the command does not specify a script, the breakpoint is set on anything that runs in the current session. The debugger breaks when the function is called, not when it is declared. ``` PS> Set-PSBreakpoint -Command "CheckLog" Id : 0 Command : CheckLog Enabled : True HitCount : 0 Action : function CheckLog { >> Get-EventLog -Log Application | >> Where-Object {($_.Source -like "TestApp") -and ($_.Message -like "*failed*")} >>} >> PS> CheckLog DEBUG: Hit breakpoint(s) DEBUG: Function breakpoint on 'prompt:CheckLog' ``` ### Example 7: Set breakpoints on multiple lines This example sets three line breakpoints in the Sample.ps1 script. It sets one breakpoint at column 2 on each of the lines specified in the script. The action specified in the **Action** parameter applies to all breakpoints. ```powershell PS C:\> Set-PSBreakpoint -Script "sample.ps1" -Line 1, 14, 19 -Column 2 -Action {&(log.ps1)} ``` ```Output Column : 2 Line : 1 Action : Enabled : True HitCount : 0 Id : 6 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 Column : 2 Line : 14 Action : Enabled : True HitCount : 0 Id : 7 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 Column : 2 Line : 19 Action : Enabled : True HitCount : 0 Id : 8 Script : C:\ps-test\sample.ps1 ScriptName : C:\ps-test\sample.ps1 ``` ### Example 8: Set a breakpoint in a runspace In this example, a job is started. The runspace is stored in a variable and passed to the `Set-PSBreakpoint` command with the **Runspace** parameter. ```powershell Start-Job -ScriptBlock { Start-Sleep -Seconds 10 } $runspace = Get-Runspace -Id 1 Set-PSBreakpoint -Command Start-Sleep -Runspace $runspace ``` ## PARAMETERS ### -Action Specifies commands that run at each breakpoint instead of breaking. Enter a script block that contains the commands. You can use this parameter to set conditional breakpoints or to perform other tasks, such as testing or logging. If this parameter is omitted, or no action is specified, execution stops at the breakpoint, and the debugger starts. When the **Action** parameter is used, the Action script block runs at each breakpoint. Execution does not stop unless the script block includes the `break` keyword. If you use the `continue` keyword in the script block, execution resumes until the next breakpoint. For more information, see [about_Script_Blocks](../Microsoft.PowerShell.Core/About/about_Script_Blocks.md), [about_Break](../Microsoft.PowerShell.Core/About/about_Break.md), and [about_Continue](../Microsoft.PowerShell.Core/About/about_Continue.md). ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Column Specifies the column number of the column in the script file on which execution stops. Enter only one column number. The default is column 1. The Column value is used with the value of the **Line** parameter to specify the breakpoint. If the **Line** parameter specifies multiple lines, the **Column** parameter sets a breakpoint at the specified column on each of the specified lines. PowerShell stops executing before the statement or expression that includes the character at the specified line and column position. Columns are counted from the top left margin beginning with column number 1 (not 0). If you specify a column that does not exist in the script, an error is not declared, but the breakpoint is never executed. ```yaml Type: System.Int32 Parameter Sets: Line Aliases: Required: False Position: 2 Default value: 1 Accept pipeline input: False Accept wildcard characters: False ``` ### -Command Sets a command breakpoint. Enter cmdlet names, such as `Get-Process`, or function names. Wildcards are permitted. Execution stops just before each instance of each command is executed. If the command is a function, execution stops each time the function is called and at each `begin`, `process`, and `end` block. ```yaml Type: System.String[] Parameter Sets: Command Aliases: C Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Line Sets a line breakpoint in a script. Enter one or more line numbers, separated by commas. PowerShell stops immediately before executing the statement that begins on each of the specified lines. Lines are counted from the top left margin of the script file beginning with line number 1 (not 0). If you specify a blank line, execution stops before the next non-blank line. If the line is out of range, the breakpoint is never hit. ```yaml Type: System.Int32[] Parameter Sets: Line Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Mode Specifies the mode of access that triggers variable breakpoints. The default is **Write**. This parameter is valid only when the **Variable** parameter is used in the command. The mode applies to all breakpoints set in the command. The acceptable values for this parameter are: - **Write** - Stops execution immediately before a new value is written to the variable. - **Read** - Stops execution when the variable is read, that is, when its value is accessed, either to be assigned, displayed, or used. In read mode, execution does not stop when the value of the variable changes. - **ReadWrite** - Stops execution when the variable is read or written. ```yaml Type: System.Management.Automation.VariableAccessMode Parameter Sets: Variable Aliases: Accepted values: Read, Write, ReadWrite Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Runspace Specifies the Id of a **Runspace** object so you can interact with breakpoints in the specified runspace. This parameter was added in PowerShell 7.2. ```yaml Type: Runspace Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Script Specifies an array of script files that this cmdlet sets a breakpoint in. Enter the paths and file names of one or more script files. If the files are in the current directory, you can omit the path. Wildcards are permitted. By default, variable breakpoints and command breakpoints are set on any command that runs in the current session. This parameter is required only when setting a line breakpoint. ```yaml Type: System.String[] Parameter Sets: Line, Command, Variable Aliases: Required: True (Line), False (Command, Variable) Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Variable Specifies an array of variables that this cmdlet sets breakpoints on. Enter a comma-separated list of variables without dollar signs (`$`). Use the **Mode** parameter to determine the mode of access that triggers the breakpoints. The default mode, Write, stops execution just before a new value is written to the variable. ```yaml Type: System.String[] Parameter Sets: Variable Aliases: V Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.CommandBreakpoint ### System.Management.Automation.LineBreakpoint ### System.Management.Automation.VariableBreakpoint `Set-PSBreakpoint` returns an object that represents each breakpoint that it sets. ## NOTES PowerShell includes the following aliases for `Set-PSBreakpoint`: - All platforms: - `sbp` - `Set-PSBreakpoint` cannot set a breakpoint on a remote computer. To debug a script on a remote computer, copy the script to the local computer and then debug it locally. - When you set a breakpoint on more than one line, command, or variable, `Set-PSBreakpoint` generates a breakpoint object for each entry. - When setting a breakpoint on a function or variable at the command prompt, you can set the breakpoint before or after you create the function or variable. ## RELATED LINKS [Disable-PSBreakpoint](Disable-PSBreakpoint.md) [Enable-PSBreakpoint](Enable-PSBreakpoint.md) [Get-PSBreakpoint](Get-PSBreakpoint.md) [Get-PSCallStack](Get-PSCallStack.md) [Remove-PSBreakpoint](Remove-PSBreakpoint.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Set-TraceSource.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/set-tracesource?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-TraceSource --- # Set-TraceSource ## SYNOPSIS Configures, starts, and stops a trace of PowerShell components. ## SYNTAX ### optionsSet (Default) ``` Set-TraceSource [-Name] <String[]> [[-Option] <PSTraceSourceOptions>] [-ListenerOption <TraceOptions>] [-FilePath <String>] [-Force] [-Debugger] [-PSHost] [-PassThru] [<CommonParameters>] ``` ### removeAllListenersSet ``` Set-TraceSource [-Name] <String[]> [-RemoveListener <String[]>] [<CommonParameters>] ``` ### removeFileListenersSet ``` Set-TraceSource [-Name] <String[]> [-RemoveFileListener <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Set-TraceSource` cmdlet configures, starts, and stops a trace of a PowerShell component. You can use it to specify which components will be traced and where the tracing output is sent. ## EXAMPLES ### Example 1: Trace the ParameterBinding component ``` Set-TraceSource -Name "ParameterBinding" -Option ExecutionFlow -PSHost -ListenerOption "ProcessId,TimeStamp" ``` This command starts tracing for the ParameterBinding component of PowerShell. It uses the **Name** parameter to specify the trace source, the **Option** parameter to select the `ExecutionFlow` trace events, and the **PSHost** parameter to select the PowerShell host listener, which sends the output to the console. The **ListenerOption** parameter adds the `ProcessId` and `TimeStamp` values to the trace message prefix. ### Example 2: Stop a trace ``` Set-TraceSource -Name "ParameterBinding" -RemoveListener "Host" ``` This command stops the trace of the **ParameterBinding** component of PowerShell. It uses the **Name** parameter to identify the component that was being traced and the **RemoveListener** parameter to identify the trace listener. ## PARAMETERS ### -Debugger Indicates that the cmdlet sends the trace output to the debugger. You can view the output in any user-mode or kernel mode debugger or in Microsoft Visual Studio. This parameter also selects the default trace listener. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: optionsSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FilePath Specifies a file that this cmdlet sends the trace output to. This parameter also selects the file trace listener. If you use this parameter to start the trace, use the **RemoveFileListener** parameter to stop the trace. ```yaml Type: System.String Parameter Sets: optionsSet Aliases: PSPath, Path Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Indicates that the cmdlet overwrites a read-only file. Use with the **FilePath** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: optionsSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ListenerOption Specifies optional data to the prefix of each trace message in the output. The acceptable values for this parameter are: - `None` - `LogicalOperationStack` - `DateTime` - `Timestamp` - `ProcessId` - `ThreadId` - `Callstack` `None` is the default. These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **ListenerOption** parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. ```yaml Type: System.Diagnostics.TraceOptions Parameter Sets: optionsSet Aliases: Accepted values: None, LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies which components are traced. Enter the name of the trace source of each component. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: True ``` ### -Option Specifies the type of events that are traced. The acceptable values for this parameter are: - `None` - `Constructor` - `Dispose` - `Finalizer` - `Method` - `Property` - `Delegates` - `Events` - `Exception` - `Lock` - `Error` - `Errors` - `Warning` - `Verbose` - `WriteLine` - `Data` - `Scope` - `ExecutionFlow` - `Assert` - `All` `None` is the default. The following values are combinations of other values: - `ExecutionFlow`: `Constructor`, `Dispose`, `Finalizer`, `Method`, `Delegates`, `Events`, `Scope` - `Data`: `Constructor`, `Dispose`, `Finalizer`, `Property`, `Verbose`, `WriteLine` - `Errors`: `Error`, `Exception` These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **Option** parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. ```yaml Type: System.Management.Automation.PSTraceSourceOptions Parameter Sets: optionsSet Aliases: Accepted values: None, Constructor, Dispose, Finalizer, Method, Property, Delegates, Events, Exception, Lock, Error, Errors, Warning, Verbose, WriteLine, Data, Scope, ExecutionFlow, Assert, All Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: optionsSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PSHost Indicates that this cmdlet sends the trace output to the PowerShell host. This parameter also selects the PSHost trace listener. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: optionsSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RemoveFileListener Stops the trace by removing the file trace listener associated with the specified file. Enter the path and file name of the trace output file. ```yaml Type: System.String[] Parameter Sets: removeFileListenersSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RemoveListener Stops the trace by removing the trace listener. Use the following values with **RemoveListener**: - To remove PSHost (console), type `Host`. - To remove Debugger, type `Debug`. - To remove all trace listeners, type `*`. To remove the file trace listener, use the **RemoveFileListener** parameter. ```yaml Type: System.String[] Parameter Sets: removeAllListenersSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a name to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSTraceSource When you use the **PassThru** parameter, this cmdlet returns a **PSTraceSource** object representing the trace session. ## NOTES - Tracing is a method that developers use to debug and refine programs. When tracing, the program generates detailed messages about each step in its internal processing. The PowerShell tracing cmdlets are designed to help PowerShell developers, but they are available to all users. They let you monitor nearly every aspect of the functionality of PowerShell. A trace source is the part of each PowerShell component that manages tracing and generates trace messages for the component. To trace a component, you identify its trace source. A trace listener receives the output of the trace and displays it to the user. You can elect to send the trace data to a user-mode or kernel-mode debugger, to the console, to a file, or to a custom listener derived from the **System.Diagnostics.TraceListener** class. - To start a trace, use the **Name** parameter to specify a trace source and the **FilePath**, **Debugger**, or **PSHost** parameters to specify a listener (a destination for the output). Use the **Options** parameter to determine the types of events that are traced and the **ListenerOption** parameter to configure the trace output. - To change the configuration of a trace, enter a `Set-TraceSource` command as you would to start a trace. PowerShell recognizes that the trace source is already being traced. It stops the trace, adds the new configuration, and starts or restarts the trace. - To stop a trace, use the **RemoveListener** parameter. To stop a trace that uses the file listener (a trace started by using the **FilePath** parameter), use the **RemoveFileListener** parameter. When you remove the listener, the trace stops. - To determine which components can be traced, use Get-TraceSource. The trace sources for each module are loaded automatically when the component is in use, and they appear in the output of `Get-TraceSource`. ## RELATED LINKS [Get-TraceSource](Get-TraceSource.md) [Trace-Command](Trace-Command.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Set-Variable.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/set-variable?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-Variable --- # Set-Variable ## SYNOPSIS Sets the value of a variable. Creates the variable if one with the requested name does not exist. ## SYNTAX ``` Set-Variable [-Name] <String[]> [[-Value] <Object>] [-Include <String[]>] [-Exclude <String[]>] [-Description <String>] [-Option <ScopedItemOptions>] [-Force] [-Visibility <SessionStateEntryVisibility>] [-PassThru] [-Scope <String>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Set-Variable` cmdlet assigns a value to a specified variable or changes the current value. If the variable does not exist, the cmdlet creates it. ## EXAMPLES ### Example 1: Set a variable and get its value These commands set the value of the `$desc` variable to `A description`, and then gets the value of the variable. ```powershell Set-Variable -Name "desc" -Value "A description" Get-Variable -Name "desc" ``` ```Output Name Value ---- ----- desc A description ``` ### Example 2: Set a global, read-only variable This example creates a global, read-only variable that contains all processes on the system, and then it displays all properties of the variable. ```powershell Set-Variable -Name "processes" -Value (Get-Process) -Option Constant -Scope Global -Description "All processes" -PassThru | Format-List -Property * ``` The command uses the `Set-Variable` cmdlet to create the variable. It uses the **PassThru** parameter to create an object representing the new variable, and it uses the pipeline operator (`|`) to pass the object to the `Format-List` cmdlet. It uses the **Property** parameter of `Format-List` with a value of all (`*`) to display all properties of the newly created variable. The value, `(Get-Process)`, is enclosed in parentheses to ensure that it is executed before being stored in the variable. Otherwise, the variable contains the words `Get-Process`. ### Example 3: Understand public vs. private variables This example shows how to change the visibility of a variable to `Private`. This variable can be read and changed by scripts with the required permissions, but it is not visible to the user. ```powershell New-Variable -Name "counter" -Visibility Public -Value 26 $Counter ``` ```Output 26 ``` ```powershell Get-Variable c* ``` ```Output Name Value ---- ----- Culture en-US ConsoleFileName ConfirmPreference High CommandLineParameters {} Counter 26 ``` ```powershell Set-Variable -Name "counter" -Visibility Private Get-Variable c* ``` ```output Name Value ---- ----- Culture en-US ConsoleFileName ConfirmPreference High CommandLineParameters {} ``` ```powershell $counter ``` ```Output "Cannot access the variable '$counter' because it is a private variable" ``` ```powershell .\use-counter.ps1 #Commands completed successfully. ``` This command shows how to change the visibility of a variable to Private. This variable can be read and changed by scripts with the required permissions, but it is not visible to the user. ## PARAMETERS ### -Description Specifies the description of the variable. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Exclude Specifies an array of items that this cmdlet excludes from the operation. The value of this parameter qualifies the **Path** parameter. Enter a path element or pattern, such as `*.txt`. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Allows you to create a variable with the same name as an existing read-only variable, or to change the value of a read-only variable. By default, you can overwrite a variable, unless the variable has an option value of `ReadOnly` or `Constant`. For more information, see the **Option** parameter. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Include Specifies an array of items that this cmdlet includes in the operation. The value of this parameter qualifies the **Name** parameter. Enter a name or name pattern, such as `c*`. Wildcards are permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Name Specifies the variable name. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Option Specifies the value of the **Options** property of the variable. Valid values are: - `None`: Sets no options. (`None` is the default.) - `ReadOnly`: Can be deleted. Cannot be changed, except by using the Force parameter. - `Constant`: Cannot be deleted or changed. `Constant` is valid only when you are creating a variable. You cannot change the options of an existing variable to `Constant`. - `Private`: The variable is available only in the current scope. - `AllScope`: The variable is copied to any new scopes that are created. These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **Option** parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. ```yaml Type: System.Management.Automation.ScopedItemOptions Parameter Sets: (All) Aliases: Accepted values: None, ReadOnly, Constant, Private, AllScope, Unspecified Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns an object representing the new variable. By default, this cmdlet does not generate any output. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Scope Specifies the scope of the variable.The acceptable values for this parameter are: - `Global` - `Local` - `Script` - `Private` - A number relative to the current scope (0 through the number of scopes, where 0 is the current scope and 1 is its parent). `Local` is the default. For more information, see [about_Scopes](../Microsoft.PowerShell.Core/About/about_scopes.md). ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Local Accept pipeline input: False Accept wildcard characters: False ``` ### -Value Specifies the value of the variable. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Visibility Determines whether the variable is visible outside of the session in which it was created. This parameter is designed for use in scripts and commands that will be delivered to other users. Valid values are: - `Public`: The variable is visible. (`Public` is the default.) - `Private`: The variable is not visible. When a variable is private, it does not appear in lists of variables, such as those returned by `Get-Variable`, or in displays of the **Variable:** drive. Commands to read or change the value of a private variable return an error. However, the user can run commands that use a private variable if the commands were written in the session in which the variable was defined. ```yaml Type: System.Management.Automation.SessionStateEntryVisibility Parameter Sets: (All) Aliases: Accepted values: Public, Private Required: False Position: Named Default value: Public Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Object You can pipe an object representing the value of the variable to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.Management.Automation.PSVariable When you use the **PassThru** parameter, this cmdlet returns a **PSVariable** object representing the new or changed variable. ## NOTES PowerShell includes the following aliases for `Set-Variable`: - All platforms: - `set` - `sv` ## RELATED LINKS [Clear-Variable](Clear-Variable.md) [Get-Variable](Get-Variable.md) [New-Variable](New-Variable.md) [Remove-Variable](Remove-Variable.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Show-Command.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/21/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/show-command?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Show-Command --- # Show-Command ## SYNOPSIS Displays PowerShell command information in a graphical window. ## SYNTAX ``` Show-Command [[-Name] <String>] [-Height <Double>] [-Width <Double>] [-NoCommonParameter] [-ErrorPopup] [-PassThru] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Show-Command` cmdlet lets you create a PowerShell command in a command window. You can use the features of the command window to run the command or have it return the command to you. `Show-Command` is a very useful teaching and learning tool. `Show-Command` works on all command types, including cmdlets, functions, workflows and CIM commands. Without parameters, `Show-Command` displays a command window that lists all available commands in all installed modules. To find the commands in a module, select the module from the Modules drop-down list. To select a command, click the command name. To use the command window, select a command, either by using the Name or by clicking the command name in the **Commands** list. Each parameter set is displayed on a separate tab. Asterisks indicate the mandatory parameters. To enter values for a parameter, type the value in the text box or select the value from the drop-down box. To add a switch parameter, click to select the parameter check box. When you're ready, you can click **Copy** to copy the command that you've created to the clipboard or click **Run** to run the command. You can also use the **PassThru** parameter to return the command to the host program, such as the PowerShell console. To cancel the command selection and return to the view that displays all commands, press Ctrl and click the selected command. In the PowerShell Integrated Scripting Environment (ISE), a variation of the `Show-Command` window is displayed by default. For information about using this command window, see the PowerShell ISE Help topics. This cmdlet was reintroduced in PowerShell 7. Because this cmdlet requires a user interface, it does not work on Windows Server Core or Windows Nano Server. This cmdlet is only available on Windows systems that support the Windows Desktop. ## EXAMPLES ### Example 1: Open the Commands window This example displays the default view of the `Show-Command` window. The **Commands** window displays a list of all commands in all modules that are installed on the computer. ```powershell Show-Command ``` ### Example 2: Open a cmdlet in the Commands window This example display the `Invoke-Command` cmdlet in the **Command** window. You can use this display to run `Invoke-Command` commands. ```powershell Show-Command -Name "Invoke-Command" ``` ### Example 3: Open a cmdlet with specified parameters This command opens a `Show-Command` window for the`Connect-PSSession`cmdlet. ```powershell Show-Command -Name "Connect-PSSession" -Height 700 -Width 1000 -ErrorPopup ``` The **Height** and **Width** parameters specify the dimension of the command window. The **ErrorPopup** parameter displays the error command window. When you click **Run**, the `Connect-PSSession` command runs, just as would if you typed the `Connect-PSSession` command at the command line. ### Example 4: Specify new default parameter values for a cmdlet This example uses the `$PSDefaultParameterValues` automatic variable to set new default values for the **Height**, **Width**, and **ErrorPopup** parameters of the `Show-Command` cmdlet. ```powershell $PSDefaultParameterValues = @{ "Show-Command:Height" = 700 "Show-Command:Width" = 1000 "Show-Command:ErrorPopup" = $true } ``` Now when you run a `Show-Command` command, the new defaults are applied automatically. To use these default values in every PowerShell session, add the `$PSDefaultParameterValues` variable to your PowerShell profile. For more information, see [about_Profiles](../Microsoft.PowerShell.Core/About/about_Profiles.md) and [about_Parameters_Default_Values](../Microsoft.PowerShell.Core/About/about_Parameters_Default_Values.md). ### Example 5: Send output to a grid view This command shows how to use the `Show-Command` and `Out-GridView` cmdlets together. ```powershell Show-Command Get-ChildItem | Out-GridView ``` The command uses the `Show-Command` cmdlet to open a command window for the`Get-ChildItem`cmdlet. When you click the **Run** button, the `Get-ChildItem` command runs and generates output. The pipeline operator ( | ) sends the output of the `Get-ChildItem` command to the `Out-GridView` cmdlet, which displays the `Get-ChildItem` output in an interactive window. ### Example 6: Display a command that you create in the Commands window This example shows the command that you created in the `Show-Command` window. The command uses the **PassThru** parameter, which returns the `Show-Command` results in a string. ```powershell Show-Command -PassThru ``` ```Output Get-EventLog -LogName "Windows PowerShell" -Newest 5 ``` For example, if you use the `Show-Command` window to create a `Get-EventLog` command that gets the five newest events in the Windows PowerShell event log, and then click **OK**, the command returns the output shown above. Viewing the command string helps you learn PowerShell. ### Example 7: Save a command to a variable This example shows how to run the command string that you get when you use the **PassThru** parameter of the `Show-Command` cmdlet. This strategy lets you see the command and use it. ```powershell $C = Show-Command -PassThru $C Invoke-Expression $C ``` ```Output Get-EventLog -LogName "PowerShell" -Newest 5 Index Time EntryType Source InstanceID Message ----- ---- --------- ------ ---------- ------- 11520 Dec 16 16:37 Information Windows PowerShell 400 Engine state is changed from None to Available... 11519 Dec 16 16:37 Information Windows PowerShell 600 Provider "Variable" is Started. ... 11518 Dec 16 16:37 Information Windows PowerShell 600 Provider "Registry" is Started. ... 11517 Dec 16 16:37 Information Windows PowerShell 600 Provider "Function" is Started. ... 11516 Dec 16 16:37 Information Windows PowerShell 600 Provider "FileSystem" is Started. ... ``` The first command uses the **PassThru** parameter of the `Show-Command` cmdlet and saves the results of the command in the `$C` variable. In this case, we use the `Show-Command` window to create a `Get-EventLog` command that gets the five newest events in the Windows PowerShell event log. When you click **OK**, `Show-Command` returns the command string, which is saved in the `$C` variable. ### Example 8: Save the output of a command to a variable This example uses the **ErrorPopup** parameter to save the output of a command in a variable. ```powershell $P = Show-Command Get-Process -ErrorPopup $P ``` ```Output Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 473 33 94096 112532 709 2.06 4492 powershell ``` In addition to displaying errors in a window, **ErrorPopup** returns command output to the current command, instead of creating a new command. When you run this command, the `Show-Command` window opens. You can use the window features to set parameter values. To run the command, click the **Run** button in the `Show-Command` window. ## PARAMETERS ### -ErrorPopup Indicates that the cmdlet displays errors in a pop-up window, in addition to displaying them at the command line. By default, when a command that is run in a `Show-Command` window generates an error, the error is displayed only at the command line. Also, when you run the command (by using the **Run** button in the `Show-Command` window), the **ErrorPopup** parameter returns the command results to the current command, instead of running the command and returning its output to a new command. You can use this feature to save the command results in a variable. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Height Specifies the height of the `Show-Command` window in pixels. Enter a value between 300 and the number of pixels in the screen resolution. If the value is too large to display the command window on the screen, `Show-Command` generates an error. The default height is 600 pixels. For a `Show-Command` command that includes the **Name** parameter, the default height is 300 pixels. ```yaml Type: System.Double Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Displays a command window for the specified command. Enter the name of one command, such as the name of a cmdlet, function, or CIM command. If you omit this parameter, `Show-Command` displays a command window that lists all of the PowerShell commands in all modules installed on the computer. ```yaml Type: System.String Parameter Sets: (All) Aliases: CommandName Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NoCommonParameter Indicates that this cmdlet omits the Common Parameters section of the command display. By default, the Common Parameters appear in an expandable section at the bottom of the command window. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -PassThru Returns an object representing the item with which you are working. By default, this cmdlet does not generate any output. To run the command string, copy and paste it at the command prompt or save it in a variable and use the `Invoke-Expression` cmdlet to run the string in the variable. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Width Specifies the width of the `Show-Command` window in pixels. Enter a value between 300 and the number of pixels in the screen resolution. If the value is too large to display the command window on the screen, `Show-Command` generates an error. The default width is 300 pixels. ```yaml Type: System.Double Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None By default, this cmdlet returns no output. ### System.String When you use the **PassThru** parameter, this cmdlet returns a command string. ### System.Object When you use the **ErrorPopup** parameter, this cmdlet returns the command output (any object). ## NOTES PowerShell includes the following aliases for `Show-Command`: - Windows: - `shcm` This cmdlet is only available on Windows platforms. `Show-Command` does not work in remote sessions. ## RELATED LINKS

#File: reference/7.6/Microsoft.PowerShell.Utility/Show-Markdown.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 08/23/2019 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/show-markdown?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Show-Markdown --- # Show-Markdown ## SYNOPSIS Shows a Markdown file or string in the console in a friendly way using VT100 escape sequences or in a browser using HTML. ## SYNTAX ### Path (Default) ``` Show-Markdown [-Path] <String[]> [-UseBrowser] [<CommonParameters>] ``` ### InputObject ``` Show-Markdown -InputObject <PSObject> [-UseBrowser] [<CommonParameters>] ``` ### LiteralPath ``` Show-Markdown -LiteralPath <String[]> [-UseBrowser] [<CommonParameters>] ``` ## DESCRIPTION The `Show-Markdown` cmdlet is used to render Markdown in a human readable format either in a terminal or in a browser. `Show-Markdown` can return a string that includes the VT100 escape sequences which the terminal renders (if it supports VT100 escape sequences). This is primarily used for viewing Markdown files in a terminal. You can also get this string via the `ConvertFrom-Markdown` by specifying the **AsVT100EncodedString** parameter. `Show-Markdown` also has the ability to open a browser and show you a rendered version of the Markdown. It renders the Markdown by turning it into HTML and opening the HTML file in your default browser. You can change how `Show-Markdown` renders Markdown in a terminal by using `Set-MarkdownOption`. This cmdlet was introduced in PowerShell 6.1. ## EXAMPLES ### Example 1: Simple example specifying a path ```powershell Show-Markdown -Path ./README.md ``` ### Example 2: Simple example specifying a string ```powershell @" # Show-Markdown ## Markdown You can now interact with Markdown via PowerShell! *stars* __underlines__ "@ | Show-Markdown ``` ### Example 2: Opening Markdown in a browser ```powershell Show-Markdown -Path ./README.md -UseBrowser ``` ## PARAMETERS ### -InputObject A Markdown string that will be shown in the terminal. If you do not pass in a supported format, `Show-Markdown` will emit an error. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: InputObject Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -LiteralPath Specifies the path to a Markdown file. Unlike the Path parameter, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: LiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the path to a Markdown file to be rendered. ```yaml Type: System.String[] Parameter Sets: Path Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -UseBrowser Compiles the Markdown input as HTML and opens it in your default browser. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject ### System.String[] ## OUTPUTS ### System.String ## NOTES ## RELATED LINKS [ConvertFrom-Markdown](ConvertFrom-Markdown.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Sort-Object.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/sort-object?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Sort-Object --- # Sort-Object ## SYNOPSIS Sorts objects by property values. ## SYNTAX ### Default (Default) ``` Sort-Object [-Stable] [-Descending] [-Unique] [-InputObject <PSObject>] [[-Property] <Object[]>] [-Culture <String>] [-CaseSensitive] [<CommonParameters>] ``` ### Top ``` Sort-Object [-Descending] [-Unique] -Top <Int32> [-InputObject <PSObject>] [[-Property] <Object[]>] [-Culture <String>] [-CaseSensitive] [<CommonParameters>] ``` ### Bottom ``` Sort-Object [-Descending] [-Unique] -Bottom <Int32> [-InputObject <PSObject>] [[-Property] <Object[]>] [-Culture <String>] [-CaseSensitive] [<CommonParameters>] ``` ## DESCRIPTION The `Sort-Object` cmdlet sorts objects in ascending or descending order based on object property values. If sort properties aren't included in a command, PowerShell uses default sort properties of the first input object. If the input object's type has no default sort properties, PowerShell attempts to compare the objects themselves. For more information, see the [Notes](#notes) section. You can sort objects by a single property or multiple properties. Multiple properties use hash tables to sort in ascending order, descending order, or a combination of sort orders. Properties are sorted as case-sensitive or case-insensitive. Use the **Unique** parameter to remove duplicates from the output. ## EXAMPLES ### Example 1: Sort the current directory by name This example sorts the files and subdirectories in a directory. ```powershell Get-ChildItem -Path C:\Test | Sort-Object ``` ```Output Directory: C:\Test Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2/13/2019 08:55 26 anotherfile.txt -a---- 2/13/2019 13:26 20 Bfile.txt -a---- 2/12/2019 15:40 118014 Command.txt -a---- 2/1/2019 08:43 183 CreateTestFile.ps1 d----- 2/25/2019 18:25 Files d----- 2/25/2019 18:24 Logs -ar--- 2/12/2019 14:31 27 ReadOnlyFile.txt -a---- 2/12/2019 16:24 23 Zsystemlog.log ``` The `Get-ChildItem` cmdlet gets the files and subdirectories from the directory specified by the **Path** parameter, `C:\Test`. The objects are sent down the pipeline to the `Sort-Object` cmdlet. `Sort-Object` doesn't specify a property so the output is sorted by the default sort property, **Name**. ### Example 2: Sort the current directory by file length This command displays the files in the current directory by length in ascending order. ```powershell Get-ChildItem -Path C:\Test -File | Sort-Object -Property Length ``` ```Output Directory: C:\Test Mode LastWriteTime Length Name ---- ------------- ------ ---- -a---- 2/13/2019 13:26 20 Bfile.txt -a---- 2/12/2019 16:24 23 Zsystemlog.log -a---- 2/13/2019 08:55 26 anotherfile.txt -ar--- 2/12/2019 14:31 27 ReadOnlyFile.txt -a---- 2/1/2019 08:43 183 CreateTestFile.ps1 -a---- 2/12/2019 15:40 118014 Command.txt ``` The `Get-ChildItem` cmdlet gets the files from the directory specified by the **Path** parameter. The **File** parameter specifies that `Get-ChildItem` only gets file objects. The objects are sent down the pipeline to the `Sort-Object` cmdlet. `Sort-Object` uses the **Length** parameter to sort the files by length in ascending order. ### Example 3: Sort processes by memory usage This example displays processes with the highest memory usage based on their working set (WS) size. ```powershell Get-Process | Sort-Object -Property WS | Select-Object -Last 5 ``` ```Output NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 136 193.92 217.11 889.16 87492 8 OUTLOOK 112 347.73 297.02 95.19 106908 8 Teams 206 266.54 323.71 37.17 60620 8 MicrosoftEdgeCP 35 552.19 549.94 131.66 6552 8 Code 0 1.43 595.12 0.00 2780 0 Memory Compression ``` The `Get-Process` cmdlet gets the list of processes running on the computer. The process objects are sent down the pipeline to the `Sort-Object` cmdlet. `Sort-Object` uses the **Property** parameter to sort the objects by **WS**. The objects are sent down the pipeline to the `Select-Object` cmdlet. `Select-Object` uses the **Last** parameter to specify the last five objects, which are the objects with the highest **WS** usage. In PowerShell 6, the `Sort-Object` parameter **Bottom** is an alternative to `Select-Object`. For example, `Get-Process | Sort-Object -Property WS -Bottom 5`. ### Example 4: Sort HistoryInfo objects by Id This command sorts the PowerShell session's **HistoryInfo** objects using the **Id** property. Each PowerShell session has its own command history. ```powershell Get-History | Sort-Object -Property Id -Descending ``` ```Output Id CommandLine -- ----------- 10 Get-Command Sort-Object -Syntax 9 $PSVersionTable 8 Get-Command Sort-Object -Syntax 7 Get-Command Sort-Object -ShowCommandInfo 6 Get-ChildItem -Path C:\Test | Sort-Object -Property Length 5 Get-Help Clear-History -Online 4 Get-Help Clear-History -Full 3 Get-ChildItem | Get-Member 2 Get-Command Sort-Object -Syntax 1 Set-Location C:\Test\ ``` The `Get-History` cmdlet gets the history objects from the current PowerShell session. The objects are sent down the pipeline to the `Sort-Object` cmdlet. `Sort-Object` uses the **Property** parameter to sort the objects by **Id**. The **Descending** parameter sorts the command history from newest to oldest. ### Example 5: Use a hash table to sort properties in ascending and descending order This example uses two properties to sort the objects, **Status** and **DisplayName**. **Status** is sorted in descending order and **DisplayName** is sorted in ascending order. A hash table is used to specify the **Property** parameter's value. The hash table uses an expression to specify the property names and sort orders. For more information about hash tables, see [about_Hash_Tables](../Microsoft.PowerShell.Core/About/about_Hash_Tables.md). The **Status** property used in the hash table is an enumerated property. For more information, see [ServiceControllerStatus](/dotnet/api/system.serviceprocess.servicecontrollerstatus). ```powershell Get-Service | Sort-Object -Property @{Expression = "Status"; Descending = $true}, @{Expression = "DisplayName"; Descending = $false} ``` ```Output Status Name DisplayName ------ ---- ----------- Running Appinfo Application Information Running BthAvctpSvc AVCTP service Running BrokerInfrastru... Background Tasks Infrastructure Ser... Running BDESVC BitLocker Drive Encryption Service Running CoreMessagingRe... CoreMessaging Running VaultSvc Credential Manager Running DsSvc Data Sharing Service Running Dhcp DHCP Client ... Stopped ALG Application Layer Gateway Service Stopped AppMgmt Application Management Stopped BITS Background Intelligent Transfer Ser... Stopped wbengine Block Level Backup Engine Service Stopped BluetoothUserSe... Bluetooth User Support Service_14fb... Stopped COMSysApp COM+ System Application Stopped smstsmgr ConfigMgr Task Sequence Agent Stopped DeviceInstall Device Install Service Stopped MSDTC Distributed Transaction Coordinator ``` The `Get-Service` cmdlet gets the list of services on the computer. The service objects are sent down the pipeline to the `Sort-Object` cmdlet. `Sort-Object` uses the **Property** parameter with a hash table to specify the property names and sort orders. The **Property** parameter is sorted by two properties, **Status** in descending order and **DisplayName** in ascending order. **Status** is an enumerated property. **Stopped** has a value of **1** and **Running** has a value of **4**. The **Descending** parameter is set to `$true` so that **Running** processes are displayed before **Stopped** processes. **DisplayName** sets the **Descending** parameter to `$false` to sort the display names in alphabetical order. ### Example 6: Sort text files by time span This command sorts text files in descending order by the time span between **CreationTime** and **LastWriteTime**. ```powershell Get-ChildItem -Path C:\Test\*.txt | Sort-Object -Property {$_.CreationTime - $_.LastWriteTime} | Format-Table CreationTime, LastWriteTime, FullName ``` ```Output CreationTime LastWriteTime FullName ------------ ------------- -------- 11/21/2018 12:39:01 2/26/2019 08:59:36 C:\Test\test2.txt 12/4/2018 08:29:41 2/26/2019 08:57:05 C:\Test\powershell_list.txt 2/20/2019 08:15:59 2/26/2019 12:09:43 C:\Test\CreateTestFile.txt 2/20/2019 08:15:59 2/26/2019 12:07:41 C:\Test\Command.txt 2/20/2019 08:15:59 2/26/2019 08:57:52 C:\Test\ReadOnlyFile.txt 11/29/2018 15:16:50 12/4/2018 16:16:24 C:\Test\LogData.txt 2/25/2019 18:25:11 2/26/2019 12:08:47 C:\Test\Zsystemlog.txt 2/25/2019 18:25:11 2/26/2019 08:55:33 C:\Test\Bfile.txt 2/26/2019 08:46:59 2/26/2019 12:12:19 C:\Test\LogFile3.txt ``` The `Get-ChildItem` cmdlet uses the **Path** parameter to specify the directory `C:\Test` and all of the `*.txt` files. The objects are sent down the pipeline to the `Sort-Object` cmdlet. `Sort-Object` uses the **Property** parameter with a scriptblock to determine each files time span between **CreationTime** and **LastWriteTime**. ### Example 7: Sort names in a text file This example shows how to sort a list from a text file. The original file is displayed as an unsorted list. `Sort-Object` sorts the contents and then sorts the contents with the **Unique** parameter that removes duplicates. ```powershell # All items unsorted Get-Content -Path C:\Test\ServerNames.txt ``` ```Output localhost server01 server25 LOCALHOST Server19 server3 localhost ``` ```powershell # All items sorted Get-Content -Path C:\Test\ServerNames.txt | Sort-Object localhost LOCALHOST localhost server01 Server19 server25 server3 ``` ```powershell # Unique filtered items sorted Get-Content -Path C:\Test\ServerNames.txt | Sort-Object -Unique ``` ```Output localhost server01 Server19 server25 server3 ``` The `Get-Content` cmdlet uses the **Path** parameter to specify the directory and filename. The file `ServerNames.txt` contains an unsorted list of computer names. The `Get-Content` cmdlet uses the **Path** parameter to specify the directory and filename. The file `ServerNames.txt` contains an unsorted list of computer names. The objects are sent down the pipeline to the `Sort-Object` cmdlet. `Sort-Object` sorts the list in the default order, ascending. The `Get-Content` cmdlet uses the **Path** parameter to specify the directory and filename. The file `ServerNames.txt` contains an unsorted list of computer names. The objects are sent down the pipeline to the `Sort-Object` cmdlet. `Sort-Object` uses the **Unique** parameter to remove duplicate computer names. The list is sorted in the default order, ascending. ### Example 8: Sort a string as an integer This example shows how to sort a text file that contains string objects as integers. You can send each command down the pipeline to `Get-Member` and verify that the objects are strings instead of integers. For these examples, the `ProductId.txt` file contains an unsorted list of product numbers. In the first example, `Get-Content` gets the contents of the file and pipes lines to the `Sort-Object` cmdlet. `Sort-Object` sorts the string objects in ascending order. ```powershell # String sorted Get-Content -Path C:\Test\ProductId.txt | Sort-Object ``` ```Output 0 1 12345 1500 2 2800 3500 4100 500 6200 77 88 99999 ``` ```powershell # Integer sorted Get-Content -Path C:\Test\ProductId.txt | Sort-Object {[int]$_} ``` ```Output 0 1 2 77 88 500 1500 2800 3500 4100 6200 12345 99999 ``` In the second example, `Get-Content` gets the contents of the file and pipes lines to the `Sort-Object` cmdlet. `Sort-Object` uses a script block to convert the strings to integers. In the sample code, `[int]` converts the string to an integer and `$_` represents each string as it comes down the pipeline. The integer objects are sent down the pipeline to the `Sort-Object` cmdlet. `Sort-Object` sorts the integer objects in numeric order. ### Example 9: Using stable sorts When you use the **Top**, **Bottom**, or **Stable** parameters, the sorted objects are delivered in the order they were received by `Sort-Object` when the sort criteria are equal. In this example, we are sorting the numbers one through 20 by the their value 'modulo 3'. The modulo value ranges from zero to two. ```powershell 1..20 |Sort-Object {$_ % 3} ``` ```Output 18 3 15 6 12 9 1 16 13 10 7 4 19 11 8 14 5 17 2 20 ``` ```powershell 1..20 |Sort-Object {$_ % 3} -Stable ``` ```Output 3 6 9 12 15 18 1 4 7 10 13 16 19 2 5 8 11 14 17 20 ``` The output from the first sort is correctly grouped by the modulus value but the individual items aren't sorted within the modulus range. The second sort uses the **Stable** option to return a stable sort. ### Example 10: Sort by multiple properties If you want to sort by multiple properties, separate the properties by commas. ```powershell Get-ChildItem -Path C:\Test | Sort-Object Length,Name ``` ```Output Directory: C:\Test Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 13/10/2021 22:16 2 File01.txt -a--- 13/10/2021 22:16 2 File03.txt -a--- 13/10/2021 22:18 64 File02.txt -a--- 13/10/2021 22:18 64 File04.txt ``` The `Get-ChildItem` cmdlet gets the files from the directory specified by the **Path** parameter. The objects are sent down the pipeline to the `Sort-Object` cmdlet. `Sort-Object` uses the **Length** and **Name** parameter to sort the files by length in ascending order. Since `File01.txt` and `File03.txt` have the same length, they're further sorted by their property **Name**. ### Example 11: Sort hashtables by key value Beginning in PowerShell 6, `Sort-Object` supports sorting of **hashtable** input by key values. The following example sorts an array of hashtables by the value of each hashtable's `weight` key. ```powershell @( @{ name = 'a' ; weight = 7 } @{ name = 'b' ; weight = 1 } @{ name = 'c' ; weight = 3 } @{ name = 'd' ; weight = 7 } ) | Sort-Object -Property weight -OutVariable Sorted $Sorted | ForEach-Object -Process { "{0}: {1}" -f $_.name, $_.weight } ``` ```output Name Value ---- ----- Weight 1 Name b Weight 3 Name c Weight 7 Name a Weight 7 Name d b: 1 c: 3 a: 7 d: 7 ``` ## PARAMETERS ### -Bottom Specifies the number of objects to get from the end of a sorted object array. This results in a stable sort. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Int32 Parameter Sets: Bottom Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CaseSensitive Indicates that the sort is case-sensitive. By default, sorts aren't case-sensitive. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Case-insensitive Accept pipeline input: False Accept wildcard characters: False ``` ### -Culture Specifies the cultural configuration to use for sorts. Use `Get-Culture` to display the system's culture configuration. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Descending Indicates that `Sort-Object` sorts the objects in descending order. The default is ascending order. To sort multiple properties with different sort orders, use a hash table. For example, with a hash table you can sort one property in ascending order and another property in descending order. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Ascending Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject To sort objects, send them down the pipeline to `Sort-Object`. If you use the **InputObject** parameter to submit a collection of items, `Sort-Object` receives one object that represents the collection. Because one object can't be sorted, `Sort-Object` returns the entire collection unchanged. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Property Specifies the property names that `Sort-Object` uses to sort the objects. Wildcards are permitted. Objects are sorted based on the property values. If you don't specify a property, `Sort-Object` sorts based on default properties for the object type or the objects themselves. Use commas to separate multiple properties. Multiple properties can be sorted in ascending order, descending order, or a combination of sort orders. When you specify multiple properties, the objects are sorted by the first property. If multiple objects have the same value for the first property, those objects are sorted by the second property. This process continues until there are no more specified properties or no groups of objects. The **Property** parameter's value can be a calculated property. To create a calculated property, use a scriptblock or a hashtable. Valid keys for a hash table are as follows: - `Expression` - `<string>` or `<script block>` - `Ascending` or `Descending` - `<boolean>` For more information, see [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md). ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: Default properties Accept pipeline input: False Accept wildcard characters: True ``` ### -Stable The sorted objects are delivered in the order they were received when the sort criteria are equal. This parameter was added in PowerShell v6.2.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Default Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Top Specifies the number of objects to get from the start of a sorted object array. This results in a stable sort. This parameter was introduced in PowerShell 6.0. ```yaml Type: System.Int32 Parameter Sets: Top Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Unique Indicates that `Sort-Object` eliminates duplicates and returns only the unique members of the collection. The first instance of a unique value is included in the sorted output. **Unique** is case-insensitive. Strings that only differ by character case are considered the same. For example, character and CHARACTER. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: All Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe the objects to be sorted to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSObject This cmdlet returns the sorted objects. ## NOTES PowerShell includes the following aliases for `Sort-Object`: - Windows: - `sort` The `Sort-Object` cmdlet sorts objects based on properties specified in the command or the default sort properties for the object type. Default sort properties are defined using the `PropertySet` named `DefaultKeyPropertySet` in a `types.ps1xml` file. For more information, see [about_Types.ps1xml](/powershell/module/Microsoft.PowerShell.Core/About/about_Types.ps1xml). If an object doesn't have one of the specified properties, the property value for that object is interpreted by `Sort-Object` as **Null** and placed at the end of the sort order. When no sort properties are available, PowerShell attempts to compare the objects themselves. `Sort-Object` uses the **Compare** method for each property. If a property doesn't implement **IComparable**, the cmdlet converts the property value to a string and uses the **Compare** method for **System.String**. For more information, see [PSObject.CompareTo(Object) Method](/dotnet/api/system.management.automation.psobject.compareto). If you sort on an enumerated property such as **Status**, `Sort-Object` sorts by the enumeration values. For Windows services, **Stopped** has a value of **1** and **Running** has a value of **4**. **Stopped** is sorted before **Running** because of the enumerated values. For more information, see [ServiceControllerStatus](/dotnet/api/system.serviceprocess.servicecontrollerstatus). The performance of the sorting algorithm is slower when doing a stable sort. ## RELATED LINKS [about_Calculated_Properties](../Microsoft.PowerShell.Core/About/about_Calculated_Properties.md) [about_Hash_Tables](../Microsoft.PowerShell.Core/About/about_Hash_Tables.md) [about_Types.ps1xml](../Microsoft.PowerShell.Core/About/about_Types.ps1xml.md) [Compare-Object](Compare-Object.md) [ForEach-Object](../Microsoft.PowerShell.Core/ForEach-Object.md) [Group-Object](Group-Object.md) [Measure-Object](Measure-Object.md) [New-Object](New-Object.md) [Select-Object](Select-Object.md) [Tee-Object](Tee-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Start-Sleep.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 10/08/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/start-sleep?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Start-Sleep --- # Start-Sleep ## SYNOPSIS Suspends the activity in a script or session for the specified period of time. ## SYNTAX ### Seconds (Default) ``` Start-Sleep [-Seconds] <Double> [<CommonParameters>] ``` ### Milliseconds ``` Start-Sleep -Milliseconds <Int32> [<CommonParameters>] ``` ### FromTimeSpan ``` Start-Sleep -Duration <TimeSpan> [<CommonParameters>] ``` ## DESCRIPTION The `Start-Sleep` cmdlet suspends the activity in a script or session for the specified period of time. You can use it for many tasks, such as waiting for an operation to complete or pausing before repeating an operation. ## EXAMPLES ### Example 1: Pause execution for 1.5 seconds In this example, the execution of commands pauses for one and one-half seconds. ```powershell Start-Sleep -Seconds 1.5 ``` ### Example 2: Pause execution at the command line This example shows that execution is paused for 5 seconds when run from the command line. ```powershell PS> Get-Date; Start-Sleep -Seconds 5; Get-Date Friday, May 13, 2022 9:38:15 AM Friday, May 13, 2022 9:38:20 AM ``` PowerShell cannot execute the second `Get-Date` command until the sleep timer expires. ### Example 3: Sleep commands using a **TimeSpan** This example makes all the commands in the session sleep for 30 seconds. ```powershell Start-Sleep -Duration (New-TimeSpan -Seconds 30) ``` ## PARAMETERS ### -Duration Uses a **TimeSpan** object to specify how long the resource sleeps in milliseconds. The value must not be a negative **TimeSpan** and must not exceed `[int]::MaxValue` milliseconds. This parameter was added in PowerShell 7.3. ```yaml Type: System.TimeSpan Parameter Sets: FromTimeSpan Aliases: ts Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Milliseconds Specifies how long the resource sleeps in milliseconds. The parameter can be abbreviated as **m**. ```yaml Type: System.Int32 Parameter Sets: Milliseconds Aliases: ms Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Seconds Specifies how long the resource sleeps in seconds. You can omit the parameter name or you can abbreviate it as **s**. Beginning in PowerShell 6.2.0, this parameter now accepts fractional values. ```yaml Type: System.Double Parameter Sets: Seconds Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.Int32 You can pipe the number of seconds to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES PowerShell includes the following aliases for `Start-Sleep`: - Windows: - `sleep` - `Ctrl+C` breaks out of `Start-Sleep`. - `Ctrl+C` does not break out of `[Threading.Thread]::Sleep`. For more information, see [Thread.Sleep Method](/dotnet/api/system.threading.thread.sleep). ## RELATED LINKS

#File: reference/7.6/Microsoft.PowerShell.Utility/Tee-Object.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 04/25/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/tee-object?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Tee-Object --- # Tee-Object ## SYNOPSIS Saves command output in a file or variable and also sends it down the pipeline. ## SYNTAX ### File (Default) ``` Tee-Object [-InputObject <PSObject>] [-FilePath] <String> [-Append] [[-Encoding] <Encoding>] [<CommonParameters>] ``` ### LiteralFile ``` Tee-Object [-InputObject <PSObject>] -LiteralPath <String> [[-Encoding] <Encoding>] [<CommonParameters>] ``` ### Variable ``` Tee-Object [-InputObject <PSObject>] -Variable <String> [<CommonParameters>] ``` ## DESCRIPTION The `Tee-Object` cmdlet redirects output, that is, it sends the output of a command in two directions (like the letter T). It stores the output in a file or variable and also sends it down the pipeline. If `Tee-Object` is the last command in the pipeline, the command output is displayed at the prompt. ## EXAMPLES ### Example 1: Output processes to a file and to the console This example gets a list of the processes running on the computer and sends the result to a file. Because a second path is not specified, the processes are also displayed in the console. ```powershell Get-Process | Tee-Object -FilePath "C:\Test1\testfile2.txt" ``` ```Output Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName ------- ------ ----- ----- ----- ------ -- ----------- 83 4 2300 4520 39 0.30 4032 00THotkey 272 6 1400 3944 34 0.06 3088 alg 81 3 804 3284 21 2.45 148 ApntEx 81 4 2008 5808 38 0.75 3684 Apoint ... ``` ### Example 2: Output processes to a variable and `Select-Object` This example gets a list of the processes running on the computer, saves them to the `$proc` variable, and pipes them to `Select-Object`. ```powershell Get-Process notepad | Tee-Object -Variable proc | Select-Object ProcessName, Handles ``` ```Output ProcessName Handles ----------- ------- notepad 43 notepad 37 notepad 38 notepad 38 ``` The `Select-Object` cmdlet selects the **ProcessName** and **Handles** properties. Note that the `$proc` variable includes the default information returned by `Get-Process`. ### Example 3: Output system files to two log files This example saves a list of system files in a two log files, a cumulative file and a current file. ```powershell Get-ChildItem -Path D: -File -System -Recurse | Tee-Object -FilePath "C:\test\AllSystemFiles.txt" -Append | Out-File C:\test\NewSystemFiles.txt ``` The command uses the `Get-ChildItem` cmdlet to do a recursive search for system files on the D: drive. A pipeline operator (`|`) sends the list to `Tee-Object`, which appends the list to the AllSystemFiles.txt file and passes the list down the pipeline to the `Out-File` cmdlet, which saves the list in the `NewSystemFiles.txt file`. ### Example 4: Print output to console and use in the pipeline This example gets the files in a folder, prints them to the console, then filters the files for those that have a defined front matter metadata block. Finally, it lists the names of the articles that have front matter. ```powershell $consoleDevice = if ($IsWindows) { '\\.\CON' } else { '/dev/tty' } $frontMatterPattern = '(?s)^---(?<FrontMatter>.+)---' $articles = Get-ChildItem -Path .\reference\7.4\PSReadLine\About\ | Tee-Object -FilePath $consoleDevice | Where-Object { (Get-Content $_ -Raw) -match $frontMatterPattern } $articles.Name ``` ```Output Directory: C:\code\docs\PowerShell-Docs\reference\7.4\PSReadLine\About Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 12/13/2022 11:37 AM 384 .markdownlint.yaml -a--- 4/25/2023 11:28 AM 40194 about_PSReadLine_Functions.md -a--- 4/25/2023 10:58 AM 10064 about_PSReadLine.md about_PSReadLine_Functions.md about_PSReadLine.md ``` The example sets the `$consoleDevice` variable to the value of the current terminal's console device. On Windows, you can write to the current console device by redirecting your output to the `\\.\CON` filepath. On non-Windows systems, you use the `/dev/tty` filepath. Then it sets the `$frontMatterPattern` variable to a regular expression that matches when a string starts with three dashes (`---`) and has any content before another three dashes. When this pattern matches an article's content, the article has a defined front matter metadata block. Next, the example uses `Get-ChildItem` to retrieve every file in the `About` folder. `Tee-Object` prints the piped results to the console using the **FileName** parameter. `Where-Object` filters the files by getting their content as a single string with the **Raw** parameter of `Get-Content` and comparing that string to `$frontMatterPattern`. Finally, the example prints the names of the files in the folder that have a defined front matter metadata block. ## PARAMETERS ### -Append Indicates that the cmdlet appends the output to the specified file. Without this parameter, the new content replaces any existing content in the file without warning. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: File Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Encoding Specifies the type of encoding for the target file. The default value is `utf8NoBOM`. The acceptable values for this parameter are as follows: - `ascii`: Uses the encoding for the ASCII (7-bit) character set. - `ansi`: Uses the encoding for the for the current culture's ANSI code page. This option was added in PowerShell 7.4. - `bigendianunicode`: Encodes in UTF-16 format using the big-endian byte order. - `oem`: Uses the default encoding for MS-DOS and console programs. - `unicode`: Encodes in UTF-16 format using the little-endian byte order. - `utf7`: Encodes in UTF-7 format. - `utf8`: Encodes in UTF-8 format. - `utf8BOM`: Encodes in UTF-8 format with Byte Order Mark (BOM) - `utf8NoBOM`: Encodes in UTF-8 format without Byte Order Mark (BOM) - `utf32`: Encodes in UTF-32 format. Beginning with PowerShell 6.2, the **Encoding** parameter also allows numeric IDs of registered code pages (like `-Encoding 1251`) or string names of registered code pages (like `-Encoding "windows-1251"`). For more information, see the .NET documentation for [Encoding.CodePage](/dotnet/api/system.text.encoding.codepage?view=netcore-2.2). Starting with PowerShell 7.4, you can use the `Ansi` value for the **Encoding** parameter to pass the numeric ID for the current culture's ANSI code page without having to specify it manually. This parameter was introduced in PowerShell 7.2. > [!NOTE] > **UTF-7*** is no longer recommended to use. As of PowerShell 7.1, a warning is written if you > specify `utf7` for the **Encoding** parameter. ```yaml Type: System.Text.Encoding Parameter Sets: (All) Aliases: Accepted values: ASCII, BigEndianUnicode, OEM, Unicode, UTF7, UTF8, UTF8BOM, UTF8NoBOM, UTF32 Required: False Position: 1 Default value: UTF8NoBOM Accept pipeline input: False Accept wildcard characters: False ``` ### -FilePath Specifies a file that this cmdlet saves the object to Wildcard characters are permitted, but must resolve to a single file. Starting in PowerShell 7, when you specify the **FilePath** as `\\.\CON` on Windows or `/dev/tty` on non-Windows systems, the **InputObject** is printed in the console. Those file paths correspond to the current terminal's console device on the system, enabling you to print the **InputObject** and send it to the output stream with one command. ```yaml Type: System.String Parameter Sets: File Aliases: Path Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -InputObject Specifies the object to be saved and displayed. Enter a variable that contains the objects or type a command or expression that gets the objects. You can also pipe an object to `Tee-Object`. When you use the **InputObject** parameter with `Tee-Object`, instead of piping command results to `Tee-Object`, the **InputObject** value is treated as a single object even if the value is a collection. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -LiteralPath Specifies a file that this cmdlet saves the object to. Unlike **FilePath**, the value of the **LiteralPath** parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String Parameter Sets: LiteralFile Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Variable Specifies a variable that the cmdlet saves the object to. Enter a variable name without the preceding dollar sign (`$`). ```yaml Type: System.String Parameter Sets: Variable Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSObject This cmdlet returns the object that it redirects. ## NOTES PowerShell includes the following aliases for `Tee-Object`: - Windows: - `tee` You can also use the `Out-File` cmdlet or the redirection operator, both of which save the output in a file but do not send it down the pipeline. Beginning in PowerShell 6, `Tee-Object` uses BOM-less UTF-8 encoding when it writes to files. If you need a different encoding, use the `Out-File` cmdlet with the **Encoding** parameter. ## RELATED LINKS [Compare-Object](Compare-Object.md) [ForEach-Object](../Microsoft.PowerShell.Core/ForEach-Object.md) [Group-Object](Group-Object.md) [Measure-Object](Measure-Object.md) [New-Object](New-Object.md) [Select-Object](Select-Object.md) [Sort-Object](Sort-Object.md) [Where-Object](../Microsoft.PowerShell.Core/Where-Object.md) [about_Redirection](../Microsoft.PowerShell.Core/About/about_Redirection.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Test-Json.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 04/29/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/test-json?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Test-Json --- # Test-Json ## SYNOPSIS Tests whether a string is a valid JSON document ## SYNTAX ### JsonString (Default) ``` Test-Json [-Json] <String> [-Options <String[]>] [<CommonParameters>] ``` ### JsonStringWithSchemaString ``` Test-Json [-Json] <String> [-Schema] <String> [-Options <String[]>] [<CommonParameters>] ``` ### JsonStringWithSchemaFile ``` Test-Json [-Json] <String> -SchemaFile <String> [-Options <String[]>] [<CommonParameters>] ``` ### JsonPath ``` Test-Json -Path <String> [-Options <String[]>] [<CommonParameters>] ``` ### JsonPathWithSchemaString ``` Test-Json -Path <String> [-Schema] <String> [-Options <String[]>] [<CommonParameters>] ``` ### JsonPathWithSchemaFile ``` Test-Json -Path <String> -SchemaFile <String> [-Options <String[]>] [<CommonParameters>] ``` ### JsonLiteralPath ``` Test-Json -LiteralPath <String> [-Options <String[]>] [<CommonParameters>] ``` ### JsonLiteralPathWithSchemaString ``` Test-Json -LiteralPath <String> [-Schema] <String> [-Options <String[]>] [<CommonParameters>] ``` ### JsonLiteralPathWithSchemaFile ``` Test-Json -LiteralPath <String> -SchemaFile <String> [-Options <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Test-Json` cmdlet tests whether a string is a valid JavaScript Object Notation (JSON) document and can optionally verify that JSON document against a provided schema. The verified string can then be used with the `ConvertFrom-Json` cmdlet convert a JSON-formatted string to a JSON object, which is easily managed in PowerShell or sent to another program or web service that access JSON input. Many web sites use JSON instead of XML to serialize data for communication between servers and web-based apps. This cmdlet was introduced in PowerShell 6.1 ## EXAMPLES ### Example 1: Test if an object is valid JSON This example tests whether the input string is a valid JSON document. ```powershell '{"name": "Ashley", "age": 25}' | Test-Json ``` ```Output True ``` ### Example 2: Test an object against a provided schema This example takes a string containing a JSON schema and compares it to an input string. ```powershell $schema = @' { "definitions": {}, "$schema": "http://json-schema.org/draft-07/schema#", "$id": "http://example.com/root.json", "type": "object", "title": "The Root Schema", "required": [ "name", "age" ], "properties": { "name": { "$id": "#/properties/name", "type": "string", "title": "The Name Schema", "default": "", "examples": [ "Ashley" ], "pattern": "^(.*)$" }, "age": { "$id": "#/properties/age", "type": "integer", "title": "The Age Schema", "default": 0, "examples": [ 25 ] } } } '@ '{"name": "Ashley", "age": "25"}' | Test-Json -Schema $schema -ErrorAction SilentlyContinue ``` ```Output False ``` In this example, we use the **ErrorAction** parameter to suppres the error message. Without this parameter the command also outputs an error because the schema expects an integer for **age** but the JSON input we tested uses a string value instead. For more information, see [JSON Schema](https://json-schema.org/). ### Example 3: Test an object against a schema from file JSON schema can reference definitions using `$ref` keyword. The `$ref` can resolve to a URI that references another file. The **SchemaFile** parameter accepts literal path to the JSON schema file and allows JSON files to be validated against such schemas. In this example the `schema.json` file references `definitions.json`. ```powershell Get-Content schema.json ``` ```Output { "description":"A person", "type":"object", "properties":{ "name":{ "$ref":"definitions.json#/definitions/name" }, "hobbies":{ "$ref":"definitions.json#/definitions/hobbies" } } } ``` ```powershell Get-Content definitions.json ``` ```Output { "definitions":{ "name":{ "type":"string" }, "hobbies":{ "type":"array", "items":{ "type":"string" } } } } ``` ```powershell '{"name": "James", "hobbies": [".NET", "Blogging"]}' | Test-Json -SchemaFile 'schema.json' ``` ```Output True ``` For more information, see [Structuring a complex schema](https://json-schema.org/understanding-json-schema/structuring.html). ## PARAMETERS ### -Json Specifies the JSON string to test for validity. Enter a variable that contains the string, or type a command or expression that gets the string. You can also pipe a string to `Test-Json`. The **Json** parameter is required. ```yaml Type: System.String Parameter Sets: JsonString, JsonStringWithSchemaString, JsonStringWithSchemaFile Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -LiteralPath Specifies a path to a JSON file. The value of **LiteralPath** is used exactly as it's typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell PowerShell not to interpret any characters as escape sequences. This parameter was added in PowerShell 7.4. ```yaml Type: System.String Parameter Sets: JsonLiteralPath, JsonLiteralPathWithSchemaString, JsonLiteralPathWithSchemaFile Aliases: PSPath, LP Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Options By default, `Test-Json` doesn't support JSON containing comments or trailing commas. This parameter allows you to specify options to change the default behavior. The following options are available: - `IgnoreComments` - `AllowTrailingCommas` This parameter was added in PowerShell 7.5.0-preview.4. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Accepted values: IgnoreComments, AllowTrailingCommas Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Path Specifies the path to a JSON file. This cmdlet gets the item at the specified location. Wildcard characters are permitted but the pattern must resolve to a single file. This parameter was added in PowerShell 7.4. ```yaml Type: System.String Parameter Sets: JsonPath, JsonPathWithSchemaString, JsonPathWithSchemaFile Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: True ``` ### -Schema Specifies a schema to validate the JSON input against. If passed, `Test-Json` validates that the JSON input conforms to the spec specified by the **Schema** parameter and return `$true` only if the input conforms to the provided schema. For more information, see [JSON Schema](https://json-schema.org/). ```yaml Type: System.String Parameter Sets: JsonStringWithSchemaString, JsonLiteralPathWithSchemaString, JsonPathWithSchemaString Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SchemaFile Specifies a schema file used to validate the JSON input. When used, the `Test-Json` returns `$true` only if the JSON input conforms to the schema defined in the file specified by the **SchemaFile** parameter. For more information, see [JSON Schema](https://json-schema.org/). ```yaml Type: System.String Parameter Sets: JsonStringWithSchemaFile, JsonLiteralPathWithSchemaFile, JsonPathWithSchemaFile Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a JSON string to this cmdlet. ## OUTPUTS ### Boolean This cmdlet returns `$true` if the JSON is valid and otherwise `$false`. ## NOTES Since PowerShell 6, PowerShell uses the Newtonsoft.Json assemblies for JSON functions. Newtonsoft's implementation includes several extensions to the JSON standard, such as support for comments and use of single quotes. For a full list of features, see the Newtonsoft documentation at [https://www.newtonsoft.com/json](https://www.newtonsoft.com/json). Beginning in PowerShell 7.4, `Test-Json` uses [System.Text.Json](xref:System.Text.Json) for JSON parsing and [JsonSchema.NET](https://www.nuget.org/packages/JsonSchema.Net) for schema validation. With these changes, `Test-Json`: - No longer supports Draft 4 schemas - Only supports strictly conformant JSON For a complete list of differences between Newtonsoft.Json and System.Text.Json, see the _Table of differences_ in [Migrate from Newtonsoft.Json to System.Text.Json](/dotnet/standard/serialization/system-text-json/migrate-from-newtonsoft?pivots=dotnet-8-0#table-of-differences). For more information about JSON schema specifications, see the documentation at [JSON-Schema.org](https://json-schema.org/specification.html). ## RELATED LINKS [An Introduction to JavaScript Object Notation (JSON) in JavaScript and .NET](/previous-versions/dotnet/articles/bb299886(v=msdn.10)) [Additional JSON Schema Details](https://json-schema.org/) [ConvertTo-Json](ConvertTo-Json.md) [Invoke-WebRequest](Invoke-WebRequest.md) [Invoke-RestMethod](Invoke-RestMethod.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Trace-Command.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 02/27/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/trace-command?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Trace-Command --- # Trace-Command ## SYNOPSIS Configures and starts a trace of the specified expression or command. ## SYNTAX ### expressionSet (Default) ``` Trace-Command [-InputObject <PSObject>] [-Name] <String[]> [[-Option] <PSTraceSourceOptions>] [-Expression] <ScriptBlock> [-ListenerOption <TraceOptions>] [-FilePath <String>] [-Force] [-Debugger] [-PSHost] [<CommonParameters>] ``` ### commandSet ``` Trace-Command [-InputObject <PSObject>] [-Name] <String[]> [[-Option] <PSTraceSourceOptions>] [-Command] <String> [-ArgumentList <Object[]>] [-ListenerOption <TraceOptions>] [-FilePath <String>] [-Force] [-Debugger] [-PSHost] [<CommonParameters>] ``` ## DESCRIPTION The `Trace-Command` cmdlet configures and starts a trace of the specified expression or command. It works like Set-TraceSource, except that it applies only to the specified command. ## EXAMPLES ### Example 1: Trace metadata processing, parameter binding, and an expression This example starts a trace of metadata processing, parameter binding, and cmdlet creation and destruction of the `Get-Process Notepad` expression. ```powershell Trace-Command -Name Metadata, ParameterBinding, Cmdlet -Expression {Get-Process Notepad} -PSHost ``` It uses the **Name** parameter to specify the trace sources, the **Expression** parameter to specify the command, and the **PSHost** parameter to send the output to the console. Because it doesn't specify any tracing options or listener options, the command uses the defaults: - All for the tracing options - None for the listener options ### Example 2: Trace the actions of ParameterBinding operations This example traces the actions of the **ParameterBinding** operations of PowerShell while it processes a `Get-Alias` expression that takes input from the pipeline. ```powershell $A = "i*" Trace-Command ParameterBinding {Get-Alias $input} -PSHost -InputObject $A ``` In `Trace-Command`, the **InputObject** parameter passes an object to the expression that's being processed during the trace. The first command stores the string `i*` in the `$A` variable. The second command uses the `Trace-Command` cmdlet with the ParameterBinding trace source. The **PSHost** parameter sends the output to the console. The expression being processed is `Get-Alias $input`, where the `$input` variable is associated with the **InputObject** parameter. The **InputObject** parameter passes the variable `$A` to the expression. In effect, the command being processed during the trace is `Get-Alias -InputObject $A" or "$A | Get-Alias`. ### Example 3: Trace ParameterBinding operations for native commands PowerShell 7.3 added the ability to trace parameter binding for native commands. The following example shows how PowerShell parses the command-line arguments for the native command `TestExe`. ```powershell $a = 'a" "b' Trace-Command -PSHOST -Name ParameterBinding { TestExe -echoargs $a 'c" "d' e" "f } ``` ```Output DEBUG: 2023-02-27 14:20:45.3975 ParameterBinding Information: 0 : BIND NAMED native application line args [C:\Public\Toolbox\TestExe\testexe.exe] DEBUG: 2023-02-27 14:20:45.3978 ParameterBinding Information: 0 : BIND cmd line arg [-echoargs] to position [0] DEBUG: 2023-02-27 14:20:45.3979 ParameterBinding Information: 0 : BIND cmd line arg [a" "b] to position [1] DEBUG: 2023-02-27 14:20:45.3980 ParameterBinding Information: 0 : BIND cmd line arg [c" "d] to position [2] DEBUG: 2023-02-27 14:20:45.3982 ParameterBinding Information: 0 : BIND cmd line arg [e f] to position [3] DEBUG: 2023-02-27 14:20:47.6092 ParameterBinding Information: 0 : CALLING BeginProcessing ``` ## PARAMETERS ### -ArgumentList Specifies the parameters and parameter values for the command being traced. The alias for **ArgumentList** is **Args**. This feature is useful for debugging dynamic parameters. For more information about the behavior of **ArgumentList**, see [about_Splatting](../Microsoft.PowerShell.Core/About/about_Splatting.md#splatting-with-arrays). ```yaml Type: System.Object[] Parameter Sets: commandSet Aliases: Args Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Command Specifies a command that's being processed during the trace. When you use this parameter, PowerShell processes the command just as it would be processed in a pipeline. For example, command discovery isn't repeated for each incoming object. ```yaml Type: System.String Parameter Sets: commandSet Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Debugger Indicates that the cmdlet sends the trace output to the debugger. You can view the output in any user-mode or kernel mode debugger or in Visual Studio. This parameter also selects the default trace listener. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Expression Specifies the expression that's being processed during the trace. Enclose the expression in braces (`{}`). ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: expressionSet Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FilePath Specifies a file that the cmdlet sends the trace output to. This parameter also selects the file trace listener. ```yaml Type: System.String Parameter Sets: (All) Aliases: PSPath, Path Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Forces the command to run without asking for user confirmation. Used with the **FilePath** parameter. Even using the **Force** parameter, the cmdlet can't override security restrictions. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies input to the expression that's being processed during the trace. You can enter a variable that represents the input that the expression accepts, or pass an object through the pipeline. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -ListenerOption Specifies optional data to the prefix of each trace message in the output. The acceptable values for this parameter are: - `None` - `LogicalOperationStack` - `DateTime` - `Timestamp` - `ProcessId` - `ThreadId` - `Callstack` `None` is the default. These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **ListenerOption** parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. ```yaml Type: System.Diagnostics.TraceOptions Parameter Sets: (All) Aliases: Accepted values: None, LogicalOperationStack, DateTime, Timestamp, ProcessId, ThreadId, Callstack Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Name Specifies an array of PowerShell components that are traced. Enter the name of the trace source of each component. Wildcards are permitted. To find the trace sources on your computer, type `Get-TraceSource`. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Option Determines the type of events that are traced. The acceptable values for this parameter are: - `None` - `Constructor` - `Dispose` - `Finalizer` - `Method` - `Property` - `Delegates` - `Events` - `Exception` - `Lock` - `Error` - `Errors` - `Warning` - `Verbose` - `WriteLine` - `Data` - `Scope` - `ExecutionFlow` - `Assert` - `All` `All` is the default. The following values are combinations of other values: - `ExecutionFlow`: `Constructor`, `Dispose`, `Finalizer`, `Method`, `Delegates`, `Events`, `Scope` - `Data`: `Constructor`, `Dispose`, `Finalizer`, `Property`, `Verbose`, `WriteLine` - `Errors`: `Error`, `Exception` These values are defined as a flag-based enumeration. You can combine multiple values together to set multiple flags using this parameter. The values can be passed to the **Option** parameter as an array of values or as a comma-separated string of those values. The cmdlet will combine the values using a binary-OR operation. Passing values as an array is the simplest option and also allows you to use tab-completion on the values. ```yaml Type: System.Management.Automation.PSTraceSourceOptions Parameter Sets: (All) Aliases: Accepted values: None, Constructor, Dispose, Finalizer, Method, Property, Delegates, Events, Exception, Lock, Error, Errors, Warning, Verbose, WriteLine, Data, Scope, ExecutionFlow, Assert, All Required: False Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PSHost Indicates that the cmdlet sends the trace output to the PowerShell host. This parameter also selects the PSHost trace listener. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe objects that represent input to the expression to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSObject This cmdlet returns no output of its own. The traced command may return output. This cmdlet writes the command trace to the debug stream. ## NOTES Tracing is a method that developers use to debug and refine programs. When tracing, the program generates detailed messages about each step in its internal processing. The PowerShell tracing cmdlets are designed to help PowerShell developers, but they're available to all users. They let you monitor nearly every aspect of the functionality of the shell. A trace source is the part of each PowerShell component that manages tracing and generates trace messages for the component. To trace a component, you identify its trace source. Use `Get-TraceSource` to see a list of PowerShell components that are enabled for tracing. A trace listener receives the output of the trace and displays it to the user. You can elect to send the trace data to a user-mode or kernel-mode debugger, to the host or console, to a file, or to a custom listener derived from the **System.Diagnostics.TraceListener** class. ## RELATED LINKS [Get-TraceSource](Get-TraceSource.md) [Measure-Command](Measure-Command.md) [Set-TraceSource](Set-TraceSource.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Unblock-File.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/unblock-file?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Unblock-File --- # Unblock-File ## SYNOPSIS Unblocks files that were downloaded from the internet. ## SYNTAX ### ByPath (Default) ``` Unblock-File [-Path] <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ByLiteralPath ``` Unblock-File -LiteralPath <String[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet only works on the Windows and macOS platforms.** The `Unblock-File` cmdlet lets you open files that were downloaded from the internet. It unblocks PowerShell script files that were downloaded from the internet so you can run them, even when the PowerShell execution policy is **RemoteSigned**. By default, these files are blocked to protect the computer from untrusted files. Before using the `Unblock-File` cmdlet, review the file and its source and verify that it is safe to open. Internally, the `Unblock-File` cmdlet removes the **Zone.Identifier** alternate data stream, which has a value of `3` to indicate that it was downloaded from the internet. For more information about PowerShell execution policies, see [about_Execution_Policies](../Microsoft.PowerShell.Core/about/about_Execution_Policies.md). This cmdlet was introduced in Windows PowerShell 3.0. ## EXAMPLES ### Example 1: Unblock a file This command unblocks the `PowerShellTips.chm` file. ``` PS C:\> Unblock-File -Path C:\Users\User01\Documents\Downloads\PowerShellTips.chm ``` ### Example 2: Unblock multiple files This command unblocks all of the files in the `C:\Downloads` directory whose names include "PowerShell". Do not run a command like this one until you have verified that all files are safe. ``` PS C:\> dir C:\Downloads\*PowerShell* | Unblock-File ``` ### Example 3: Find and unblock scripts This command shows how to find and unblock PowerShell scripts. The first command uses the **Stream** parameter of the *Get-Item* cmdlet get files with the **Zone.Identifier** stream. The second command shows what happens when you run a blocked script in a PowerShell session in which the execution policy is **RemoteSigned**. The **RemoteSigned** policy prevents you from running scripts that are downloaded from the internet unless they are digitally signed. The third command uses the `Unblock-File` cmdlet to unblock the script so it can run in the session. ``` PS C:\> Get-Item * -Stream "Zone.Identifier" -ErrorAction SilentlyContinue FileName: C:\ps-test\Start-ActivityTracker.ps1 Stream Length ------ ------ Zone.Identifier 26 PS C:\> C:\ps-test\Start-ActivityTracker.ps1 C:\ps-test\Start-ActivityTracker.ps1 : File C:\ps-test\Start-ActivityTracker.ps1 cannot be loaded. The file C:\ps-test\Start-ActivityTracker.ps1 is not digitally signed. The script will not execute on the system. For more information, see about_Execution_Policies. At line:1 char:1 + C:\ps-test\Start-ActivityTracker.ps1 + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess PS C:\> Get-Item C:\ps-test\Start-ActivityTracker.ps1 | Unblock-File ``` ## PARAMETERS ### -LiteralPath Specifies the files to unblock. Unlike **Path**, the value of the **LiteralPath** parameter is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks (`'`). Single quotation marks tell PowerShell not to interpret any characters as escape sequences. ```yaml Type: System.String[] Parameter Sets: ByLiteralPath Aliases: PSPath, LP Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Path Specifies the files to unblock. Wildcard characters are supported. ```yaml Type: System.String[] Parameter Sets: ByPath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a file path to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES - Support for macOS was added in PowerShell 7. - The `Unblock-File` cmdlet works only in file system drives. - `Unblock-File` performs the same operation as the **Unblock** button on the **Properties** dialog box in File Explorer. - If you use the `Unblock-File` cmdlet on a file that is not blocked, the command has no effect on the unblocked file and the cmdlet does not generate errors. ## RELATED LINKS [about_Execution_Policies](../Microsoft.PowerShell.Core/About/about_Execution_Policies.md) [Get-Item](../Microsoft.PowerShell.Management/Get-Item.md) [Out-File](Out-File.md) [FileSystem Provider](../Microsoft.PowerShell.Core/about/about_FileSystem_Provider.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Unregister-Event.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 06/20/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/unregister-event?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Unregister-Event --- # Unregister-Event ## SYNOPSIS Cancels an event subscription. ## SYNTAX ### BySource (Default) ``` Unregister-Event [-SourceIdentifier] <String> [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### ById ``` Unregister-Event [-SubscriptionId] <Int32> [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Unregister-Event` cmdlet cancels an event subscription that was created by using the `Register-EngineEvent`, `Register-ObjectEvent`, or `Register-WmiEvent` cmdlet. When an event subscription is canceled, the event subscriber is deleted from the session and the subscribed events are no longer added to the event queue. When you cancel a subscription to an event created by using the `New-Event` cmdlet, the new event is also deleted from the session. `Unregister-Event` does not delete events from the event queue. To delete events, use the `Remove-Event` cmdlet. ## EXAMPLES ### Example 1: Cancel an event subscription by source identifier This command cancels the event subscription that has a source identifier of ProcessStarted. ```powershell Unregister-Event -SourceIdentifier "ProcessStarted" ``` To find the source identifier of an event, use the `Get-Event` cmdlet. To find the source identifier of an event subscription, use the `Get-EventSubscriber` cmdlet ### Example 2: Cancel an event subscription by subscription identifier This command cancels the event subscription that has a subscription identifier of 2. ```powershell Unregister-Event -SubscriptionId 2 ``` To find the subscription identifier of an event subscription, use the `Get-EventSubscriber` cmdlet. ### Example 3: Cancel all event subscriptions This example cancels all event subscriptions in the session. ```powershell Get-EventSubscriber -Force | Unregister-Event -Force ``` Using the **Force** parameter with `Get-EventSubscriber` gets all event subscriber objects in the session, including the subscribers that are hidden. The output is piped to `Unregister-Event`, which deletes the subscribers from the session. The **Force** parameter is required on `Unregister-Event` to remove any hidden subscribers. ## PARAMETERS ### -Force Cancels all event subscriptions, including subscriptions that were hidden by using the **SupportEvent** parameter of `Register-ObjectEvent`, `Register-WmiEvent`, and `Register-EngineEvent`. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SourceIdentifier Specifies a source identifier that this cmdlet cancels event subscriptions. A **SourceIdentifier** or **SubscriptionId** parameter must be included in every command. ```yaml Type: System.String Parameter Sets: BySource Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -SubscriptionId Specifies a source identifier ID that this cmdlet cancels event subscriptions. A **SourceIdentifier** or **SubscriptionId** parameter must be included in every command. ```yaml Type: System.Int32 Parameter Sets: ById Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSEventSubscriber You can pipe the output from `Get-EventSubscriber` to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES No event sources available on the Linux or macOS platforms. Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled. `Unregister-Event` cannot delete events created by using the `New-Event` cmdlet unless you have subscribed to the event by using the `Register-EngineEvent` cmdlet. To delete a custom event from the session, you must remove it programmatically or close the session. ## RELATED LINKS [Get-Event](Get-Event.md) [Get-EventSubscriber](Get-EventSubscriber.md) [New-Event](New-Event.md) [Register-EngineEvent](Register-EngineEvent.md) [Register-ObjectEvent](Register-ObjectEvent.md) [Remove-Event](Remove-Event.md) [Unregister-Event](Unregister-Event.md) [Wait-Event](Wait-Event.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Update-FormatData.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/update-formatdata?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Update-FormatData --- # Update-FormatData ## SYNOPSIS Updates the formatting data in the current session. ## SYNTAX ``` Update-FormatData [[-AppendPath] <String[]>] [-PrependPath <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Update-FormatData` cmdlet reloads the formatting data from formatting files into the current session. This cmdlet lets you update the formatting data without restarting PowerShell. Without parameters, `Update-FormatData` reloads the formatting files that it loaded previously. You can use the parameters of `Update-FormatData` to add new formatting files to the session. Formatting files are text files in XML format with the `format.ps1xml` file name extension. The formatting data in the files defines the display of Microsoft .NET Framework objects in the session. When PowerShell starts, it loads the format data from the PowerShell source code. However, you can create custom format.ps1xml files to update formatting in the current session. You can use `Update-FormatData` to reload the formatting data into the current session without restarting PowerShell. This is useful when you have added or changed a formatting file, but do not want to interrupt the session. For more information about formatting files in PowerShell, see [about_Format.ps1xml](../Microsoft.PowerShell.Core/About/about_Format.ps1xml.md). ## EXAMPLES ### Example 1: Reload previously loaded formatting files ```powershell Update-FormatData ``` This command reloads the formatting files that it loaded previously. ### Example 2: Reload formatting files and trace and log formatting files ```powershell Update-FormatData -AppendPath Trace.format.ps1xml, Log.format.ps1xml ``` This command reloads the formatting files into the session, including two new files, `Trace.format.ps1xml` and `Log.format.ps1xml`. Because the command uses the **AppendPath** parameter, the formatting data in the new files is loaded after the formatting data from the built-in files. The **AppendPath** parameter is used because the new files contain formatting data for objects that are not referenced in the built-in files. ### Example 3: Edit a formatting file and reload it ```powershell Update-FormatData -PrependPath "C:\test\NewFiles.format.ps1xml" # Edit the NewFiles.format.ps1 file. Update-FormatData ``` This example shows how to reload a formatting file after you have edited it. The first command adds the `NewFiles.format.ps1xml` file to the session. It uses the **PrependPath** parameter because the file contains formatting data for objects that are referenced in the built-in files. After adding the `NewFiles.format.ps1xml` file and testing it in these sessions, the author edits the file. The second command uses the `Update-FormatData` cmdlet to reload the formatting files. Because the `NewFiles.format.ps1xml` file was previously loaded, `Update-FormatData` automatically reloads it without using parameters. ## PARAMETERS ### -AppendPath Specifies formatting files that this cmdlet adds to the session. The files are loaded after PowerShell loads the built-in formatting files. When formatting .NET objects, PowerShell uses the first formatting definition that it finds for each .NET type. If you use the **AppendPath** parameter, PowerShell searches the data from the built-in files before it encounters the formatting data that you are adding. Use this parameter to add a file that formats a .NET object that is not referenced in the built-in formatting files. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: PSPath, Path Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -PrependPath Specifies formatting files that this cmdlet adds to the session. The files are loaded before PowerShell loads the built-in formatting files. When formatting .NET objects, PowerShell uses the first formatting definition that it finds for each .NET type. If you use the **PrependPath** parameter, PowerShell searches the data from the files that you are adding before it encounters the formatting data from the built-in files. Use this parameter to add a file that formats a .NET object that is also referenced in the built-in formatting files. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains the append path to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES - `Update-FormatData` also updates the formatting data for commands in the session that were imported from modules. If the formatting file for a module changes, you can run an `Update-FormatData` command to update the formatting data for imported commands. You do not need to import the module again. ## RELATED LINKS [Get-FormatData](Get-FormatData.md) [Export-FormatData](Export-FormatData.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Update-List.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/02/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/update-list?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Update-List --- # Update-List ## SYNOPSIS Adds items to and removes items from a property value that contains a collection of objects. ## SYNTAX ### AddRemoveSet (Default) ``` Update-List [-Add <Object[]>] [-Remove <Object[]>] [-InputObject <PSObject>] [[-Property] <String>] [<CommonParameters>] ``` ### ReplaceSet ``` Update-List -Replace <Object[]> [-InputObject <PSObject>] [[-Property] <String>] [<CommonParameters>] ``` ## DESCRIPTION The `Update-List` cmdlet adds, removes, or replaces items in a property value of an object and returns the updated object. This cmdlet is designed for properties that contain collections of objects. The **Add** and **Remove** parameters add individual items to and remove them from the collection. The **Replace** parameter replaces the entire collection. If you don't specify a property in the command, `Update-List` returns a hashtable that describes the update instead of updating the object. Later, you can use this change set to update a list object. This cmdlet works only when the property that's being updated supports the **IList** interface that `Update-List` uses. Also, any `Set` cmdlets that accept an update must support the **IList** interface. This cmdlet was reintroduced in PowerShell 7. ## EXAMPLES ### Example 1: Add items to a property value In this example we create a class that represents a deck of cards where the cards are stored as a **List** collection object. The **NewDeck()** method uses `Update-List`to add a complete deck of card values to the **Cards** collection. ```powershell class Cards { [System.Collections.Generic.List[string]]$Cards [string]$Name Cards([string]$_name) { $this.Name = $_name $this.Cards = [System.Collections.Generic.List[string]]::new() } NewDeck() { $_suits = "`u{2663}","`u{2666}","`u{2665}","`u{2660}" $_values = 'A',2,3,4,5,6,7,8,9,10,'J','Q','K' $_deck = foreach ($s in $_suits){ foreach ($v in $_values){ "$v$s"} } $this | Update-List -Property Cards -Add $_deck | Out-Null } Show() { Write-Host Write-Host $this.Name ": " $this.Cards[0..12] if ($this.Cards.Count -gt 13) { Write-Host (' ' * ($this.Name.Length+3)) $this.Cards[13..25] } if ($this.Cards.Count -gt 26) { Write-Host (' ' * ($this.Name.Length+3)) $this.Cards[26..38] } if ($this.Cards.Count -gt 39) { Write-Host (' ' * ($this.Name.Length+3)) $this.Cards[39..51] } } Shuffle() { $this.Cards = Get-Random -InputObject $this.Cards -Count 52 } Sort() { $this.Cards.Sort() } } ``` > [!NOTE] > The `Update-List` cmdlet outputs the updated object to the pipeline. We pipe the output to > `Out-Null` to suppress the unwanted display. ### Example 2: Add and remove items of a collection property Continuing with the code in Example 1, we will create instances of the **Cards** class to represent a deck of cards and the cards held by two players. We use the `Update-List` cmdlet to add cards to the players' hands and to remove cards from the deck. ```powershell $player1 = [Cards]::new('Player 1') $player2 = [Cards]::new('Player 2') $deck = [Cards]::new('Deck') $deck.NewDeck() $deck.Shuffle() $deck.Show() # Deal two hands $player1 | Update-List -Property Cards -Add $deck.Cards[0,2,4,6,8] | Out-Null $player2 | Update-List -Property Cards -Add $deck.Cards[1,3,5,7,9] | Out-Null $deck | Update-List -Property Cards -Remove $player1.Cards | Out-Null $deck | Update-List -Property Cards -Remove $player2.Cards | Out-Null $player1.Show() $player2.Show() $deck.Show() ``` ```Output Deck : 4♦ 7♥ J♦ 5♣ A♣ 8♦ J♣ Q♥ 6♦ 3♦ 9♦ 6♣ 2♣ K♥ 4♠ 10♥ 8♠ 10♦ 9♠ 6♠ K♦ 7♣ 3♣ Q♣ A♥ Q♠ 3♥ 5♥ 2♦ 5♠ J♥ J♠ 10♣ 4♥ Q♦ 10♠ 4♣ 2♠ 2♥ 6♥ 7♦ A♠ 5♦ 8♣ 9♥ K♠ 7♠ 3♠ 9♣ A♦ K♣ 8♥ Player 1 : 4♦ J♦ A♣ J♣ 6♦ Player 2 : 7♥ 5♣ 8♦ Q♥ 3♦ Deck : 9♦ 6♣ 2♣ K♥ 4♠ 10♥ 8♠ 10♦ 9♠ 6♠ K♦ 7♣ 3♣ Q♣ A♥ Q♠ 3♥ 5♥ 2♦ 5♠ J♥ J♠ 10♣ 4♥ Q♦ 10♠ 4♣ 2♠ 2♥ 6♥ 7♦ A♠ 5♦ 8♣ 9♥ K♠ 7♠ 3♠ 9♣ A♦ K♣ 8♥ ``` The output shows the state of the deck before the cards were dealt to the players. You can see that each player received five cards from the deck. The final output shows the state of the deck after dealing the cards to the players. `Update-List` was used to select the cards from the deck and add them to the players' collection. Then the players' cards were removed from the deck using `Update-List`. ### Example 3: Add and remove items in a single command `Update-List` allows you to use the **Add** and **Remove** parameters in a single command. In this example, Player 1 wants to discard the `4♦` and `6♦` and get two new cards. ```powershell # Player 1 wants two new cards - remove 2 cards & add 2 cards $player1 | Update-List -Property Cards -Remove $player1.Cards[0,4] -Add $deck.Cards[0..1] | Out-Null $player1.Show() # remove dealt cards from deck $deck | Update-List -Property Cards -Remove $deck.Cards[0..1] | Out-Null $deck.Show() ``` ```Output Player 1 : J♦ A♣ J♣ 9♦ 6♣ Deck : 2♣ K♥ 4♠ 10♥ 8♠ 10♦ 9♠ 6♠ K♦ 7♣ 3♣ Q♣ A♥ Q♠ 3♥ 5♥ 2♦ 5♠ J♥ J♠ 10♣ 4♥ Q♦ 10♠ 4♣ 2♠ 2♥ 6♥ 7♦ A♠ 5♦ 8♣ 9♥ K♠ 7♠ 3♠ 9♣ A♦ K♣ 8♥ ``` ### Example 4: Apply a change set to a list object If you don't specify a property, `Update-List` returns a hashtable that describes the update instead of updating the object. You can cast the hashtable to a **System.PSListModifier** object and use the `ApplyTo()` method to apply the change set to a list. ```powershell $list = [System.Collections.ArrayList] (1, 43, 2) $changeInstructions = Update-List -Remove 43 -Add 42 $changeInstructions ``` ```Output Name Value ---- ----- Add {42} Remove {43} ``` ```powershell ([pslistmodifier]($changeInstructions)).ApplyTo($list) $list ``` ```Output 1 2 42 ``` ## PARAMETERS ### -Add Specifies the property values to be added to the collection. Enter the values in the order that they should appear in the collection. ```yaml Type: System.Object[] Parameter Sets: AddRemoveSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects to be updated. You can also pipe the object to be updated to `Update-List`. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Property Specifies the property that contains the collection that's being updated. If you omit this parameter, `Update-List` returns an object that represents the change instead of changing the object. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Remove Specifies the property values to be removed from the collection. ```yaml Type: System.Object[] Parameter Sets: AddRemoveSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Replace Specifies a new collection. This parameter replaces all items in the original collection with the items specified by this parameter. ```yaml Type: System.Object[] Parameter Sets: ReplaceSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe the object to be updated to this cmdlet. ## OUTPUTS ### System.Collections.Hashtable By default, this cmdlet returns a hashtable that describes the update. ### System.Object When you specify the **Property** parameter, this cmdlet returns the updated object. ## NOTES ## RELATED LINKS [Select-Object](Select-Object.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Update-TypeData.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 08/07/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/update-typedata?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Update-TypeData --- # Update-TypeData ## SYNOPSIS Updates the extended type data in the session. ## SYNTAX ### FileSet (Default) ``` Update-TypeData [[-AppendPath] <String[]>] [-PrependPath <String[]>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### DynamicTypeSet ``` Update-TypeData [-MemberType <PSMemberTypes>] [-MemberName <String>] [-Value <Object>] [-SecondValue <Object>] [-TypeConverter <Type>] [-TypeAdapter <Type>] [-SerializationMethod <String>] [-TargetTypeForDeserialization <Type>] [-SerializationDepth <Int32>] [-DefaultDisplayProperty <String>] [-InheritPropertySerializationSet <Nullable`1>] [-StringSerializationSource <String>] [-DefaultDisplayPropertySet <String[]>] [-DefaultKeyPropertySet <String[]>] [-PropertySerializationSet <String[]>] -TypeName <String> [-Force] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### TypeDataSet ``` Update-TypeData [-Force] [-TypeData] <TypeData[]> [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The `Update-TypeData` cmdlet updates the extended type data in the session by reloading the `Types.ps1xml` files into memory and adding new extended type data. By default, PowerShell loads extended type data as it is needed. Without parameters, `Update-TypeData` reloads all of the `Types.ps1xml` files that it has loaded in the session, including any type files that you added. You can use the parameters of `Update-TypeData` to add new type files and add and replace extended type data. The `Update-TypeData` cmdlet can be used to preload all type data. This feature is particularly useful when you are developing types and want to load those new types for testing purposes. Beginning in Windows PowerShell 3.0, you can use `Update-TypeData` to add and replace extended type data in the session without using a `Types.ps1xml` file. Type data that is added dynamically, that is, without a file, is added only to the current session. To add the type data to all sessions, add an `Update-TypeData` command to your PowerShell profile. For more information, see [about_Profiles](../Microsoft.PowerShell.Core/About/about_Profiles.md). Also, beginning in Windows PowerShell 3.0, you can use the `Get-TypeData` cmdlet to get the extended types in the current session and the `Remove-TypeData` cmdlet to delete extended types from the current session. Exceptions that occur in properties, or from adding properties to an `Update-TypeData` command, do not report errors. This is to suppress exceptions that would occur in many common types during formatting and outputting. If you are getting .NET properties, you can work around the suppression of exceptions by using method syntax instead, as shown in the following example: `"hello".get_Length()` Note that method syntax can only be used with .NET properties. Properties that are added by running the `Update-TypeData` cmdlet cannot use method syntax. For more information about the `Types.ps1xml` files in PowerShell, see [about_Types.ps1xml](../Microsoft.PowerShell.Core/About/about_Types.ps1xml.md). ## EXAMPLES ### Example 1: Update extended types ```powershell Update-TypeData ``` This command updates the extended type configuration from the `Types.ps1xml` files that have already been used in the session. ### Example 2: Update types multiple times This example shows how to update the types in a type file multiple times in the same session. The first command updates the extended type configuration from the `Types.ps1xml` files, processing the `TypesA.types.ps1xml` and `TypesB.types.ps1xml` files first. The second command shows how to update the `TypesA.types.ps1xml` again, such as you might do if you added or changed a type in the file. You can either repeat the previous command for the `TypesA.types.ps1xml` file, or run an `Update-TypeData` command without parameters, because `TypesA.types.ps1xml` is already in the type file list for the current session. ```powershell Update-TypeData -PrependPath TypesA.types.ps1xml, TypesB.types.ps1xml Update-TypeData -PrependPath TypesA.types.ps1xml ``` ### Example 3: Add a script property to DateTime objects This example uses `Update-TypeData` to add the **Quarter** script property to **System.DateTime** objects in the current session, such as those returned by the `Get-Date` cmdlet. ```powershell $typeDataParams = @{ TypeName = 'System.DateTime' MemberType = 'ScriptProperty' MemberName = 'Quarter' Value = { switch ($this.Month) { { $_ -in @(1, 2, 3) } { return 'Q1' } { $_ -in @(4, 5, 6) } { return 'Q2' } { $_ -in @(7, 8, 9) } { return 'Q3' } default { return 'Q4' } } } } Update-TypeData @typeDataParams (Get-Date).Quarter ``` ```Output Q1 ``` The `Update-TypeData` command uses the **TypeName** parameter to specify **the System.DateTime** type, the **MemberName** parameter to specify a name for the new property, the **MemberType** property to specify the **ScriptProperty** type, and the **Value** parameter to specify the script that determines the annual quarter. The value of the **Value** property is a script that calculates the current annual quarter. The script block uses the `$this` automatic variable to represent the current instance of the object and the In operator to determine whether the month value appears in each integer array. For more information about the `-in` operator, see [about_Comparison_Operators](../Microsoft.PowerShell.Core/about/about_Comparison_Operators.md). The second command gets the new Quarter property of the current date. ### Example 4: Update a type that displays in lists by default This example shows how to set the properties of a type that displays in lists by default, that is, when no properties are specified. Because the type data is not specified in a `Types.ps1xml` file, it is effective only in the current session. ```powershell Get-Date | Format-List Update-TypeData -TypeName "System.DateTime" -DefaultDisplayPropertySet @( 'DateTime' 'DayOfYear' 'Quarter' ) Get-Date | Format-List ``` ```Output DisplayHint : DateTime Date : 8/7/2024 12:00:00 AM Day : 7 DayOfWeek : Wednesday DayOfYear : 220 Hour : 10 Kind : Local Millisecond : 568 Microsecond : 308 Nanosecond : 600 Minute : 34 Month : 8 Second : 43 Ticks : 638586236835683086 TimeOfDay : 10:34:43.5683086 Year : 2024 DateTime : Wednesday, August 7, 2024 10:34:43 AM Quarter : Q3 DateTime : Wednesday, August 7, 2024 10:34:43 AM DayOfYear : 220 Quarter : Q3 ``` The first command shows the list view for the `Get-Date` command, which outputs a **System.DateTime** object that represents the current date. The command uses a pipeline operator (`|`) to send the **DateTime** object to the `Format-List` cmdlet. Because the `Format-List` command does not specify the properties to display in the list, PowerShell displays every public, non-hidden property for the object. The second command uses the `Update-TypeData` cmdlet to set the default list properties for the **System.DateTime** type. The command uses the **TypeName** parameter to specify the type and the **DefaultDisplayPropertySet** parameter to specify the default properties for a list. The selected properties include the new **Quarter** script property that was added in a previous example. The last command gets the current date and displays it in a list format again. It only displays the properties defined in the `Update-TypeData` command, instead of the full list of properties. ### Example 5: Set the property a type displays in wide format This example demonstrates how to create a new script property and use it as the default property displayed when the type is passed to the `Format-Wide` cmdlet. ```powershell Get-Command *File* | Format-Wide ``` ```Output Set-AppPackageProvisionedDataFile Set-ProvisionedAppPackageDataFile Set-ProvisionedAppXDataFile Write-FileSystemCache Write-FileSystemCache Add-PoshGitToProfile Block-FileShareAccess Clear-FileStorageTier Close-SmbOpenFile Debug-FileShare Disable-NetIPHttpsProfile Enable-NetIPHttpsProfile Get-FileIntegrity Get-FileShare Get-FileShareAccessControlEntry Get-FileStorageTier Get-NetConnectionProfile Get-NetFirewallHyperVProfile Get-NetFirewallProfile Get-SmbOpenFile Get-StorageFileServer Get-SupportedFileSystems Grant-FileShareAccess New-FileShare New-NetFirewallHyperVProfile New-ScriptFileInfo New-ScriptFileInfo New-StorageFileServer Publish-BCFileContent Remove-FileShare Remove-NetFirewallHyperVProfile Remove-PoshGitFromProfile Remove-StorageFileServer Repair-FileIntegrity Revoke-FileShareAccess Set-FileIntegrity Set-FileShare Set-FileStorageTier Set-NetConnectionProfile Set-NetFirewallHyperVProfile Set-NetFirewallProfile Set-StorageBusProfile Set-StorageFileServer Test-ScriptFileInfo Test-ScriptFileInfo Unblock-FileShareAccess Update-ScriptFileInfo Update-ScriptFileInfo Add-BitsFile Get-AppLockerFileInformation Get-FileHash Get-PSScriptFileInfo Import-PowerShellDataFile New-FileCatalog New-PSRoleCapabilityFile New-PSScriptFileInfo New-PSSessionConfigurationFile New-TemporaryFile Out-File Set-AppXProvisionedDataFile Test-FileCatalog Test-PSScriptFileInfo Test-PSSessionConfigurationFile Unblock-File Update-PSScriptFileInfo FileDialogBroker.exe FileHistory.exe forfiles.exe openfiles.exe ``` ```powershell $typeDataParams = @{ TypeName = 'System.Management.Automation.CommandInfo' DefaultDisplayProperty = 'FullyQualifiedName' MemberType = 'ScriptProperty' MemberName = 'FullyQualifiedName' Value = { [OutputType([string])] param() # For executables, return the path to the application. if ($this -is [System.Management.Automation.ApplicationInfo]) { return $this.Path } # For commands defined outside a module, return only the name. if ([string]::IsNullOrEmpty($this.ModuleName)) { return $this.Name } # Return the fully-qualified command name "<ModuleName>\<CommandName>" return '{0}\{1}' -f $this.ModuleName, $this.Name } } Update-TypeData @typeDataParams Get-Command *File* | Format-Wide ``` ```Output Dism\Set-AppPackageProvisionedDataFile Dism\Set-ProvisionedAppPackageDataFile Dism\Set-ProvisionedAppXDataFile Storage\Write-FileSystemCache VMDirectStorage\Write-FileSystemCache posh-git\Add-PoshGitToProfile Storage\Block-FileShareAccess Storage\Clear-FileStorageTier SmbShare\Close-SmbOpenFile Storage\Debug-FileShare NetworkTransition\Disable-NetIPHttpsProfile NetworkTransition\Enable-NetIPHttpsProfile Storage\Get-FileIntegrity Storage\Get-FileShare Storage\Get-FileShareAccessControlEntry Storage\Get-FileStorageTier NetConnection\Get-NetConnectionProfile NetSecurity\Get-NetFirewallHyperVProfile NetSecurity\Get-NetFirewallProfile SmbShare\Get-SmbOpenFile Storage\Get-StorageFileServer Storage\Get-SupportedFileSystems Storage\Grant-FileShareAccess Storage\New-FileShare NetSecurity\New-NetFirewallHyperVProfile PowerShellGet\New-ScriptFileInfo PowerShellGet\New-ScriptFileInfo Storage\New-StorageFileServer BranchCache\Publish-BCFileContent Storage\Remove-FileShare NetSecurity\Remove-NetFirewallHyperVProfile posh-git\Remove-PoshGitFromProfile Storage\Remove-StorageFileServer Storage\Repair-FileIntegrity Storage\Revoke-FileShareAccess Storage\Set-FileIntegrity Storage\Set-FileShare Storage\Set-FileStorageTier NetConnection\Set-NetConnectionProfile NetSecurity\Set-NetFirewallHyperVProfile NetSecurity\Set-NetFirewallProfile StorageBusCache\Set-StorageBusProfile Storage\Set-StorageFileServer PowerShellGet\Test-ScriptFileInfo PowerShellGet\Test-ScriptFileInfo Storage\Unblock-FileShareAccess PowerShellGet\Update-ScriptFileInfo PowerShellGet\Update-ScriptFileInfo BitsTransfer\Add-BitsFile AppLocker\Get-AppLockerFileInformation Microsoft.PowerShell.Utility\Get-FileHash Microsoft.PowerShell.PSResourceGet\Get-PSScriptFileInfo Microsoft.PowerShell.Utility\Import-PowerShellDataFile Microsoft.PowerShell.Security\New-FileCatalog Microsoft.PowerShell.Core\New-PSRoleCapabilityFile Microsoft.PowerShell.PSResourceGet\New-PSScriptFileInfo Microsoft.PowerShell.Core\New-PSSessionConfigurationFile Microsoft.PowerShell.Utility\New-TemporaryFile Microsoft.PowerShell.Utility\Out-File Dism\Set-AppXProvisionedDataFile Microsoft.PowerShell.Security\Test-FileCatalog Microsoft.PowerShell.PSResourceGet\Test-PSScriptFileInfo Microsoft.PowerShell.Core\Test-PSSessionConfigurationFile Microsoft.PowerShell.Utility\Unblock-File Microsoft.PowerShell.PSResourceGet\Update-PSScriptFileInfo C:\WINDOWS\system32\FileDialogBroker.exe C:\WINDOWS\system32\FileHistory.exe C:\WINDOWS\system32\forfiles.exe C:\WINDOWS\system32\openfiles.exe ``` The first command uses the `Get-Command` cmdlet to return every command with a name containing the word `File`. It pipes the output to the `Format-Wide` cmdlet, which shows the names of the commands in columns. Next, the example uses `Update-TypeData` to define both the **DefaultDisplayProperty** and a new script property for the **CommandInfo** type. The output for `Get-Command` returns **CommandInfo** objects and objects derived from that type. The new script property, **FullyQualifiedName**, returns the full path to executable applications and the fully qualified name for cmdlets, which prefixes the cmdlet name with the module that defines it. The `Update-TypeData` cmdlet is able to define the new script property and use it as the **DefaultDisplayProperty** in the same command. Finally, the output shows the results of the `Get-Command` displayed in wide format after the type update. It shows the fully qualified name for cmdlets and the full path to executable applications. ### Example 6: Update type data for a piped object ```powershell $typeDataParams = @{ MemberType = 'ScriptProperty' MemberName = 'SupportsUpdatableHelp' Value = { [OutputType([bool])] param() return (-not [string]::IsNullOrEmpty($this.HelpInfoUri)) } } Get-Module Microsoft.PowerShell.Utility | Update-TypeData @typeDataParams Get-Module -ListAvailable -Name Microsoft.PowerShell.* | Format-Table Name, SupportsUpdatableHelp ``` ```Output Name SupportsUpdatableHelp ---- --------------------- Microsoft.PowerShell.Archive True Microsoft.PowerShell.Diagnostics True Microsoft.PowerShell.Host True Microsoft.PowerShell.Management True Microsoft.PowerShell.PSResourceGet True Microsoft.PowerShell.Security True Microsoft.PowerShell.Utility True Microsoft.PowerShell.Operation.Validation True Microsoft.PowerShell.LocalAccounts True ``` This example demonstrates that when you pipe an object to `Update-TypeData`, `Update-TypeData` adds extended type data for the object type. This technique is quicker than using the `Get-Member` cmdlet or the `Get-Type` method to get the object type. However, if you pipe a collection of objects to `Update-TypeData`, it updates the type data of the first object type and then returns an error for all other objects in the collection because the member is already defined on the type. The first command uses the `Get-Module` cmdlet to get the **Microsoft.PowerShell.Utility** module. The command pipes the module object to the `Update-TypeData` cmdlet, which updates the type data for the **System.Management.Automation.PSModuleInfo** type and the types derived from it, such as the **ModuleInfoGrouping** type that `Get-Module` returns when you use the **ListAvailable** parameter in the command. The `Update-TypeData` commands adds the **SupportsUpdatableHelp** script property to all imported modules. The value of the **Value** parameter is a script that returns `$true` if the **HelpInfoUri** property of the module is populated and `$false` otherwise. The second command pipes the module objects from `Get-Module` to the `Format-Table` cmdlet, which displays the **Name** and **SupportsUpdatableHelp** properties of the available modules. ## PARAMETERS ### -AppendPath Specifies the path to optional `.ps1xml` files. The specified files are loaded in the order that they are listed after the built-in files are loaded. You can also pipe an **AppendPath** value to `Update-TypeData`. ```yaml Type: System.String[] Parameter Sets: FileSet Aliases: PSPath, Path Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -DefaultDisplayProperty Specifies the property of the type that is displayed by the `Format-Wide` cmdlet when no other properties are specified. Type the name of a standard or extended property of the type. The value of this parameter can be the name of a type that is added in the same command. This value is effective only when there are no wide views defined for the type in a `Format.ps1xml` file. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String Parameter Sets: DynamicTypeSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DefaultDisplayPropertySet Specifies one or more properties of the type. These properties are displayed by the `Format-List`, `Format-Table`, and `Format-Custom` cmdlets when no other properties are specified. Type the names of standard or extended properties of the type. The value of this parameter can be the names of types that are added in the same command. This value is effective only when there are no list, table, or custom views, respectively, defined for the type in a `Format.ps1xml` file. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String[] Parameter Sets: DynamicTypeSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DefaultKeyPropertySet Specifies one or more properties of the type. These properties are used by the `Group-Object` and `Sort-Object` cmdlets when no other properties are specified. Type the names of standard or extended properties of the type. The value of this parameter can be the names of types that are added in the same command. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String[] Parameter Sets: DynamicTypeSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Indicates that the cmdlet uses the specified type data, even if type data has already been specified for that type. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: DynamicTypeSet, TypeDataSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InheritPropertySerializationSet Indicates whether the set of properties that are serialized is inherited. The default value is `$null`. The acceptable values for this parameter are: - `$true`. The property set is inherited. - `$false`. The property set is not inherited. - `$null`. Inheritance is not defined. This parameter is valid only when the value of the **SerializationMethod** parameter is `SpecificProperties`. When the value of this parameter is `$false`, the **PropertySerializationSet** parameter is required. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Nullable`1[System.Boolean] Parameter Sets: DynamicTypeSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MemberName Specifies the name of a property or method. Use this parameter with the **TypeName**, **MemberType**, **Value** and **SecondValue** parameters to add or change a property or method of a type. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String Parameter Sets: DynamicTypeSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MemberType Specifies the type of the member to add or change. Use this parameter with the **TypeName**, **MemberType**, **Value** and **SecondValue** parameters to add or change a property or method of a type. The acceptable values for this parameter are: - AliasProperty - CodeMethod - CodeProperty - Noteproperty - ScriptMethod - ScriptProperty For information about these values, see [PSMemberTypes Enumeration](/dotnet/api/system.management.automation.psmembertypes). This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.PSMemberTypes Parameter Sets: DynamicTypeSet Aliases: Accepted values: NoteProperty, AliasProperty, ScriptProperty, CodeProperty, ScriptMethod, CodeMethod Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PrependPath Specifies the path to the optional `.ps1xml` files. The specified files are loaded in the order that they are listed before the built-in files are loaded. ```yaml Type: System.String[] Parameter Sets: FileSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PropertySerializationSet Specifies the names of properties that are serialized. Use this parameter when the value of the **SerializationMethod** parameter is **SpecificProperties**. ```yaml Type: System.String[] Parameter Sets: DynamicTypeSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SecondValue Specifies additional values for **AliasProperty**, **ScriptProperty**, **CodeProperty**, or **CodeMethod** members. Use this parameter with the **TypeName**, **MemberType**, **Value**, and **SecondValue** parameters to add or change a property or method of a type. When the value of the **MemberType** parameter is `AliasProperty`, the value of the **SecondValue** parameter must be a data type. PowerShell converts (that is, casts) the value of the alias property to the specified type. For example, if you add an alias property that provides an alternate name for a string property, you can also specify a **SecondValue** of **System.Int32** to convert the aliased string value to an integer. When the value of the **MemberType** parameter is `ScriptProperty`, you can use the **SecondValue** parameter to specify an additional script block. The script block in the value of the **Value** parameter gets the value of a variable. The script block in the value of the **SecondValue** parameter set the value of the variable. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Object Parameter Sets: DynamicTypeSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SerializationDepth Specifies how many levels of type objects are serialized as strings. The default value `1` serializes the object and its properties. A value of `0` serializes the object, but not its properties. A value of `2` serializes the object, its properties, and any objects in property values. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Int32 Parameter Sets: DynamicTypeSet Aliases: Required: False Position: Named Default value: 1 Accept pipeline input: False Accept wildcard characters: False ``` ### -SerializationMethod Specifies a serialization method for the type. A serialization method determines which properties of the type are serialized and the technique that is used to serialize them. The acceptable values for this parameter are: - `AllPublicProperties`. Serialize all public properties of the type. You can use the **SerializationDepth** parameter to determine whether child properties are serialized. - `String`. Serialize the type as a string. You can use the **StringSerializationSource** to specify a property of the type to use as the serialization result. Otherwise, the type is serialized by using the **ToString** method of the object. - `SpecificProperties`. Serialize only the specified properties of this type. Use the **PropertySerializationSet** parameter to specify the properties of the type that are serialized. You can also use the **InheritPropertySerializationSet** parameter to determine whether the property set is inherited and the **SerializationDepth** parameter to determine whether child properties are serialized. In PowerShell, serialization methods are stored in **PSStandardMembers** internal objects. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String Parameter Sets: DynamicTypeSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -StringSerializationSource Specifies the name of a property of the type. The value of specified property is used as the serialization result. This parameter is valid only when the value of the **SerializationMethod** parameter is String. ```yaml Type: System.String Parameter Sets: DynamicTypeSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TargetTypeForDeserialization Specifies the type to which object of this type are converted when they are deserialized. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Type Parameter Sets: DynamicTypeSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TypeAdapter Specifies the type of a type adapter, such as **Microsoft.PowerShell.Cim.CimInstanceAdapter**. A type adapter enables PowerShell to get the members of a type. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Type Parameter Sets: DynamicTypeSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TypeConverter Specifies a type converter to convert values between different types. If a type converter is defined for a type, an instance of the type converter is used for the conversion. Enter a **System.Type** value that is derived from the **System.ComponentModel.TypeConverter** or **System.Management.Automation.PSTypeConverter** classes. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Type Parameter Sets: DynamicTypeSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TypeData Specifies an array of type data that this cmdlet adds to the session. Enter a variable that contains a **TypeData** object or a command that gets a **TypeData** object, such as a `Get-TypeData` command. You can also pipe a **TypeData** object to `Update-TypeData`. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Management.Automation.Runspaces.TypeData[] Parameter Sets: TypeDataSet Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -TypeName Specifies the name of the type to extend. For types in the **System** namespace, enter the short name. Otherwise, the full type name is required. Wildcards are not supported. You can pipe type names to `Update-TypeData`. When you pipe an object to `Update-TypeData`, `Update-TypeData` gets the type name of the object and type data to the object type. Use this parameter with the **MemberName**, **MemberType**, **Value** and **SecondValue** parameters to add or change a property or method of a type. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.String Parameter Sets: DynamicTypeSet Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Value Specifies the value of the property or method. If you add an `AliasProperty`, `CodeProperty`, `ScriptProperty`, or `CodeMethod` member, you can use the **SecondValue** parameter to add additional information. Use this parameter with the **MemberName**, **MemberType**, **Value** and **SecondValue** parameters to add or change a property or method of a type. This parameter was introduced in Windows PowerShell 3.0. ```yaml Type: System.Object Parameter Sets: DynamicTypeSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains the values of the **AppendPath**, **TypeName**, or **TypeData** parameters to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES ## RELATED LINKS [about_Types.ps1xml](../Microsoft.PowerShell.Core/About/about_Types.ps1xml.md) [Get-TypeData](Get-TypeData.md) [Remove-TypeData](Remove-TypeData.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Wait-Debugger.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 09/03/2024 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/wait-debugger?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Wait-Debugger --- # Wait-Debugger ## SYNOPSIS Stops a script in the debugger before running the next statement in the script. ## SYNTAX ``` Wait-Debugger [<CommonParameters>] ``` ## DESCRIPTION Stops the PowerShell script execution engine at the point immediately after the `Wait-Debugger` cmdlet and waits for a debugger to be attached. > [!CAUTION] > Make sure you remove the `Wait-Debugger` lines after you are done. A running script appears to be > hung when it's stopped at a `Wait-Debugger`. For more information about debugging in PowerShell, see [about_Debuggers](/powershell/module/microsoft.powershell.core/about/about_debuggers). ## EXAMPLES ### Example 1: Insert breakpoint for debugging The file `dbgtest.ps1` contains a function `Test-Condition`. The `Wait-Debugger` command was inserted in the function to stop the script execution at that point. When you run the function, the script stops at the `Wait-Debugger` line and enters the command-line debugger. The `l` command lists the script lines, and you can use other debugger commands to inspect the script state. ```powershell function Test-Condition { [CmdletBinding()] param ( [Parameter(Mandatory)] [string]$Name, [string]$Message = "Hello, $Name!" ) if ($Name -eq $Env:USERNAME) { Write-Output "$Message" } else { # Remove after debugging Wait-Debugger Write-Output "$Name is not the current user." } } ``` ``` PS D:\> Test-Condition Fred Entering debug mode. Use h or ? for help. At D:\temp\test\dbgtest.ps1:13 char:9 + Wait-Debugger + ~~~~~~~~~~~~~ [DBG]: PS D:\>> l 8: 9: if ($Name -eq $Env:USERNAME) { 10: Write-Output "$Message" 11: } else { 12: # Remove after debugging 13:* Wait-Debugger 14: 15: Write-Output "$Name is not the current user." 16: } 17: } [DBG]: PS D:\>> $Env:USERNAME User01 [DBG]: PS D:\>> exit PS D:\> ``` Notice that output from the `l` shows that the script execution is stopped at the `Wait-Debugger` on line 13. ### Example 2: Insert breakpoint for debugging a DSC resource In this example, the `Wait-Debugger` command was inserted in the `CopyFile` method of a DSC resource. This is similar to using `Enable-RunspaceDebug -BreakAll` in a DSC resource but breaks at a specific point in the script. ``` [DscResource()] class FileResource { [DscProperty(Key)] [string] $Path [DscProperty(Mandatory)] [Ensure] $Ensure [DscProperty(Mandatory)] [string] $SourcePath [DscProperty(NotConfigurable)] [Nullable[datetime]] $CreationTime [void] Set() { $fileExists = $this.TestFilePath($this.Path) if ($this.Ensure -eq [Ensure]::Present) { if (! $fileExists) { $this.CopyFile() } } else { if ($fileExists) { Write-Verbose -Message "Deleting the file $($this.Path)" Remove-Item -LiteralPath $this.Path -Force } } } [bool] Test() { $present = Test-Path -LiteralPath $this.Path if ($this.Ensure -eq [Ensure]::Present) { return $present } else { return (! $present) } } [FileResource] Get() { $present = Test-Path -Path $this.Path if ($present) { $file = Get-ChildItem -LiteralPath $this.Path $this.CreationTime = $file.CreationTime $this.Ensure = [Ensure]::Present } else { $this.CreationTime = $null $this.Ensure = [Ensure]::Absent } return $this } [void] CopyFile() { # Testing only - Remove before deployment! Wait-Debugger if (! (Test-Path -LiteralPath $this.SourcePath)) { throw "SourcePath $($this.SourcePath) is not found." } if (Test-Path -LiteralPath $this.Path -PathType Container) { throw "Path $($this.Path) is a directory path" } Write-Verbose "Copying $($this.SourcePath) to $($this.Path)" Copy-Item -LiteralPath $this.SourcePath -Destination $this.Path -Force } } ``` ## PARAMETERS ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES ## RELATED LINKS [Enable-DscDebug](/powershell/module/PSDesiredStateConfiguration/Enable-DscDebug) [about_Debuggers](/powershell/module/microsoft.powershell.core/about/about_debuggers)

#File: reference/7.6/Microsoft.PowerShell.Utility/Wait-Event.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 04/23/2020 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/wait-event?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Wait-Event --- # Wait-Event ## SYNOPSIS Waits until a particular event is raised before continuing to run. ## SYNTAX ``` Wait-Event [[-SourceIdentifier] <String>] [-Timeout <Int32>] [<CommonParameters>] ``` ## DESCRIPTION The `Wait-Event` cmdlet suspends execution of a script or function until a particular event is raised. Execution resumes when the event is detected. To cancel the wait, press <kbd>CTRL</kbd>+<kbd>C</kbd>. This feature provides an alternative to polling for an event. It also allows you to determine the response to an event in two different ways: - using the **Action** parameter of the event subscription - waiting for an event to return and then respond with an action ## EXAMPLES ### Example 1: Wait for the next event This example waits for the next event that is raised. ```powershell Wait-Event ``` ### Example 2: Wait for an event with a specified source identifier This example waits for the next event that is raised and that has a source identifier of ProcessStarted. ```powershell Wait-Event -SourceIdentifier "ProcessStarted" ``` ### Example 3: Wait for a timer elapsed event This example uses the `Wait-Event` cmdlet to wait for a timer event on a timer that is set for 2000 milliseconds. ```powershell $Timer = New-Object Timers.Timer $objectEventArgs = @{ InputObject = $Timer EventName = 'Elapsed' SourceIdentifier = 'Timer.Elapsed' } Register-ObjectEvent @objectEventArgs $Timer.Interval = 2000 $Timer.AutoReset = $false $Timer.Enabled = $true Wait-Event Timer.Elapsed ``` ```Output ComputerName : RunspaceId : bb560b14-ff43-48d4-b801-5adc31bbc6fb EventIdentifier : 1 Sender : System.Timers.Timer SourceEventArgs : System.Timers.ElapsedEventArgs SourceArgs : {System.Timers.Timer, System.Timers.ElapsedEventArgs} SourceIdentifier : Timer.Elapsed TimeGenerated : 4/23/2020 2:30:37 PM MessageData : ``` ### Example 4: Wait for an event after a specified timeout This example waits up to 90 seconds for the next event that is raised and that has a source identifier of **ProcessStarted**. If the specified time expires, the wait ends. ```powershell Wait-Event -SourceIdentifier "ProcessStarted" -Timeout 90 ``` ## PARAMETERS ### -SourceIdentifier Specifies the source identifier that this cmdlet waits for events. By default, `Wait-Event` waits for any event. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Timeout Specifies the maximum time, in seconds, that `Wait-Event` waits for the event to occur. The default, -1, waits indefinitely. The timing starts when you submit the `Wait-Event` command. If the specified time is exceeded, the wait ends and the command prompt returns, even if the event has not been raised. No error message is displayed. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: TimeoutSec Required: False Position: Named Default value: -1 Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String ## OUTPUTS ### System.Management.Automation.PSEventArgs ## NOTES Events, event subscriptions, and the event queue exist only in the current session. If you close the current session, the event queue is discarded and the event subscription is canceled. ## RELATED LINKS [Get-Event](Get-Event.md) [Get-EventSubscriber](Get-EventSubscriber.md) [New-Event](New-Event.md) [Register-EngineEvent](Register-EngineEvent.md) [Register-ObjectEvent](Register-ObjectEvent.md) [Remove-Event](Remove-Event.md) [Unregister-Event](Unregister-Event.md) [Wait-Event](Wait-Event.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Write-Debug.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/write-debug?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Write-Debug --- # Write-Debug ## SYNOPSIS Writes a debug message to the console. ## SYNTAX ``` Write-Debug [-Message] <String> [<CommonParameters>] ``` ## DESCRIPTION The `Write-Debug` cmdlet writes debug messages to the host from a script or command. By default, debug messages are not displayed in the console, but you can display them by using the **Debug** parameter or the `$DebugPreference` variable. ## EXAMPLES ### Example 1: Understand $DebugPreference This example writes a debug message. ```powershell Write-Debug "Cannot open file." ``` The default value of `$DebugPreference` is **SilentlyContinue**. Therefore, the message is not displayed in the console. ### Example 2: Change the value of $DebugPreference This example shows the effect of changing the value of the `$DebugPreference` variable. First, we display the current value of `$DebugPreference` and attempt to write a debug message. Then we change the value of `$DebugPreference` to **Continue**, which allows debug messages to be displayed. ``` PS> $DebugPreference SilentlyContinue PS> Write-Debug "Cannot open file." PS> PS> $DebugPreference = "Continue" PS> Write-Debug "Cannot open file." DEBUG: Cannot open file. ``` For more information about `$DebugPreference`, see [about_Preference_Variables](/powershell/module/Microsoft.PowerShell.Core/About/about_Preference_Variables). ### Example 3: Use the Debug parameter to override $DebugPreference The `Test-Debug` function writes the value of the `$DebugPreference` variable to the PowerShell host and to the Debug stream. In this example, we use the **Debug** parameter to override the `$DebugPreference` value. ```powershell function Test-Debug { [CmdletBinding()] param() Write-Debug ('$DebugPreference is ' + $DebugPreference) Write-Host ('$DebugPreference is ' + $DebugPreference) } ``` ``` PS> Test-Debug $DebugPreference is SilentlyContinue PS> Test-Debug -Debug DEBUG: $DebugPreference is Continue $DebugPreference is Continue PS> $DebugPreference SilentlyContinue ``` Notice that the value of `$DebugPreference` changes when you use the **Debug** parameter. This change only affects the scope of the function. The value is not affected outside the function. For more information about the **Debug** common parameter, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## PARAMETERS ### -Message Specifies the debug message to send to the console. ```yaml Type: System.String Parameter Sets: (All) Aliases: Msg Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains a debug message to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. It only writes to the debug stream. ## NOTES ## RELATED LINKS [about_Output_Streams](../Microsoft.PowerShell.Core/About/about_Output_Streams.md) [about_Redirection](../Microsoft.PowerShell.Core/About/about_Redirection.md) [Write-Error](Write-Error.md) [Write-Host](Write-Host.md) [Write-Output](Write-Output.md) [Write-Progress](Write-Progress.md) [Write-Verbose](Write-Verbose.md) [Write-Warning](Write-Warning.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Write-Error.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 03/01/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/write-error?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Write-Error --- # Write-Error ## SYNOPSIS Writes an object to the error stream. ## SYNTAX ### NoException (Default) ``` Write-Error [-Message] <string> [-Category <ErrorCategory>] [-ErrorId <string>] [-TargetObject <Object>] [-RecommendedAction <string>] [-CategoryActivity <string>] [-CategoryReason <string>] [-CategoryTargetName <string>] [-CategoryTargetType <string>] [<CommonParameters>] ``` ### WithException ``` Write-Error [-Exception] <Exception> [-Message <string>] [-Category <ErrorCategory>] [-ErrorId <string>] [-TargetObject <Object>] [-RecommendedAction <string>] [-CategoryActivity <string>] [-CategoryReason <string>] [-CategoryTargetName <string>] [-CategoryTargetType <string>] [<CommonParameters>] ``` ### ErrorRecord ``` Write-Error [-ErrorRecord] <ErrorRecord> [-RecommendedAction <string>] [-CategoryActivity <string>] [-CategoryReason <string>] [-CategoryTargetName <string>] [-CategoryTargetType <string>] [<CommonParameters>] ``` ## DESCRIPTION The `Write-Error` cmdlet declares a non-terminating error. By default, errors are sent in the error stream to the host program to be displayed, along with output. To write a non-terminating error, enter an error message string, an **ErrorRecord** object, or an **Exception** object. Use the other parameters of `Write-Error` to populate the error record. Non-terminating errors write an error to the error stream, but they don't stop command processing. If a non-terminating error is declared on one item in a collection of input items, the command continues to process the other items in the collection. To declare a terminating error, use the `throw` keyword. For more information, see [about_Throw](../Microsoft.PowerShell.Core/About/about_Throw.md). ## EXAMPLES ### Example 1: Write an error for RegistryKey object ```powershell Get-ChildItem | ForEach-Object { if ($_.GetType().ToString() -eq "Microsoft.Win32.RegistryKey") { Write-Error "Invalid object" -ErrorId B1 -TargetObject $_ } else { $_ } } ``` This command declares a non-terminating error when the `Get-ChildItem` cmdlet returns a `Microsoft.Win32.RegistryKey` object, such as the objects in the `HKLM:` or `HKCU:` drives of the PowerShell Registry provider. ### Example 2: Write an error message to the console ```powershell Write-Error "Access denied." ``` This command declares a non-terminating error and writes an "Access denied" error. The command uses the **Message** parameter to specify the message, but omits the optional **Message** parameter name. ### Example 3: Write an error to the console and specify the category ```powershell Write-Error -Message "Error: Too many input values." -Category InvalidArgument ``` This command declares a non-terminating error and specifies an error category. ### Example 4: Write an error using an Exception object ```powershell $E = [System.Exception]@{Source="Get-ParameterNames.ps1";HelpLink="https://go.microsoft.com/fwlink/?LinkID=113425"} Write-Error -Exception $E -Message "Files not found. The $Files location doesn't contain any XML files." ``` This command uses an **Exception** object to declare a non-terminating error. The first command uses a hash table to create the **System.Exception** object. It saves the exception object in the `$E` variable. You can use a hash table to create any object of a type that has a null constructor. The second command uses the `Write-Error` cmdlet to declare a non-terminating error. The value of the **Exception** parameter is the **Exception** object in the `$E` variable. ## PARAMETERS ### -Category Specifies the category of the error. The default value is **NotSpecified**. The acceptable values for this parameter are: - NotSpecified - OpenError - CloseError - DeviceError - DeadlockDetected - InvalidArgument - InvalidData - InvalidOperation - InvalidResult - InvalidType - MetadataError - NotImplemented - NotInstalled - ObjectNotFound - OperationStopped - OperationTimeout - SyntaxError - ParserError - PermissionDenied - ResourceBusy - ResourceExists - ResourceUnavailable - ReadError - WriteError - FromStdErr - SecurityError - ProtocolError - ConnectionError - AuthenticationError - LimitsExceeded - QuotaExceeded - NotEnabled For information about the error categories, see [ErrorCategory Enumeration](https://go.microsoft.com/fwlink/?LinkId=143600). ```yaml Type: System.Management.Automation.ErrorCategory Parameter Sets: NoException, WithException Aliases: Accepted values: NotSpecified, OpenError, CloseError, DeviceError, DeadlockDetected, InvalidArgument, InvalidData, InvalidOperation, InvalidResult, InvalidType, MetadataError, NotImplemented, NotInstalled, ObjectNotFound, OperationStopped, OperationTimeout, SyntaxError, ParserError, PermissionDenied, ResourceBusy, ResourceExists, ResourceUnavailable, ReadError, WriteError, FromStdErr, SecurityError, ProtocolError, ConnectionError, AuthenticationError, LimitsExceeded, QuotaExceeded, NotEnabled Required: False Position: Named Default value: NotSpecified Accept pipeline input: False Accept wildcard characters: False ``` ### -CategoryActivity Specifies the action that caused the error. ```yaml Type: System.String Parameter Sets: (All) Aliases: Activity Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CategoryReason Specifies how or why the activity caused the error. ```yaml Type: System.String Parameter Sets: (All) Aliases: Reason Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CategoryTargetName Specifies the name of the object that was being processed when the error occurred. ```yaml Type: System.String Parameter Sets: (All) Aliases: TargetName Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CategoryTargetType Specifies the type of the object that was being processed when the error occurred. ```yaml Type: System.String Parameter Sets: (All) Aliases: TargetType Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ErrorId Specifies an ID string to identify the error. The string should be unique to the error. ```yaml Type: System.String Parameter Sets: NoException, WithException Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ErrorRecord Specifies an error record object that represents the error. Use the properties of the object to describe the error. To create an error record object, use the `New-Object` cmdlet or get an error record object from the array in the `$Error` automatic variable. ```yaml Type: System.Management.Automation.ErrorRecord Parameter Sets: ErrorRecord Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Exception Specifies an exception object that represents the error. Use the properties of the object to describe the error. To create an exception object, use a hash table or use the `New-Object` cmdlet. ```yaml Type: System.Exception Parameter Sets: WithException Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Message Specifies the message text of the error. If the text includes spaces or special characters, enclose it in quotation marks. You can also pipe a message string to `Write-Error`. ```yaml Type: System.String Parameter Sets: NoException, WithException Aliases: Msg Required: True (NoException), False (WithException) Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -RecommendedAction Specifies the action that the user should take to resolve or prevent the error. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -TargetObject Specifies the object that was being processed when the error occurred. Enter the object, a variable that contains the object, or a command that gets the object. ```yaml Type: System.Object Parameter Sets: NoException, WithException Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains an error message to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. It only writes to the error message stream. ## NOTES `Write-Error` doesn't change the value of the `$?` automatic variable, therefore it doesn't signal a terminating error condition. To signal a terminating error, use the [$PSCmdlet.WriteError()](/dotnet/api/system.management.automation.cmdlet.writeerror) method. ## RELATED LINKS [about_Automatic_Variables](../microsoft.powershell.core/about/about_automatic_variables.md) [about_Output_Streams](../Microsoft.PowerShell.Core/About/about_Output_Streams.md) [about_Redirection](../Microsoft.PowerShell.Core/About/about_Redirection.md) [Write-Debug](Write-Debug.md) [Write-Host](Write-Host.md) [Write-Output](Write-Output.md) [Write-Progress](Write-Progress.md) [Write-Verbose](Write-Verbose.md) [Write-Warning](Write-Warning.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Write-Host.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 09/26/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/write-host?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Write-Host --- # Write-Host ## SYNOPSIS Writes customized output to a host. ## SYNTAX ``` Write-Host [[-Object] <Object>] [-NoNewline] [-Separator <Object>] [-ForegroundColor <ConsoleColor>] [-BackgroundColor <ConsoleColor>] [<CommonParameters>] ``` ## DESCRIPTION The `Write-Host` cmdlet's primary purpose is to produce for-(host)-display-only output, such as printing colored text like when prompting the user for input in conjunction with [Read-Host](Read-Host.md). `Write-Host` uses the [ToString()](/dotnet/api/system.object.tostring) method to write the output. By contrast, to output data to the pipeline, use [Write-Output](Write-Output.md) or implicit output. You can specify the color of text by using the `ForegroundColor` parameter, and you can specify the background color by using the `BackgroundColor` parameter. The Separator parameter lets you specify a string to use to separate displayed objects. The particular result depends on the program that is hosting PowerShell. > [!NOTE] > Starting in Windows PowerShell 5.0, `Write-Host` is a wrapper for `Write-Information` This allows > you to use `Write-Host` to emit output to the information stream. This enables the **capture** or > **suppression** of data written using `Write-Host` while preserving backwards compatibility. > > The `$InformationPreference` preference variable and `InformationAction` common parameter do not > affect `Write-Host` messages. The exception to this rule is `-InformationAction Ignore`, which > effectively suppresses `Write-Host` output. (see "Example 5") ## EXAMPLES ### Example 1: Write to the console without adding a new line ```powershell Write-Host "no newline test " -NoNewline Write-Host "second string" ``` ```output no newline test second string ``` This command displays the string 'no newline test' with the `NoNewline` parameter. A second string is written, but it ends up on the same line as the first due to the absence of a newline separating the strings. ### Example 2: Write to the console and include a separator ```powershell Write-Host (2,4,6,8,10,12) -Separator ", +2= " ``` ```output 2, +2= 4, +2= 6, +2= 8, +2= 10, +2= 12 ``` This command displays the even numbers from two through twelve. The **Separator** parameter is used to add the string `, +2= ` (comma, space, `+`, `2`, `=`, space). ### Example 3: Write with different text and background colors ```powershell Write-Host (2,4,6,8,10,12) -Separator ", -> " -ForegroundColor DarkGreen -BackgroundColor White ``` ```output 2, -> 4, -> 6, -> 8, -> 10, -> 12 ``` This command displays the even numbers from two through twelve. It uses the `ForegroundColor` parameter to output dark green text and the `BackgroundColor` parameter to display a white background. ### Example 4: Write with different text and background colors ```powershell Write-Host "Red on white text." -ForegroundColor red -BackgroundColor white ``` ```output Red on white text. ``` This command displays the string "Red on white text." The text is red, as defined by the `ForegroundColor` parameter. The background is white, as defined by the `BackgroundColor` parameter. ### Example 5: Suppress output from Write-Host ```powershell # The following two statements can be used to effectively suppress output from Write-Host Write-Host "I won't print" -InformationAction Ignore Write-Host "I won't print" 6> $null ``` These commands effectively suppress output of the `Write-Host` cmdlet. The first one uses the `InformationAction` parameter with the `Ignore` Value to suppress output to the information stream. The second example redirects the information stream of the command to the `$null` variable and thereby suppresses it. For more information, see [about_Output_Streams](../Microsoft.PowerShell.Core/About/about_Output_Streams.md). ## PARAMETERS ### -BackgroundColor Specifies the background color. There is no default. The acceptable values for this parameter are: - `Black` - `DarkBlue` - `DarkGreen` - `DarkCyan` - `DarkRed` - `DarkMagenta` - `DarkYellow` - `Gray` - `DarkGray` - `Blue` - `Green` - `Cyan` - `Red` - `Magenta` - `Yellow` - `White` ```yaml Type: System.ConsoleColor Parameter Sets: (All) Aliases: Accepted values: Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ForegroundColor Specifies the text color. There is no default. The acceptable values for this parameter are: - `Black` - `DarkBlue` - `DarkGreen` - `DarkCyan` - `DarkRed` - `DarkMagenta` - `DarkYellow` - `Gray` - `DarkGray` - `Blue` - `Green` - `Cyan` - `Red` - `Magenta` - `Yellow` - `White` ```yaml Type: System.ConsoleColor Parameter Sets: (All) Aliases: Accepted values: Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -NoNewline The string representations of the input objects are concatenated to form the output. No spaces or newlines are inserted between the output strings. No newline is added after the last output string. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Object Objects to display in the host. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Msg, Message Required: False Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Separator Specifies a separator string to insert between objects displayed by the host. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Object You can pipe objects to be written to the host to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. It sends the objects to the host. The host displays the objects this cmdlet sends to it. ## NOTES - When writing a collection to the host, elements of the collection are printed on the same line separated by a single space. This can be overridden with the **Separator** parameter. - Non-primitive data types such as objects with properties can cause unexpected results and not provide meaningful output. For example, `Write-Host @{a = 1; b = 2}` will print `System.Collections.DictionaryEntry System.Collections.DictionaryEntry` to the host. ## RELATED LINKS [Clear-Host](../Microsoft.PowerShell.Core/Clear-Host.md) [Out-Host](../Microsoft.PowerShell.Core/Out-Host.md) [Write-Debug](Write-Debug.md) [Write-Error](Write-Error.md) [Write-Output](Write-Output.md) [Write-Progress](Write-Progress.md) [Write-Verbose](Write-Verbose.md) [Write-Warning](Write-Warning.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Write-Information.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 01/06/2025 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/write-information?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Write-Information --- # Write-Information ## SYNOPSIS Specifies how PowerShell handles information stream data for a command. ## SYNTAX ``` Write-Information [-MessageData] <Object> [[-Tags] <String[]>] [<CommonParameters>] ``` ## DESCRIPTION The `Write-Information` cmdlet specifies how PowerShell handles information stream data for a command. Windows PowerShell 5.0 introduces a new, structured information stream. You can use this stream to transmit structured data between a script and its callers or the host application. `Write-Information` lets you add an informational message to the stream, and specify how PowerShell handles information stream data for a command. Information streams also work for `PowerShell.Streams`, jobs, and scheduled tasks. > [!NOTE] > The information stream does not follow the standard convention of prefixing its messages with > "[Stream Name]:". This was intended for brevity and visual cleanliness. The `$InformationPreference` preference variable value determines whether the message you provide to `Write-Information` is displayed at the expected point in a script's operation. Because the default value of this variable is **SilentlyContinue**, by default, informational messages are not shown. If you don't want to change the value of `$InformationPreference`, you can override its value by adding the **InformationAction** common parameter to your command. For more information, see [about_Preference_Variables](../Microsoft.PowerShell.Core/About/about_Preference_Variables.md) and [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). > [!NOTE] > Starting in Windows PowerShell 5.0, `Write-Host` is a wrapper for `Write-Information` This allows > you to use `Write-Host` to emit output to the information stream. This enables the capture or > suppression of data written using `Write-Host` while preserving backwards compatibility. For more > information see [Write-Host](Write-Host.md) ## EXAMPLES ### Example 1: Write information for Get- results In this example, you show an informational message, "Processes starting with 'P'", before running the `Get-Process` command to find all processes that have a **Name** value that starts with 'p'. Because the `$InformationPreference` variable is still set to its default, **SilentlyContinue**, you add the **InformationAction** parameter to override the `$InformationPreference` value, and show the message. The **InformationAction** value is **Continue**, which means that your message is shown, but the script or command continues, if it is not yet finished. ```powershell Write-Information -MessageData "Processes starting with 'P'" -InformationAction Continue Get-Process -Name p* ``` ```Output Processes starting with 'P' 18 19.76 15.16 0.00 6232 0 PFERemediation 20 8.92 25.15 0.00 24944 0 policyHost 9 1.77 7.64 0.00 1780 0 powercfg 10 26.67 32.18 0.00 7028 0 powercfg 8 26.55 31.59 0.00 13600 0 powercfg 9 1.66 7.55 0.00 22620 0 powercfg 21 6.17 4.54 202.20 12536 1 PowerMgr 42 84.26 12.71 2,488.84 20588 1 powershell 27 47.07 45.38 2.05 25988 1 powershell 27 24.45 5.31 0.00 12364 0 PresentationFontCache 92 112.04 13.36 82.30 13176 1 pwsh 106 163.73 93.21 302.25 14620 1 pwsh 227 764.01 92.16 1,757.22 25328 1 pwsh ``` ### Example 2: Write information and tag it In this example, you use `Write-Information` to let users know they'll need to run another command after they're done running the current command. The example adds the tag `"Instructions"` to the informational message. After running this command, when you search the information stream for messages tagged `"Instructions"`, the message is in the results. ```powershell $message = "To filter your results for PowerShell, pipe your results to the Where-Object cmdlet." Get-Process -Name p* Write-Information -MessageData $message -Tags "Instructions" -InformationAction Continue ``` ```Output NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 18 19.76 15.16 0.00 6232 0 PFERemediation 20 8.92 25.15 0.00 24944 0 policyHost 9 1.77 7.64 0.00 1780 0 powercfg 10 26.67 32.18 0.00 7028 0 powercfg 8 26.55 31.59 0.00 13600 0 powercfg 9 1.66 7.55 0.00 22620 0 powercfg 21 6.17 4.54 202.20 12536 1 PowerMgr 42 84.26 12.71 2,488.84 20588 1 powershell 27 47.07 45.38 2.05 25988 1 powershell 27 24.45 5.31 0.00 12364 0 PresentationFontCache 92 112.04 13.36 82.30 13176 1 pwsh 106 163.73 93.21 302.25 14620 1 pwsh 227 764.01 92.16 1,757.22 25328 1 pwsh To filter your results for PowerShell, pipe your results to the Where-Object cmdlet. ``` ### Example 3: Write information to a file In this example, you redirect the information stream in the function to `Info.txt` using the code `6>`. When you open the `Info.txt` file, you see the text "Here you go." ```powershell function Test-Info { Get-Process P* Write-Information "Here you go" } Test-Info 6> Info.txt ``` ### Example 4: Pass object to write information In this example, you can use `Write-Information` to write the top 10 highest CPU utilization processes from the `Get-Process` object output that has passes through multiple pipelines. ```powershell Get-Process | Sort-Object CPU -Descending | Select-Object Id, ProcessName, CPU -First 10 | Write-Information -InformationAction Continue ``` ```Output @{Id=12692; ProcessName=chrome; CPU=39431.296875} @{Id=21292; ProcessName=OUTLOOK; CPU=23991.875} @{Id=10548; ProcessName=CefSharp.BrowserSubprocess; CPU=20546.203125} @{Id=312848; ProcessName=Taskmgr; CPU=13173.1875} @{Id=10848; ProcessName=SnapClient; CPU=7014.265625} @{Id=9760; ProcessName=Receiver; CPU=6792.359375} @{Id=12040; ProcessName=Teams; CPU=5605.578125} @{Id=498388; ProcessName=chrome; CPU=3062.453125} @{Id=6900; ProcessName=chrome; CPU=2546.9375} @{Id=9044; ProcessName=explorer; CPU=2358.765625} ``` ### Example 5: Saving information records to a variable Using the **InformationVariable** parameter, you can save information records to a variable. This allows you to inspect the information stream messages later in the script. ```powershell Get-Process -Id $PID | Select-Object ProcessName, CPU, Path | Write-Information -Tags 'PowerShell' -InformationVariable 'InfoMsg' $InfoMsg | Select-Object * ``` ```Output MessageData : @{ProcessName=pwsh; CPU=12.36; Path=/opt/microsoft/powershell/7/pwsh} Source : Write-Information TimeGenerated : 10/19/2023 11:28:15 Tags : {PowerShell} User : sdwheeler Computer : circumflex ProcessId : 237 NativeThreadId : 261 ManagedThreadId : 10 ``` ## PARAMETERS ### -MessageData Specifies an informational message that you want to display to users as they run a script or command. For best results, enclose the informational message in quotation marks. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Msg, Message Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Tags One or more strings that you can use to sort and filter messages that you have added to the information stream with `Write-Information`. This parameter works similarly to the **Tags** parameter in `New-ModuleManifest`. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Object You can pipe objects to pass to the information stream to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. It only writes to the information message stream. ## NOTES ## RELATED LINKS [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md) [about_Output_Streams](../Microsoft.PowerShell.Core/About/about_Output_Streams.md) [about_Preference_Variables](../Microsoft.PowerShell.Core/About/about_Preference_Variables.md) [about_Redirection](../Microsoft.PowerShell.Core/About/about_Redirection.md) [Write-Debug](Write-Debug.md) [Write-Host](Write-Host.md) [Write-Information](Write-Information.md) [Write-Output](Write-Output.md) [Write-Progress](Write-Progress.md) [Write-Verbose](Write-Verbose.md) [Write-Warning](Write-Warning.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Write-Output.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 06/07/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/write-output?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Write-Output --- # Write-Output ## SYNOPSIS Writes the specified objects to the pipeline. ## SYNTAX ``` Write-Output [-InputObject] <PSObject[]> [-NoEnumerate] [<CommonParameters>] ``` ## DESCRIPTION Writes the specified objects to the pipeline. If `Write-Output` is the last command in the pipeline, the objects are displayed in the console. `Write-Output` sends objects to the primary pipeline, also known as the _success stream_. To send error objects to the error stream, use `Write-Error`. This cmdlet is typically used in scripts to display strings and other objects on the console. One of the built-in aliases for `Write-Output` is `echo` and similar to other shells that use `echo`. The default behavior is to display the output at the end of a pipeline. In PowerShell, it is generally not necessary to use the cmdlet in instances where the output is displayed by default. For example, `Get-Process | Write-Output` is equivalent to `Get-Process`. Or, `echo "Home directory: $HOME"` can be written, `"Home directory: $HOME"`. By default, `Write-Output` enumerates objects in a collection. However, `Write-Output` can also pass collections down the pipeline as a single object with the **NoEnumerate** parameter. ## EXAMPLES ### Example 1: Get objects and write them to the console In this example, the results of the `Get-Process` cmdlet are stored in the `$P` variable. The `Write-Output` cmdlet displays the process objects in `$P` to the console. ```powershell $P = Get-Process Write-Output $P ``` ### Example 2: Pass output to another cmdlet This command pipes the "test output" string to the `Get-Member` cmdlet, which displays the members of the **System.String** class, demonstrating that the string was passed along the pipeline. ```powershell Write-Output "test output" | Get-Member ``` ### Example 3: Suppress enumeration in output This command adds the **NoEnumerate** parameter to treat a collection or array as a single object through the pipeline. ```powershell Write-Output 1,2,3 | Measure-Object ``` ```Output Count : 3 ... ``` ```powershell Write-Output 1,2,3 -NoEnumerate | Measure-Object ``` ```Output Count : 1 ... ``` ## PARAMETERS ### -InputObject Specifies the objects to send down the pipeline. Enter a variable that contains the objects, or type a command or expression that gets the objects. ```yaml Type: System.Management.Automation.PSObject[] Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -NoEnumerate By default, the `Write-Output` cmdlet always enumerates its output. The **NoEnumerate** parameter suppresses the default behavior, and prevents `Write-Output` from enumerating output. The **NoEnumerate** parameter has no effect if the command is wrapped in parentheses, because the parentheses force enumeration. For example, `(Write-Output 1,2,3 -NoEnumerate)` still enumerates the array. The **NoEnumerate** parameter is only useful within a pipeline. Trying to see the effects of **NoEnumerate** in the console is problematic because PowerShell adds `Out-Default` to the end of every command line, which results in enumeration. But if you pipe `Write-Output -NoEnumerate` to another cmdlet, the downstream cmdlet receives the collection object, not the enumerated items of the collection. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject You can pipe objects to this cmdlet. ## OUTPUTS ### System.Management.Automation.PSObject This cmdlet returns the objects that are submitted as input. ## NOTES PowerShell includes the following aliases for `Write-Output`: - All platforms: - `echo` - Windows: - `write` ## RELATED LINKS [about_Output_Streams](../Microsoft.PowerShell.Core/About/about_Output_Streams.md) [about_Redirection](../Microsoft.PowerShell.Core/About/about_Redirection.md) [Tee-Object](Tee-Object.md) [Write-Debug](Write-Debug.md) [Write-Error](Write-Error.md) [Write-Host](Write-Host.md) [Write-Information](Write-Information.md) [Write-Progress](Write-Progress.md) [Write-Verbose](Write-Verbose.md) [Write-Warning](Write-Warning.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Write-Progress.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 08/26/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/write-progress?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Write-Progress --- # Write-Progress ## SYNOPSIS Displays a progress bar within a PowerShell command window. ## SYNTAX ``` Write-Progress [[-Activity] <String>] [[-Status] <String>] [[-Id] <Int32>] [-PercentComplete <Int32>] [-SecondsRemaining <Int32>] [-CurrentOperation <String>] [-ParentId <Int32>] [-Completed] [-SourceId <Int32>] [<CommonParameters>] ``` ## DESCRIPTION The `Write-Progress` cmdlet displays a progress bar in a PowerShell command window that depicts the status of a running command or script. You can select the indicators that the bar reflects and the text that appears above and below the progress bar. PowerShell 7.2 added the `$PSStyle` automatic variable that's used to control how PowerShell displays certain information using ANSI escape sequences. The `$PSStyle.Progress` member allows you to control progress view bar rendering. - `$PSStyle.Progress.Style` - An ANSI string setting the rendering style. - `$PSStyle.Progress.MaxWidth` - Sets the max width of the view. Defaults to `120`. The minimum value is 18. - `$PSStyle.Progress.View` - An enum with values, `Minimal` and `Classic`. `Classic` is the existing rendering with no changes. `Minimal` is a single line minimal rendering. `Minimal` is the default. For more information about `$PSStyle`, see [about_ANSI_Terminals.md](../Microsoft.PowerShell.Core/About/about_ANSI_Terminals.md). > [!NOTE] > If the host doesn't support Virtual Terminal, `$PSStyle.Progress.View` is automatically set to > `Classic`. ## EXAMPLES ### Example 1: Display the progress of a `for` loop ```powershell for ($i = 1; $i -le 100; $i++ ) { Write-Progress -Activity "Search in Progress" -Status "$i% Complete:" -PercentComplete $i Start-Sleep -Milliseconds 250 } ``` This command displays the progress of a `for` loop that counts from 1 to 100. The `Write-Progress` cmdlet includes a status bar heading `Activity`, a status line, and the variable `$i` (the counter in the `for` loop), which indicates the relative completeness of the task. ### Example 2: Display the progress of nested `for` loops ```powershell $PSStyle.Progress.View = 'Classic' for($I = 0; $I -lt 10; $I++ ) { $OuterLoopProgressParameters = @{ Activity = 'Updating' Status = 'Progress->' PercentComplete = $I * 10 CurrentOperation = 'OuterLoop' } Write-Progress @OuterLoopProgressParameters for($j = 1; $j -lt 101; $j++ ) { $InnerLoopProgressParameters = @{ ID = 1 Activity = 'Updating' Status = 'Inner Progress' PercentComplete = $j CurrentOperation = 'InnerLoop' } Write-Progress @InnerLoopProgressParameters Start-Sleep -Milliseconds 25 } } ``` ```Output Updating Progress -> [ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo] OuterLoop Updating Inner Progress [oooooooooooooooooo ] InnerLoop ``` This example sets the progress view to `Classic` and then displays the progress of two nested `for` loops, each represented by a progress bar. The `Write-Progress` command for the second progress bar includes the **Id** parameter that distinguishes it from the first progress bar. Without the **Id** parameter, the progress bars would be superimposed on each other instead of being displayed one below the other. > [!NOTE] > This example sets the progress view to `Classic`, which displays the **CurrentOperation** values > For each progress bar. When the progress view is set to `Minimal`, the **CurrentOperation** > values aren't displayed. ### Example 3: Display the progress while searching for a string ```powershell # Use Get-WinEvent to get the events in the System log and store them in the $Events variable. $Events = Get-WinEvent -LogName System # Pipe the events to the ForEach-Object cmdlet. $Events | ForEach-Object -Begin { # In the Begin block, use Clear-Host to clear the screen. Clear-Host # Set the $i counter variable to zero. $i = 0 # Set the $out variable to an empty string. $out = "" } -Process { # In the Process script block search the message property of each incoming object for "bios". if($_.Message -like "*bios*") { # Append the matching message to the out variable. $out=$out + $_.Message } # Increment the $i counter variable which is used to create the progress bar. $i = $i+1 # Determine the completion percentage $Completed = ($i/$Events.Count) * 100 # Use Write-Progress to output a progress bar. # The Activity and Status parameters create the first and second lines of the progress bar # heading, respectively. Write-Progress -Activity "Searching Events" -Status "Progress:" -PercentComplete $Completed } -End { # Display the matching messages using the out variable. $out } ``` This command displays the progress of a command to find the string "bios" in the System event log. The **PercentComplete** parameter value is calculated by dividing the number of events that have been processed `$i` by the total number of events retrieved `$Events.Count` and then multiplying that result by 100. ### Example 4: Display progress for each level of a nested process ```powershell $PSStyle.Progress.View = 'Classic' foreach ( $i in 1..10 ) { Write-Progress -Id 0 "Step $i" foreach ( $j in 1..10 ) { Write-Progress -Id 1 -ParentId 0 "Step $i - Substep $j" foreach ( $k in 1..10 ) { Write-Progress -Id 2 -ParentId 1 "Step $i - Substep $j - iteration $k" Start-Sleep -Milliseconds 150 } } } ``` ```Output Step 1 Processing Step 1 - Substep 2 Processing Step 1 - Substep 2 - Iteration 3 Processing ``` In this example you can use the **ParentId** parameter to have indented output to show parent-child relationships in the progress of each step. ## PARAMETERS ### -Activity Specifies the first line of text in the heading above the status bar. This text describes the activity whose progress is being reported. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Completed Indicates whether the progress bar is visible. If this parameter is omitted, `Write-Progress` displays progress information. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CurrentOperation Specifies the line of text below the progress bar in the `Classic` progress view. This text describes the operation that's currently taking place. This parameter has no effect when the progress view is set to `Minimal`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Id Specifies an ID that distinguishes each progress bar from the others. Use this parameter when you are creating more than one progress bar in a single command. If the progress bars don't have different IDs, they're superimposed instead of being displayed in a series. Negative values aren't allowed. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ParentId Specifies the parent activity of the current activity. Use the value `-1` if the current activity has no parent activity. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PercentComplete Specifies the percentage of the activity that's completed. Use the value `-1` if the percentage complete is unknown or not applicable. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SecondsRemaining Specifies the projected number of seconds remaining until the activity is completed. Use the value `-1` if the number of seconds remaining is unknown or not applicable. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SourceId Specifies the source of the record. You can use this in place of **Id** but can't be used with other parameters like **ParentId**. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Status Specifies the second line of text in the heading above the status bar. This text describes current state of the activity. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES If the progress bar doesn't appear, check the value of the `$ProgressPreference` variable. If the value is set to `SilentlyContinue`, the progress bar isn't displayed. For more information about PowerShell preferences, see [about_Preference_Variables](../Microsoft.PowerShell.Core/About/about_Preference_Variables.md). The parameters of the cmdlet correspond to the properties of the **System.Management.Automation.ProgressRecord** class. For more information, see [ProgressRecord Class](/dotnet/api/system.management.automation.progressrecord). ## RELATED LINKS [Write-Debug](Write-Debug.md) [Write-Error](Write-Error.md) [Write-Host](Write-Host.md) [Write-Output](Write-Output.md) [Write-Progress](Write-Progress.md) [Write-Verbose](Write-Verbose.md) [Write-Warning](Write-Warning.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Write-Verbose.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/write-verbose?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Write-Verbose --- # Write-Verbose ## SYNOPSIS Writes text to the verbose message stream. ## SYNTAX ``` Write-Verbose [-Message] <String> [<CommonParameters>] ``` ## DESCRIPTION The `Write-Verbose` cmdlet writes text to the verbose message stream in PowerShell. Typically, the verbose message stream is used to deliver more in depth information about command processing. By default, the verbose message stream is not displayed, but you can display it by changing the value of the `$VerbosePreference` variable or using the **Verbose** common parameter in any command. ## EXAMPLES ### Example 1: Write a status message ```powershell Write-Verbose -Message "Searching the Application Event Log." Write-Verbose -Message "Searching the Application Event Log." -Verbose ``` These commands use the `Write-Verbose` cmdlet to display a status message. By default, the message is not displayed. The second command uses the **Verbose** common parameter, which displays any verbose messages, regardless of the value of the `$VerbosePreference` variable. ### Example 2: Set $VerbosePreference and write a status message ```powershell $VerbosePreference = "Continue" Write-Verbose "Copying file $filename" ``` These commands use the `Write-Verbose` cmdlet to display a status message. By default, the message is not displayed. The first command assigns a value of Continue to the `$VerbosePreference` preference variable. The default value, `SilentlyContinue`, suppresses verbose messages. The second command writes a verbose message. ## PARAMETERS ### -Message Specifies the message to display. This parameter is required. You can also pipe a message string to `Write-Verbose`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Msg Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### System.String You can pipe a string that contains the message to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. It only writes to the verbose message stream. ## NOTES - Verbose messages are returned only when the command uses the **Verbose** common parameter. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). - In Windows PowerShell background jobs and remote commands, the `$VerbosePreference` variable in the job session and remote session determine whether the verbose message is displayed by default. For more information about the `$VerbosePreference` variable, see [about_Preference_Variables](../Microsoft.PowerShell.Core/About/about_Preference_Variables.md). ## RELATED LINKS [about_Output_Streams](../Microsoft.PowerShell.Core/About/about_Output_Streams.md) [about_Redirection](../Microsoft.PowerShell.Core/About/about_Redirection.md) [Write-Debug](Write-Debug.md) [Write-Error](Write-Error.md) [Write-Host](Write-Host.md) [Write-Information](Write-Information.md) [Write-Output](Write-Output.md) [Write-Progress](Write-Progress.md) [Write-Warning](Write-Warning.md)

#File: reference/7.6/Microsoft.PowerShell.Utility/Write-Warning.md

--- external help file: Microsoft.PowerShell.Commands.Utility.dll-Help.xml Locale: en-US Module Name: Microsoft.PowerShell.Utility ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.powershell.utility/write-warning?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Write-Warning --- # Write-Warning ## SYNOPSIS Writes a warning message. ## SYNTAX ``` Write-Warning [-Message] <String> [<CommonParameters>] ``` ## DESCRIPTION The `Write-Warning` cmdlet writes a warning message to the PowerShell host. The response to the warning depends on the value of the user's `$WarningPreference` variable and the use of the **WarningAction** common parameter. ## EXAMPLES ### Example 1: Write a warning message This command displays the message "WARNING: This is only a test warning." ```powershell Write-Warning "This is only a test warning." ``` ### Example 2: Pass a string to Write-Warning This command shows that you can use a pipeline operator (`|`) to send a string to `Write-Warning`. You can save the string in a variable, as shown in this command, or pipe the string directly to `Write-Warning`. ```powershell $w = "This is only a test warning." $w | Write-Warning ``` ### Example 3: Set the $WarningPreference variable and write a warning This example shows the effect of the value of the `$WarningPreference` variable on a `Write-Warning` command. ```powershell PS> $WarningPreference Continue PS> Write-Warning "This is only a test warning." This is only a test warning. PS> $WarningPreference = "SilentlyContinue" PS> Write-Warning "This is only a test warning." PS> $WarningPreference = "Stop" PS> Write-Warning "This is only a test warning." WARNING: This is only a test warning. Write-Warning: The running command stopped because the preference variable "WarningPreference" or common parameter is set to Stop: This is only a test warning. ``` The first command displays the default value of the `$WarningPreference` variable, which is `Continue`. As a result, when you write a warning, the warning message is displayed and execution continues. When you change the value of the `$WarningPreference` variable, the effect of the `Write-Warning` command changes again. A value of `SilentlyContinue` suppresses the warning. A value of `Stop` displays the warning and then stops execution of the command. For more information about the `$WarningPreference` variable, see [about_Preference_Variables](../Microsoft.Powershell.Core/About/about_Preference_Variables.md). ### Example 4: Set the WarningAction parameter and write a warning This example shows the effect of the **WarningAction** common parameter on a `Write-Warning` command. You can use the **WarningAction** common parameter with any cmdlet to determine how PowerShell responds to warnings resulting from that command. The **WarningAction** common parameter overrides the value of the `$WarningPreference` only for that particular command. ```powershell PS> Write-Warning "This is only a test warning." -WarningAction Inquire WARNING: This is only a test warning. Confirm Continue with this operation? [Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"): ``` This command uses the `Write-Warning` cmdlet to display a warning. The **WarningAction** common parameter with a value of Inquire directs the system to prompt the user when the command displays a warning. For more information about the **WarningAction** common parameter, see [about_CommonParameters](../Microsoft.Powershell.Core/About/about_CommonParameters.md). ## PARAMETERS ### -Message Specifies the warning message. ```yaml Type: System.String Parameter Sets: (All) Aliases: Msg Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string that contains the warning to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. It writes only to the warning stream. ## NOTES The default value for the `$WarningPreference` variable is `Continue`, which displays the warning and then continues executing the command. To determine valid values for a preference variable such as `$WarningPreference`, set it to a string of random characters, such as "abc". The resulting error message lists the valid values. ## RELATED LINKS [about_Output_Streams](../Microsoft.PowerShell.Core/About/about_Output_Streams.md) [about_Redirection](../Microsoft.PowerShell.Core/About/about_Redirection.md) [Write-Debug](Write-Debug.md) [Write-Error](Write-Error.md) [Write-Host](Write-Host.md) [Write-Information](Write-Information.md) [Write-Output](Write-Output.md) [Write-Progress](Write-Progress.md) [Write-Verbose](Write-Verbose.md)

#File: reference/7.6/Microsoft.WSMan.Management/Connect-WSMan.md

--- external help file: Microsoft.WSMan.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.WSMan.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.wsman.management/connect-wsman?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Connect-WSMan --- # Connect-WSMan ## SYNOPSIS Connects to the WinRM service on a remote computer. ## SYNTAX ### ComputerName (Default) ``` Connect-WSMan [-ApplicationName <String>] [[-ComputerName] <String>] [-OptionSet <Hashtable>] [-Port <Int32>] [-SessionOption <SessionOption>] [-UseSSL] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ### URI ``` Connect-WSMan [-ConnectionURI <Uri>] [-OptionSet <Hashtable>] [-Port <Int32>] [-SessionOption <SessionOption>] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Connect-WSMan` cmdlet connects to the WinRM service on a remote computer, and it establishes a persistent connection to the remote computer. You can use this cmdlet in the context of the WSMan provider to connect to the WinRM service on a remote computer. However, you can also use this cmdlet to connect to the WinRM service on a remote computer before you change to the WSMan provider. The remote computer appears in the root directory of the WSMan provider. Explicit credentials are required when the client and server computers are in different domains or workgroups. For information about how to disconnect from the WinRM service on a remote computer, see the `Disconnect-WSMan` cmdlet. ## EXAMPLES ### Example 1: Connect to a remote computer ```powershell PS C:\> Connect-WSMan -ComputerName "server01" PS C:\> cd WSMan: PS WSMan:\> PS WSMan:\> dir ``` ```Output WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan ComputerName Type ------------ ---- localhost Container server01 Container ``` This command creates a connection to the remote server01 computer. The `Connect-WSMan` cmdlet is generally used in the context of the WSMan provider to connect to a remote computer, in this case the server01 computer. However, you can use the cmdlet to establish connections to remote computers before you change to the WSMan provider. Those connections appear in the **ComputerName** list. ### Example 2: Connect to a remote computer by using Administrator credentials ```powershell PS C:\> $cred = Get-Credential Administrator PS C:\> Connect-WSMan -ComputerName "server01" -Credential $cred PS C:\> cd WSMan: PS WSMan:\> PS WSMan:\> dir ``` ```Output WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan ComputerName Type ------------ ---- localhost Container server01 Container ``` This command creates a connection to the remote system server01 using the Administrator account credentials. The first command uses the Get-Credential cmdlet to get the Administrator credentials and then stores them in the `$cred` variable. `Get-Credential` prompts you for a password of username and password through a dialog box or at the command line, depending on system registry settings. The second command uses the **Credential** parameter to pass the credentials stored in $cred to `Connect-WSMan`. `Connect-WSMan` then connects to the remote system server01 by using the Administrator credentials. ### Example 3: Connect to a remote computer over a specified port ```powershell PS C:\> Connect-WSMan -ComputerName "server01" -Port 80 PS C:\> cd WSMan: PS WSMan:\> PS WSMan:\> dir ``` ```Output WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan ComputerName Type ------------ ---- localhost Container server01 Container ``` This command creates a connection to the remote server01 computer over port 80. ### Example 4: Connect to a remote computer by using connection options ```powershell PS C:\> $a = New-WSManSessionOption -OperationTimeout 30000 PS C:\> Connect-WSMan -ComputerName "server01" -SessionOption $a PS C:\> cd WSMan: PS WSMan:\> dir ``` ```Output WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan ComputerName Type ------------ ---- localhost Container server01 Container ``` This example creates a connection to the remote server01 computer by using the connection options that are defined in the `New-WSManSessionOption` command. The first command uses `New-WSManSessionOption` to store a set of connection setting options in the `$a` variable. In this case, the session options set a connection time out of 30 seconds (30,000 milliseconds). The second command uses the **SessionOption** parameter to pass the credentials that are stored in the `$a` variable to `Connect-WSMan`. Then, `Connect-WSMan` connects to the remote server01 computer by using the specified session options. ## PARAMETERS ### -ApplicationName Specifies the application name in the connection. The default value of the **ApplicationName** parameter is WSMAN. The complete identifier for the remote endpoint is in the following format: `<Transport>://<Server>:<Port>/<ApplicationName>` For example: `http://server01:8080/WSMAN` Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of WSMAN is appropriate for most uses. This parameter is designed to be used if many computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hosts Web Services for Management (WS-Management) for efficiency. ```yaml Type: System.String Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Authentication Specifies the authentication mechanism to be used at the server. The acceptable values for this parameter are: - `Basic`- Basic is a scheme in which the user name and password are sent in clear text to the server or proxy. - `Default` - Use the authentication method implemented by the WS-Management protocol. This is the default. - `Digest` - Digest is a challenge-response scheme that uses a server-specified data string for the challenge. - `Kerberos` - The client computer and the server mutually authenticate by using Kerberos certificates. - `Negotiate` - Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows for negotiation to determine whether the Kerberos protocol or NTLM is used. - `CredSSP` - Use Credential Security Support Provider (CredSSP) authentication, which lets the user delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers. > [!CAUTION] > CredSSP delegates the user credentials from the local computer to a remote computer. This practice > increases the security risk of the remote operation. If the remote computer is compromised, when > credentials are passed to it, the credentials can be used to control the network session. ```yaml Type: Microsoft.WSMan.Management.AuthenticationMechanism Parameter Sets: (All) Aliases: auth, am Accepted values: None, Default, Digest, Negotiate, Basic, Kerberos, ClientCertificate, Credssp Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to perform this action. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they do not work with domain accounts. To get a certificate thumbprint, use the `Get-Item` or `Get-ChildItem` command in the Windows PowerShell Cert: drive. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies the computer against which to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (`.`) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet. ```yaml Type: System.String Parameter Sets: ComputerName Aliases: cn Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ConnectionURI Specifies the connection endpoint. The format of this string is as follows: `<Transport>://<Server>:<Port>/<ApplicationName>` The following string is a correctly formatted value for this parameter: `http://Server01:8080/WSMAN` The URI must be fully qualified. ```yaml Type: System.Uri Parameter Sets: URI Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as `User01`, `Domain01\User01`, or `User@Domain.com`. Or, enter a **PSCredential** object, such as one returned by the `Get-Credential` cmdlet. When you type a user name, this cmdlet prompts you for a password. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: cred, c Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -OptionSet Specifies a set of switches to a service to modify or refine the nature of the request. These resemble switches used in command-line shells because they are service specific. Any number of options can be specified. The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters: `-OptionSet @{a=1;b=2;c=3}` ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: os Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Port Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the **ComputerName** parameter must match the server's certificate common name (CN). However, if the **SkipCNCheck** parameter is specified as part of the **SessionOption** parameter, the certificate common name of the server does not have to match the host name of the server. The **SkipCNCheck** parameter should be used only for trusted computers. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SessionOption Specifies extended options for the WS-Management session. Enter a **SessionOption** object that you create by using the `New-WSManSessionOption` cmdlet. For more information about the options that are available, type `Get-Help New-WSManSessionOption`. ```yaml Type: Microsoft.WSMan.Management.SessionOption Parameter Sets: (All) Aliases: so Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL Specifies that the Secure Sockets Layer (SSL) protocol is used to establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all the Windows PowerShell content that is transmitted over the network. The **UseSSL** parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection, and you specify this parameter, the command fails. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES You can run management commands or query management data on a remote computer without creating a WS-Management session. You can do this by using the **ComputerName** parameters of `Invoke-WSManAction` and `Get-WSManInstance`. When you use the **ComputerName** parameter, Windows PowerShell creates a temporary connection that is used for the single command. After the command runs, the connection is closed. ## RELATED LINKS [Disable-WSManCredSSP](Disable-WSManCredSSP.md) [Disconnect-WSMan](Disconnect-WSMan.md) [Enable-WSManCredSSP](Enable-WSManCredSSP.md) [Get-WSManCredSSP](Get-WSManCredSSP.md) [Get-WSManInstance](Get-WSManInstance.md) [Invoke-WSManAction](Invoke-WSManAction.md) [New-WSManInstance](New-WSManInstance.md) [New-WSManSessionOption](New-WSManSessionOption.md) [Remove-WSManInstance](Remove-WSManInstance.md) [Set-WSManInstance](Set-WSManInstance.md) [Set-WSManQuickConfig](Set-WSManQuickConfig.md) [Test-WSMan](Test-WSMan.md)

#File: reference/7.6/Microsoft.WSMan.Management/Disable-WSManCredSSP.md

--- external help file: Microsoft.WSMan.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.WSMan.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.wsman.management/disable-wsmancredssp?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Disable-WSManCredSSP --- # Disable-WSManCredSSP ## SYNOPSIS Disables CredSSP authentication on a computer. ## SYNTAX ``` Disable-WSManCredSSP [-Role] <String> [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Disable-WSManCredSSP` cmdlet disables Credential Security Support Provider (CredSSP) authentication on a client or on a server computer. When CredSSP authentication is used, the user credentials are passed to a remote computer to be authenticated. Use this cmdlet to disable CredSSP on the client by specifying Client in the **Role** parameter. This cmdlet performs the following actions: - Disables CredSSP on the client. This cmdlet sets the WS-Management setting `<localhost|computername>\Client\Auth\CredSSP` to false. - Removes any `WSMan/*` setting from the Windows CredSSP policy **AllowFreshCredentials** on the client. Use this cmdlet to disable CredSSP on the server by specifying Server in **Role**. This cmdlet performs the following action: - Disables CredSSP on the server. This cmdlet sets the WS-Management setting `<localhost|computername>\Client\Auth\CredSSP` to false. > [!CAUTION] > CredSSP authentication delegates the user credentials from the local computer to a remote > computer. This practice increases the security risk of the remote operation. If the remote > computer is compromised, when credentials are passed to it, the credentials can be used to control > the network session. ## EXAMPLES ### Example 1: Disable CredSSP on a client ```powershell Disable-WSManCredSSP -Role Client ``` This command disables CredSSP on the client, which prevents delegation to servers. ### Example 2: Disable CredSSP on a server ```powershell Disable-WSManCredSSP -Role Server ``` This command disables CredSSP on the server, which prevents delegation from clients. ## PARAMETERS ### -Role Specifies whether to disable CredSSP as a client or as a server. The acceptable values for this parameter are: Client and Server. If you specify Client, this cmdlet performs the following actions: - Disables CredSSP on the client. This cmdlet sets WS-Management setting `<localhost|computername>\Client\Auth\CredSSP` to false. - Removes any `WSMan/*` setting from the Windows CredSSP policy **AllowFreshCredentials** on the client. If you specify Server, this cmdlet performs the following action: - Disables CredSSP on the server. This cmdlet sets the WS-Management setting `<localhost|computername>\Client\Auth\CredSSP` to false. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: Client, Server Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES - To enable CredSSP authentication, use the Enable-WSManCredSSP cmdlet. ## RELATED LINKS [Connect-WSMan](Connect-WSMan.md) [Disconnect-WSMan](Disconnect-WSMan.md) [Enable-WSManCredSSP](Enable-WSManCredSSP.md) [Get-WSManCredSSP](Get-WSManCredSSP.md) [Get-WSManInstance](Get-WSManInstance.md) [Invoke-WSManAction](Invoke-WSManAction.md) [New-WSManInstance](New-WSManInstance.md) [New-WSManSessionOption](New-WSManSessionOption.md) [Remove-WSManInstance](Remove-WSManInstance.md) [Set-WSManInstance](Set-WSManInstance.md) [Set-WSManQuickConfig](Set-WSManQuickConfig.md) [Test-WSMan](Test-WSMan.md)

#File: reference/7.6/Microsoft.WSMan.Management/Disconnect-WSMan.md

--- external help file: Microsoft.WSMan.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.WSMan.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.wsman.management/disconnect-wsman?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Disconnect-WSMan --- # Disconnect-WSMan ## SYNOPSIS Disconnects the client from the WinRM service on a remote computer. ## SYNTAX ``` Disconnect-WSMan [[-ComputerName] <String>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Disconnect-WSMan` cmdlet disconnects the client from the WinRM service on a remote computer. If you saved the WS-Management session in a variable, the session object remains in the variable, but the state of the WS-Management session is **Closed**. You can use this cmdlet within the context of the WSMan provider to disconnect the client from the WinRM service on a remote computer. However, you can also use this cmdlet to disconnect from the WinRM service on remote computers before you change to the WSMan provider. For more information about how to connect to the WinRM service on a remote computer, see `Connect-WSMan`. ## EXAMPLES ### Example 1: Delete a connection to a remote computer ```powershell PS C:\> Disconnect-WSMan -Computer server01 PS C:\> cd WSMan: PS WSMan:\> dir ``` ```Output WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan ComputerName Type ------------ ---- localhost Container ``` This command deletes the connection to the remote computer named server01. This cmdlet is generally used within the context of the WSMan provider to disconnect from a remote computer, in this case the server01 computer. However, you can also use `Disconnect-WSMan` to remove connections to remote computers before you change to the WSMan provider. Those connections do not appear in the ComputerName list. ## PARAMETERS ### -ComputerName Specifies the computer against which to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (`.`) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet. You cannot disconnect from the local host. That is, you cannot disconnect the default connection to the local computer. However, if you create a separate connection to the local computer, for example, by using the computer name. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES ## RELATED LINKS [Connect-WSMan](Connect-WSMan.md) [Disable-WSManCredSSP](Disable-WSManCredSSP.md) [Enable-WSManCredSSP](Enable-WSManCredSSP.md) [Get-WSManCredSSP](Get-WSManCredSSP.md) [Get-WSManInstance](Get-WSManInstance.md) [Invoke-WSManAction](Invoke-WSManAction.md) [New-WSManInstance](New-WSManInstance.md) [New-WSManSessionOption](New-WSManSessionOption.md) [Remove-WSManInstance](Remove-WSManInstance.md) [Set-WSManInstance](Set-WSManInstance.md) [Set-WSManQuickConfig](Set-WSManQuickConfig.md) [Test-WSMan](Test-WSMan.md)

#File: reference/7.6/Microsoft.WSMan.Management/Enable-WSManCredSSP.md

--- external help file: Microsoft.WSMan.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.WSMan.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.wsman.management/enable-wsmancredssp?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Enable-WSManCredSSP --- # Enable-WSManCredSSP ## SYNOPSIS Enables Credential Security Support Provider (CredSSP) authentication on a computer. ## SYNTAX ### All ``` Enable-WSManCredSSP [[-DelegateComputer] <String[]>] [-Force] [-Role] <String> [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Enable-WSManCredSSP` cmdlet enables CredSSP authentication on a client or on a server computer. When CredSSP authentication is used, the user credentials are passed to a remote computer to be authenticated. This type of authentication is designed for commands that create a remote session from another remote session. For example, if you want to run a background job on a remote computer, use this kind of authentication. `Enable-WSManCredSSP` can enable CredSSP on a **Client** or a **Server**. To enable CredSSP on a client, specify **Client** in the **Role** parameter. Clients delegate explicit credentials to a server when server authentication is achieved. To enable CredSSP on a server, specify **Server** in the **Role** parameter. A server acts as a delegate for clients. For more details, see **Role** in the Parameters section. > [!CAUTION] > CredSSP authentication delegates the user credentials from the local computer to a remote > computer. This practice increases the security risk of the remote operation. If the remote > computer is compromised, when credentials are passed to it, the credentials can be used to control > the network session. ## EXAMPLES ### Example 1: Delegate client credentials This example allows the client credentials to be delegated to a computer by using the fully qualified domain name. ```powershell Enable-WSManCredSSP -Role "Client" -DelegateComputer "Server02.fabrikam.com" ``` ```Output cfg : http://schemas.microsoft.com/wbem/wsman/1/config/client/auth lang : en-US Basic : true Digest : true Kerberos : true Negotiate : true Certificate : true CredSSP : true ``` ### Example 2: Delegate client credentials to all computers in a domain This example allows the client credentials to be delegated to all the computers in the **fabrikam.com** domain. The asterisk (`*`) wildcard specifies all computers. > [!NOTE] > Using wildcards with the **DelegateComputer** parameter can enable CredSSP on more computers than > necessary. ```powershell Enable-WSManCredSSP -Role "Client" -DelegateComputer "*.fabrikam.com" ``` ```Output cfg : http://schemas.microsoft.com/wbem/wsman/1/config/client/auth lang : en-US Basic : true Digest : true Kerberos : true Negotiate : true Certificate : true CredSSP : true ``` ### Example 3: Delegate client credentials to multiple computers This example allows the client credentials to be delegated to multiple computers. ```powershell $servers = "server02.fabrikam.com", "server03.fabrikam.com", "server04.fabrikam.com" Enable-WSManCredSSP -Role "Client" -DelegateComputer $servers ``` ```Output cfg : http://schemas.microsoft.com/wbem/wsman/1/config/client/auth lang : en-US Basic : true Digest : true Kerberos : true Negotiate : true Certificate : true CredSSP : true ``` The `$servers` variable contains a list of server names. `Enable-WSManCredSSP` uses the **Role** parameter to specify the **Client** role. The **DelegateComputer** gets the computer names from the `$servers` variable. ### Example 4: Allow a computer to act as a delegate This example allows a computer to act as a delegate for another. The `Enable-WSManCredSSP` cmdlet, shown in the earlier examples, only enables CredSSP authentication on the client, and specifies the remote computers that can act on its behalf. In order for the remote computer to act as a delegate for the client, the CredSSP item in the **Service** node of WSMan must be set to true. This example sets the CredSSP item in the **Service** node of WSMan to true. ```powershell Enable-WSManCredSSP -Role "Server" ``` ### Example 5: Allow a computer to act as a delegate by using Set-Item This example allows a computer to act as a delegate for another computer. The `Enable-WSManCredSSP` commands, shown in the earlier examples, enable CredSSP authentication only on the client computer, and they specify the remote computers that can act on behalf of the client computer. For the remote computer to act as a delegate for the client computer, the CredSSP item in the Service directory of the WSMan provider must be set to true. ```powershell Connect-WSMan -ComputerName "server02" Set-Item -Path "WSMan:\server02\service\auth\credSSP" -Value $true ``` `Connect-WSMan` creates a connection to the remote computer, server02. `Set-Item` uses the **Path** parameter to specify the **WSMan** provider's location. The **Value** parameter sets the **Service** setting to true. ## PARAMETERS ### -DelegateComputer Specifies servers to which client credentials are delegated. The best practice is to use fully qualified domain names. Wildcards are accepted, but can enable CredSSP on more computers than necessary. If the **Role** parameter is **Client**, you must specify this parameter. If **Role** is **Server**, don't specify this parameter. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: True ``` ### -Force Forces the command to run without asking for user confirmation. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Role Specifies whether to enable CredSSP as a client or as a server. The acceptable values for this parameter are: **Client** and **Server**. If you specify **Client**, the following actions are performed. These settings allow the client to delegate explicit credentials to a server when server authentication is achieved. - Enables CredSSP on the client. - Sets the WS-Management setting `\<localhost|computername\>\Client\Auth\CredSSP` to true. - Sets the Windows CredSSP policy **AllowFreshCredentials** to **WSMan/Delegate** on the client. If you specify **Server**, the following actions are performed. This policy setting allows the server to act as a delegate for clients. - Enables CredSSP on the server. - Sets the WS-Management setting `\<localhost|computername\>\Service\Auth\CredSSP` to true. ```yaml Type: System.String Parameter Sets: (All) Aliases: Accepted values: Client, Server Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Xml.XmlElement If CredSSP authentication is successfully enabled, this cmdlet returns an **XMLElement** object. ## NOTES To disable CredSSP authentication, use the `Disable-WSManCredSSP` cmdlet. ## RELATED LINKS [Connect-WSMan](Connect-WSMan.md) [Disable-WSManCredSSP](Disable-WSManCredSSP.md) [Disconnect-WSMan](Disconnect-WSMan.md) [Get-WSManCredSSP](Get-WSManCredSSP.md) [Get-WSManInstance](Get-WSManInstance.md) [Invoke-WSManAction](Invoke-WSManAction.md) [New-WSManInstance](New-WSManInstance.md) [New-WSManSessionOption](New-WSManSessionOption.md) [Remove-WSManInstance](Remove-WSManInstance.md) [Set-WSManInstance](Set-WSManInstance.md) [Set-WSManQuickConfig](Set-WSManQuickConfig.md) [Test-WSMan](Test-WSMan.md)

#File: reference/7.6/Microsoft.WSMan.Management/Get-WSManCredSSP.md

--- external help file: Microsoft.WSMan.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.WSMan.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.wsman.management/get-wsmancredssp?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-WSManCredSSP --- # Get-WSManCredSSP ## SYNOPSIS Gets the Credential Security Support Provider-related configuration for the client. ## SYNTAX ``` Get-WSManCredSSP [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Get-WSManCredSSP` cmdlet gets the Credential Security Support Provider-related configuration of the client and the server. The output indicates whether Credential Security Support Provider (CredSSP) authentication is enabled or disabled. This cmdlet also displays configuration information for the **AllowFreshCredentials** policy of CredSSP. When you use CredSSP authentication, the user credentials are passed to a remote computer to be authenticated. This type of authentication is designed for commands that create a remote session from another remote session. For example, if you want to run a background job on a remote computer, use this kind of authentication. The cmdlet performs the following actions: - Gets the WS-Management CredSSP setting on the client (`<localhost|computername>\Client\Auth\CredSSP`). - Gets the Windows CredSSP policy setting **AllowFreshCredentials**. - Gets the WS-Management CredSSP setting on the server (`<localhost|computername>\Service\Auth\CredSSP`). > [!CAUTION] > CredSSP authentication delegates the user credentials from the local computer to a remote > computer. This practice increases the security risk of the remote operation. If the remote > computer is compromised, when credentials are passed to it, the credentials can be used to control > the network session. ## EXAMPLES ### Example 1: Display CredSSP configuration ```powershell Get-WSManCredSSP ``` This command displays CredSSP configuration information for both the client and server. The output identifies that this computer is or is not configured for CredSSP. If the computer is configured for CredSSP, this is the output: `The machine is configured to allow delegating fresh credentials to the following target(s): wsman/server02.accounting.fabrikam.com` If the computer is not configured for CredSSP, this is the output: `The machine is not configured to allow delegating fresh credentials.` ## PARAMETERS ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns a message string describing the configuration state for CredSSP. ## NOTES To disable CredSSP authentication, use the `Disable-WSManCredSSP` cmdlet. To enable CredSSP authentication, use the `Enable-WSManCredSSP` cmdlet. ## RELATED LINKS [Connect-WSMan](Connect-WSMan.md) [Disable-WSManCredSSP](Disable-WSManCredSSP.md) [Disconnect-WSMan](Disconnect-WSMan.md) [Enable-WSManCredSSP](Enable-WSManCredSSP.md) [Get-WSManInstance](Get-WSManInstance.md) [Invoke-WSManAction](Invoke-WSManAction.md) [New-WSManInstance](New-WSManInstance.md) [New-WSManSessionOption](New-WSManSessionOption.md) [Remove-WSManInstance](Remove-WSManInstance.md) [Set-WSManInstance](Set-WSManInstance.md) [Set-WSManQuickConfig](Set-WSManQuickConfig.md) [Test-WSMan](Test-WSMan.md)

#File: reference/7.6/Microsoft.WSMan.Management/Get-WSManInstance.md

--- external help file: Microsoft.WSMan.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.WSMan.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.wsman.management/get-wsmaninstance?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-WSManInstance --- # Get-WSManInstance ## SYNOPSIS Displays management information for a resource instance specified by a Resource URI. ## SYNTAX ### GetInstance (Default) ``` Get-WSManInstance [-ApplicationName <String>] [-ComputerName <String>] [-ConnectionURI <Uri>] [-Dialect <Uri>] [-Fragment <String>] [-OptionSet <Hashtable>] [-Port <Int32>] [-ResourceURI] <Uri> [-SelectorSet <Hashtable>] [-SessionOption <SessionOption>] [-UseSSL] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ### Enumerate ``` Get-WSManInstance [-ApplicationName <String>] [-BasePropertiesOnly] [-ComputerName <String>] [-ConnectionURI <Uri>] [-Dialect <Uri>] [-Enumerate] [-Filter <String>] [-OptionSet <Hashtable>] [-Port <Int32>] [-Associations] [-ResourceURI] <Uri> [-ReturnType <String>] [-SessionOption <SessionOption>] [-Shallow] [-UseSSL] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ## DESCRIPTION The `Get-WSManInstance` cmdlet retrieves an instance of a management resource that is specified by a resource Uniform Resource Identifier (URI). The information that is retrieved can be a complex XML information set, which is an object, or a simple value. This cmdlet is the equivalent to the standard Web Services for Management (WS-Management) **Get** command. This cmdlet uses the WS-Management connection/transport layer to retrieve information. ## EXAMPLES ### Example 1: Get all information from WMI ```powershell Get-WSManInstance -ResourceURI wmicimv2/Win32_Service -SelectorSet @{name="winrm"} -ComputerName "Server01" ``` This command returns all of the information that Windows Management Instrumentation (WMI) exposes about the **WinRM** service on the remote server01 computer. ### Example 2: Get the status of the Spooler service ```powershell Get-WSManInstance -ResourceURI wmicimv2/Win32_Service -SelectorSet @{name="spooler"} -Fragment Status -ComputerName "Server01" ``` This command returns only the status of the **Spooler** service on the remote server01 computer. ### Example 3: Get endpoint references for all services ```powershell Get-WSManInstance -Enumerate -ResourceURI wmicimv2/Win32_Service -ReturnType EPR ``` This command returns endpoint references that correspond to all the services on the local computer. ### Example 4: Get services that meet specified criteria ```powershell Get-WSManInstance -Enumerate -ResourceURI wmicimv2/* -Filter "select * from Win32_Service where StartMode = 'Auto' and State = 'Stopped'" -ComputerName "Server01" ``` This command lists all of the services that meet the following criteria on the remote Server01 computer: - The startup type of the service is Automatic. - The service is stopped. ### Example 5: Get listener configuration that matches criteria on the local computer ```powershell Get-WSManInstance -ResourceURI winrm/config/listener -SelectorSet @{Address="*";Transport="http"} ``` This command lists the WS-Management listener configuration on the local computer for the listener that matches the criteria in the selector set. ### Example 6: Get listener configuration that matches criteria on a remote computer ```powershell Get-WSManInstance -ResourceURI winrm/config/listener -SelectorSet @{Address="*";Transport="http"} -ComputerName "Server01" ``` This command lists the WS-Management listener configuration on the remote server01 computer for the listener that matches the criteria in the selector set. ### Example 7: Get associated instances related to a specified instance ```powershell Get-WSManInstance -Enumerate -Dialect Association -Filter "{Object=Win32_Service?name=winrm}" -ResourceURI wmicimv2/* ``` This command gets the associated instances that are related to the specified instance (winrm). You must enclose the filter in quotation marks, as shown in the example. ### Example 8: Get association instances related to a specified instance ```powershell Get-WSManInstance -Enumerate -Dialect Association -Associations -Filter "{Object=Win32_Service?name=winrm}" -ResourceURI wmicimv2/* ``` This command gets association instances that are related to the specified instance (winrm). Because the **Dialect** value is association and the **Associations** parameter is used, this command returns association instances, not associated instances. You must enclose the filter in quotation marks, as shown in the example. ## PARAMETERS ### -ApplicationName Specifies the application name in the connection. The default value of the **ApplicationName** parameter is WSMAN. The complete identifier for the remote endpoint is in the following format: \<transport\>://\<server\>:\<port\>/\<ApplicationName\> For example: `http://server01:8080/WSMAN` Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of WSMAN is appropriate for most uses. This parameter is designed to be used if many computers establish remote connections to one computer that is running PowerShell. In this case, IIS hosts WS-Management for efficiency. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Associations Indicates that this cmdlet gets association instances, not associated instances. You can use this parameter only when the **Dialect** parameter has a value of Association. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Enumerate Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Authentication Specifies the authentication mechanism to be used at the server. The acceptable values for this parameter are: - `Basic` - Basic is a scheme in which the user name and password are sent in clear text to the server or proxy. - `Default` - Use the authentication method implemented by the WS-Management protocol. This is the default. - `Digest` - Digest is a challenge-response scheme that uses a server-specified data string for the challenge. - `Kerberos` - The client computer and the server mutually authenticate by using Kerberos certificates. - `Negotiate` - Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows for negotiation to determine whether the Kerberos protocol or NTLM is used. - `CredSSP` - Use Credential Security Support Provider (CredSSP) authentication, which lets the user delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers. > [!CAUTION] > CredSSP delegates the user credentials from the local computer to a remote computer. This practice > increases the security risk of the remote operation. If the remote computer is compromised, when > credentials are passed to it, the credentials can be used to control the network session. ```yaml Type: Microsoft.WSMan.Management.AuthenticationMechanism Parameter Sets: (All) Aliases: auth, am Accepted values: None, Default, Digest, Negotiate, Basic, Kerberos, ClientCertificate, Credssp Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -BasePropertiesOnly Indicates that this cmdlet enumerates only the properties that are part of the base class that is specified by the **ResourceURI** parameter. This parameter has no effect if the **Shallow** parameter is specified. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Enumerate Aliases: UBPO, Base Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to perform this action. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they do not work with domain accounts. To get a certificate thumbprint, use the `Get-Item` or `Get-ChildItem` command in the PowerShell Cert: drive. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies the computer against which to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (`.`) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet. ```yaml Type: System.String Parameter Sets: (All) Aliases: CN Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ConnectionURI Specifies the connection endpoint. The format of this string is as follows: \<Transport\>://\<Server\>:\<Port\>/\<ApplicationName\> The following string is a correctly formatted value for this parameter: `http://Server01:8080/WSMAN` The URI must be fully qualified. ```yaml Type: System.Uri Parameter Sets: (All) Aliases: CURI, CU Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as User01, Domain01\User01, or User@Domain.com. Or, enter a **PSCredential** object, such as one returned by the `Get-Credential` cmdlet. When you type a user name, this cmdlet prompts you for a password. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: cred, c Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Dialect Specifies the dialect to use in the filter predicate. This can be any dialect that is supported by the remote service. The following aliases can be used for the dialect URI: - `WQL` - `http://schemas.microsoft.com/wbem/wsman/1/WQL` - Selector - `http://schemas.microsoft.com/wbem/wsman/1/wsman/SelectorFilter` - Association - `http://schemas.dmtf.org/wbem/wsman/1/cimbinding/associationFilter` ```yaml Type: System.Uri Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Enumerate Indicates that this cmdlet returns all of the instances of a management resource. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Enumerate Aliases: Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Filter Specifies the filter expression for the enumeration. If you specify this parameter, you must also specify **Dialect**. The valid values of this parameter depend on the dialect that is specified in **Dialect**. For example, if **Dialect** is WQL, the **Filter** parameter must contain a string, and the string must contain a valid WQL query such as the following query: `"Select * from Win32_Service where State != Running"` If **Dialect** is Association, **Filter** must contain a string, and the string must contain a valid filter, such as the following filter: `-filter:Object=EPR\[;AssociationClassName=AssocClassName\]\[;ResultClassName=ClassName\]\[;Role=RefPropertyName\]\[;ResultRole=RefPropertyName\]}` ```yaml Type: System.String Parameter Sets: Enumerate Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Fragment Specifies a section inside the instance that is to be updated or retrieved for the specified operation. For example, to get the status of a spooler service, specify the following: `-Fragment Status` ```yaml Type: System.String Parameter Sets: GetInstance Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OptionSet Specifies a set of switches to a service to modify or refine the nature of the request. These resemble switches used in command-line shells because they are service specific. Any number of options can be specified. The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters: `-OptionSet @{a=1;b=2;c=3}` ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: OS Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Port Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the **ComputerName** parameter must match the server's certificate common name (CN). However, if the **SkipCNCheck** parameter is specified as part of the **SessionOption** parameter, the certificate common name of the server does not have to match the host name of the server. The **SkipCNCheck** parameter should be used only for trusted computers. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ResourceURI Specifies the URI of the resource class or instance. The URI identifies a specific type of resource, such as disks or processes, on a computer. A URI consists of a prefix and a path of a resource. For example: `http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk` `http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor` ```yaml Type: System.Uri Parameter Sets: (All) Aliases: RURI Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -ReturnType Specifies the type of data to be returned. The acceptable values for this parameter are: - `Object` - `EPR` - `ObjectAndEPR` The default value is `Object`. If you specify `Object` or do not specify this parameter, this cmdlet returns only objects. If you specify endpoint reference (EPR) this cmdlet returns only the endpoint references of the objects. Endpoint references contain information about the resource URI and the selectors for the instance. If you specify `ObjectAndEPR`, this cmdlet returns both the object and its associated endpoint references. ```yaml Type: System.String Parameter Sets: Enumerate Aliases: RT Accepted values: object, epr, objectandepr Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SelectorSet Specifies a set of value pairs that are used to select particular management resource instances. The **SelectorSet** parameter is used when more than one instance of the resource exists. The value of the **SelectorSet** parameter must be a hash table. The following example shows how to enter a value for this parameter: `-SelectorSet @{Name="WinRM";ID="yyy"}` ```yaml Type: System.Collections.Hashtable Parameter Sets: GetInstance Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SessionOption Specifies extended options for the WS-Management session. Enter a **SessionOption** object that you create by using the New-WSManSessionOption cmdlet. For more information about the options that are available, type `Get-Help New-WSManSessionOption`. ```yaml Type: Microsoft.WSMan.Management.SessionOption Parameter Sets: (All) Aliases: SO Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Shallow Indicates that this cmdlet returns only instances of the base class that is specified in the resource URI. If you do not specify this parameter, this cmdlet returns instances of the base class that is specified in the URI and in all its derived classes. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: Enumerate Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL Specifies that the Secure Sockets Layer (SSL) protocol is used to establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all the Windows PowerShell content that is transmitted over the network. The **UseSSL** parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection, and you specify this parameter, the command fails. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: SSL Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Xml.XmlElement This cmdlet returns an **XMLElement** object. ## NOTES ## RELATED LINKS [Connect-WSMan](Connect-WSMan.md) [Disable-WSManCredSSP](Disable-WSManCredSSP.md) [Disconnect-WSMan](Disconnect-WSMan.md) [Enable-WSManCredSSP](Enable-WSManCredSSP.md) [Get-WSManCredSSP](Get-WSManCredSSP.md) [Invoke-WSManAction](Invoke-WSManAction.md) [New-WSManInstance](New-WSManInstance.md) [New-WSManSessionOption](New-WSManSessionOption.md) [Remove-WSManInstance](Remove-WSManInstance.md) [Set-WSManInstance](Set-WSManInstance.md) [Set-WSManQuickConfig](Set-WSManQuickConfig.md) [Test-WSMan](Test-WSMan.md)

#File: reference/7.6/Microsoft.WSMan.Management/Invoke-WSManAction.md

--- external help file: Microsoft.WSMan.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.WSMan.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.wsman.management/invoke-wsmanaction?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Invoke-WSManAction --- # Invoke-WSManAction ## SYNOPSIS Invokes an action on the object that is specified by the Resource URI and by the selectors. ## SYNTAX ### URI (Default) ``` Invoke-WSManAction [-Action] <String> [-ConnectionURI <Uri>] [-FilePath <String>] [-OptionSet <Hashtable>] [[-SelectorSet] <Hashtable>] [-SessionOption <SessionOption>] [-ValueSet <Hashtable>] [-ResourceURI] <Uri> [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ### ComputerName ``` Invoke-WSManAction [-Action] <String> [-ApplicationName <String>] [-ComputerName <String>] [-FilePath <String>] [-OptionSet <Hashtable>] [-Port <Int32>] [[-SelectorSet] <Hashtable>] [-SessionOption <SessionOption>] [-UseSSL] [-ValueSet <Hashtable>] [-ResourceURI] <Uri> [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Invoke-WSManAction` runs an action on the object that is specified by RESOURCE_URI, where parameters are specified by key value pairs. This cmdlet uses the WSMan connection/transport layer to run the action. ## EXAMPLES ### Example 1: Invoke a method ```powershell Invoke-WSManAction -Action StartService -ResourceURI wmicimv2/Win32_Service -SelectorSet @{name="spooler"} -Authentication Default ``` ```Output xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service cim : http://schemas.dmtf.org/wbem/wscim/1/common lang : en-US ReturnValue : 0 ``` This command calls the StartService method of the **Win32_Service** WMI class instance that corresponds to the Spooler service. The return value indicates whether the action was successful. In this case, a return value of 0 indicates success. A return value of 5 indicates that the service is already started. ### Example 2: Invoke a method ```powershell Invoke-WSManAction -Action StopService -ResourceURI wmicimv2/Win32_Service -SelectorSet @{Name="spooler"} -FilePath:input.xml -Authentication Default ``` ```Output xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service cim : http://schemas.dmtf.org/wbem/wscim/1/common lang : en-US ReturnValue : 0 ``` This command calls the **StopService** method on the Spooler service by using input from a file. The file, `Input.xml`, contains the following content: `<p:StopService_INPUT xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service" />` ### Example 3: Invoke a method with specified parameter values ```powershell Invoke-WSManAction -Action Create -ResourceURI wmicimv2/Win32_Process -ValueSet @{CommandLine="notepad.exe";CurrentDirectory="C:\"} ``` ```Output xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Process cim : http://schemas.dmtf.org/wbem/wscim/1/common lang : en-US ProcessId : 6356 ReturnValue : 0 ``` This command calls the **Create** method of the **Win32_Process** class. It passes the method two parameter values, `Notepad.exe` and `C:\`. As a result, a new process is created to run Notepad, and the current directory of the new process is set to `C:\`. ### Example 4: Invoke a method on a remote computer ```powershell Invoke-WSManAction -Action StartService -ResourceURI wmicimv2/Win32_Service -SelectorSet @{name="spooler"} -ComputerName server01 -Authentication Default ``` ```Output xsi : http://www.w3.org/2001/XMLSchema-instance p : http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service cim : http://schemas.dmtf.org/wbem/wscim/1/common lang : en-US ReturnValue : 0 ``` This command calls the StartService method of the **Win32_Service** WMI class instance that corresponds to the Spooler service. Because the ComputerName parameter is specified, the command runs against the remote server01 computer. The return value indicates whether the action was successful. In this case, a return value of 0 indicates success. A return value of 5 indicates that the service is already started. ## PARAMETERS ### -Action Specifies the method to run on the management object specified by the ResourceURI and selectors. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ApplicationName Specifies the application name in the connection. The default value of the ApplicationName parameter is WSMAN. The complete identifier for the remote endpoint is in the following format: `<Transport>://<Server>:<Port>/<ApplicationName>` For example: `http://server01:8080/WSMAN` Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of "WSMAN" is appropriate for most uses. This parameter is designed to be used when numerous computers establish remote connections to one computer running Windows PowerShell. In this case, IIS hosts Web Services for Management (WS-Management) for efficiency. ```yaml Type: System.String Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Authentication Specifies the authentication mechanism to be used at the server. Possible values are: - `Basic` - Basic is a scheme in which the user name and password are sent in clear text to the server or proxy. - `Default` - Use the authentication method implemented by the WS-Management protocol. This is the default. - `Digest` - Digest is a challenge-response scheme that uses a server-specified data string for the challenge. - `Kerberos` - The client computer and the server mutually authenticate by using Kerberos certificates. - `Negotiate` - Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows negotiation to determine whether the Kerberos protocol or NTLM is used. - `CredSSP` - Use Credential Security Support Provider (CredSSP) authentication, which allows the user to delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers. > [!CAUTION] > CredSSP delegates the user's credentials from the local computer to a remote computer. This > practice increases the security risk of the remote operation. If the remote computer is > compromised, when credentials are passed to it, the credentials can be used to control the network > session. ```yaml Type: Microsoft.WSMan.Management.AuthenticationMechanism Parameter Sets: (All) Aliases: auth, am Accepted values: None, Default, Digest, Negotiate, Basic, Kerberos, ClientCertificate, Credssp Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to perform this action. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they do not work with domain accounts. To get a certificate thumbprint, use the `Get-Item` or `Get-ChildItem` command in the Windows PowerShell Cert: drive. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (`.`) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet. ```yaml Type: System.String Parameter Sets: ComputerName Aliases: cn Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ConnectionURI Specifies the connection endpoint. The format of this string is: `<Transport>://<Server>:<Port>/<ApplicationName>` The following string is a properly formatted value for this parameter: `http://Server01:8080/WSMAN` The URI must be fully qualified. ```yaml Type: System.Uri Parameter Sets: URI Aliases: CURI, CU Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as "User01", "Domain01\User01", or User@Domain.com. Or, enter a PSCredential object, such as one returned by the `Get-Credential` cmdlet. When you type a user name, you will be prompted for a password. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: cred, c Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -FilePath Specifies the path of a file that is used to update a management resource. You specify the management resource by using the ResourceURI parameter and the SelectorSet parameter. For example, the following command uses the FilePath parameter: `Invoke-WSManAction -Action StopService -ResourceUri wmicimv2/Win32_Service -SelectorSet @{Name="spooler"} -FilePath C:\input.xml -Authentication Default` This command calls the **StopService** method on the Spooler service by using input from a file. The file, `Input.xml`, contains the following content: `<p:StopService_INPUT xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service" />` ```yaml Type: System.String Parameter Sets: (All) Aliases: Path Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OptionSet Passes a set of switches to a service to modify or refine the nature of the request. These are similar to switches used in command-line shells because they are service specific. Any number of options can be specified. The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters: `-OptionSet @{a=1;b=2;c=3}` ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: os Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -Port Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the ComputerName parameter must match the server's certificate common name (CN). However, if the SkipCNCheck parameter is specified as part of the SessionOption parameter, then the certificate common name of the server does not have to match the host name of the server. The SkipCNCheck parameter should be used only for trusted machines. ```yaml Type: System.Int32 Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ResourceURI Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer. A URI consists of a prefix and a path to a resource. For example: `http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk` `http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor` ```yaml Type: System.Uri Parameter Sets: (All) Aliases: ruri Required: True Position: 0 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -SelectorSet Specifies a set of value pairs that are used to select particular management resource instances. **SelectorSet** is used when more than one instance of the resource exists. The value of **SelectorSet** must be a hash table. The following example shows how to enter a value for this parameter: `-SelectorSet @{Name="WinRM";ID="yyy"}` ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: Required: False Position: 2 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -SessionOption Defines a set of extended options for the WS-Management session. Enter a SessionOption object that you create by using the `New-WSManSessionOption` cmdlet. For more information about the options that are available, see `New-WSManSessionOption`. ```yaml Type: Microsoft.WSMan.Management.SessionOption Parameter Sets: (All) Aliases: so Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL Specifies that the Secure Sockets Layer (SSL) protocol is used to establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all the PowerShell content that is transmitted over the network. The UseSSL parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this parameter, the command fails. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ValueSet Specifies a hash table that helps modify a management resource. You specify the management resource using the **ResourceURI** and **SelectorSet** parameters. The value of the ValueSet parameter must be a hash table. ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Xml.XmlElement This cmdlet returns the result of the operation as an **XmlElement** object. ## NOTES ## RELATED LINKS [Connect-WSMan](Connect-WSMan.md) [Disable-WSManCredSSP](Disable-WSManCredSSP.md) [Disconnect-WSMan](Disconnect-WSMan.md) [Enable-WSManCredSSP](Enable-WSManCredSSP.md) [Get-WSManCredSSP](Get-WSManCredSSP.md) [Get-WSManInstance](Get-WSManInstance.md) [New-WSManInstance](New-WSManInstance.md) [New-WSManSessionOption](New-WSManSessionOption.md) [Remove-WSManInstance](Remove-WSManInstance.md) [Set-WSManInstance](Set-WSManInstance.md) [Set-WSManQuickConfig](Set-WSManQuickConfig.md) [Test-WSMan](Test-WSMan.md)

#File: reference/7.6/Microsoft.WSMan.Management/Microsoft.WSMan.Management.md

--- Download Help Link: https://aka.ms/powershell75-help Help Version: 7.6.0.0 Locale: en-US Module Guid: 766204a6-330e-4263-a7ab-46c87afc366c Module Name: Microsoft.WSMan.Management ms.date: 03/01/2019 schema: 2.0.0 title: Microsoft.WSMan.Management --- # Microsoft.WSMan.Management Module ## Description This section contains the help topics for the cmdlets that are installed with PowerShell Microsoft.WSMan.Management module. The WSMan module contains cmdlets and providers that manage the WS-Management protocol in PowerShell. This module is only available on the Windows platform. ## Microsoft.WSMan.Management Cmdlets ### [Connect-WSMan](Connect-WSMan.md) Connects to the WinRM service on a remote computer. ### [Disable-WSManCredSSP](Disable-WSManCredSSP.md) Disables CredSSP authentication on a computer. ### [Disconnect-WSMan](Disconnect-WSMan.md) Disconnects the client from the WinRM service on a remote computer. ### [Enable-WSManCredSSP](Enable-WSManCredSSP.md) Enables CredSSP authentication on a computer. ### [Get-WSManCredSSP](Get-WSManCredSSP.md) Gets the Credential Security Support Provider-related configuration for the client. ### [Get-WSManInstance](Get-WSManInstance.md) Displays management information for a resource instance specified by a Resource URI. ### [Invoke-WSManAction](Invoke-WSManAction.md) Invokes an action on the object that is specified by the Resource URI and by the selectors. ### [New-WSManInstance](New-WSManInstance.md) Creates a new instance of a management resource. ### [New-WSManSessionOption](New-WSManSessionOption.md) Creates session option hash table to use as input parameters for WS-Management cmdlets. ### [Remove-WSManInstance](Remove-WSManInstance.md) Deletes a management resource instance. ### [Set-WSManInstance](Set-WSManInstance.md) Modifies the management information that is related to a resource. ### [Set-WSManQuickConfig](Set-WSManQuickConfig.md) Configures the local computer for remote management. ### [Test-WSMan](Test-WSMan.md) Tests whether the WinRM service is running on a local or remote computer.

#File: reference/7.6/Microsoft.WSMan.Management/New-WSManInstance.md

--- external help file: Microsoft.WSMan.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.WSMan.Management ms.date: 03/31/2020 online version: https://learn.microsoft.com/powershell/module/microsoft.wsman.management/new-wsmaninstance?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-WSManInstance --- # New-WSManInstance ## SYNOPSIS Creates a new instance of a management resource. ## SYNTAX ### ComputerName (Default) ``` New-WSManInstance [-ApplicationName <String>] [-ComputerName <String>] [-FilePath <String>] [-OptionSet <Hashtable>] [-Port <Int32>] [-ResourceURI] <Uri> [-SelectorSet] <Hashtable> [-SessionOption <SessionOption>] [-UseSSL] [-ValueSet <Hashtable>] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ### URI ``` New-WSManInstance [-ConnectionURI <Uri>] [-FilePath <String>] [-OptionSet <Hashtable>] [-ResourceURI] <Uri> [-SelectorSet] <Hashtable> [-SessionOption <SessionOption>] [-ValueSet <Hashtable>] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `New-WSManInstance` cmdlet creates a new instance of a management resource. It uses a resource URI and a value set or input file to create the new instance of the management resource. This cmdlet uses the WinRM connection/transport layer to create the management resource instance. ## EXAMPLES ### Example 1: Create a HTTPS listener This command creates an instance of a WS-Management HTTPS listener on all IP addresses. ```powershell New-WSManInstance winrm/config/Listener -SelectorSet @{Transport='HTTPS'; Address='*'} -ValueSet @{Hostname="HOST";CertificateThumbprint="XXXXXXXXXX"} ``` ## PARAMETERS ### -ApplicationName Specifies the application name in the connection. The default value of the **ApplicationName** parameter is **WSMAN**. The complete identifier for the remote endpoint is in the following format: `<transport>://<server>:<port>/<ApplicationName>` For example: `http://server01:8080/WSMAN` Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of **WSMAN** is appropriate for most uses. This parameter is designed to be used when numerous computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hosts Web Services for Management (WS-Management) for efficiency. ```yaml Type: System.String Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: Wsman Accept pipeline input: False Accept wildcard characters: False ``` ### -Authentication Specifies the authentication mechanism to be used at the server. Possible values are: - Basic: Basic is a scheme in which the username and password are sent in clear text to the server or proxy. - Default: Use the authentication method implemented by the WS-Management protocol. This is the default. - Digest: Digest is a challenge-response scheme that uses a server-specified data string for the challenge. - Kerberos: The client computer and the server mutually authenticate using Kerberos certificates. - Negotiate: Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows negotiation to determine whether the Kerberos protocol or NTLM is used. - CredSSP: Use Credential Security Support Provider (CredSSP) authentication, which allows the user to delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers. > [!CAUTION] > CredSSP delegates the user's credentials from the local computer to a remote computer. This > practice increases the security risk of the remote operation. If the remote computer is > compromised, when credentials are passed to it, the credentials can be used to control the network > session. ```yaml Type: Microsoft.WSMan.Management.AuthenticationMechanism Parameter Sets: (All) Aliases: auth, am Accepted values: None, Default, Digest, Negotiate, Basic, Kerberos, ClientCertificate, Credssp Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to perform this action. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they do not work with domain accounts. To get a certificate thumbprint, use the `Get-Item` or `Get-ChildItem` command in the PowerShell Cert: drive. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (`.`) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet. ```yaml Type: System.String Parameter Sets: ComputerName Aliases: cn Required: False Position: Named Default value: Localhost Accept pipeline input: False Accept wildcard characters: False ``` ### -ConnectionURI Specifies the connection endpoint. The format of this string is: `<Transport>://<Server>:<Port>/<ApplicationName>` The following string is a properly formatted value for this parameter: `http://Server01:8080/WSMAN` The URI must be fully qualified. ```yaml Type: System.Uri Parameter Sets: URI Aliases: CURI, CU Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as "User01", "Domain01\User01", or "User@Domain.com". Or, enter a PSCredential object, such as one returned by the `Get-Credential` cmdlet. When you type a user name, you will be prompted for a password. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: cred, c Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -FilePath Specifies the path of a file that is used to create a management resource. You specify the management resource using the **ResourceURI** parameter and the **SelectorSet** parameter . For example, the following command uses the **File** parameter: `Invoke-WSManAction -Action StopService -ResourceUri wmi/cimv2/Win32_Service -SelectorSet @{Name="spooler"} -File C:\input.xml -Authentication Default` This command calls the **StopService** method on the Spooler service using input from a file. The file, `Input.xml`, contains the following content: `<p:StopService_INPUT xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service" />` ```yaml Type: System.String Parameter Sets: (All) Aliases: Path Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OptionSet Passes a set of switches to a service to modify or refine the nature of the request. These are similar to switches used in command-line shells because they are service specific. Any number of options can be specified. The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters: `-OptionSet @{a=1;b=2;c=3}` ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: os Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Port Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the **ComputerName** parameter must match the server's certificate common name (CN). However, if the **SkipCNCheck** parameter is specified as part of the **SessionOption** parameter, the certificate common name of the server does not have to match the host name of the server. The **SkipCNCheck** parameter should be used only for trusted computers. ```yaml Type: System.Int32 Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ResourceURI Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer. A URI consists of a prefix and a path to a resource. For example: `http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk` `http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor` ```yaml Type: System.Uri Parameter Sets: (All) Aliases: ruri Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SelectorSet Specifies a set of value pairs that are used to select particular management resource instances. The **SelectorSet** parameter is used when more than one instance of the resource exists. The value of the **SelectorSet** parameter must be a hash table. The following example shows how to enter a value for this parameter: `-SelectorSet @{Name="WinRM";ID="yyy"}` ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -SessionOption Defines a set of extended options for the WS-Management session. Enter a **SessionOption** object that you create using the `New-WSManSessionOption` cmdlet. For more information about the options that are available, see `New-WSManSessionOption`. ```yaml Type: Microsoft.WSMan.Management.SessionOption Parameter Sets: (All) Aliases: so Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL Specifies that the Secure Sockets Layer (SSL) protocol should be used to establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all the Windows PowerShell content that is transmitted over the network. The **UseSSL** parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this parameter, the command fails. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ValueSet Specifies a hash table that helps modify a management resource. You specify the management resource using the **ResourceURI** parameter and the **SelectorSet** parameter. The value of the **ValueSet** parameter must be a hash table. ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Xml.XmlElement This cmdlet returns the created WSMan instance as an **XmlElement** object. ## NOTES The `Set-WmiInstance` cmdlet, a Windows Management Instrumentation (WMI) cmdlet, is similar. `Set-WmiInstance` uses the DCOM connection/transport layer to create or update WMI instances. ## RELATED LINKS [Connect-WSMan](Connect-WSMan.md) [Disable-WSManCredSSP](Disable-WSManCredSSP.md) [Disconnect-WSMan](Disconnect-WSMan.md) [Enable-WSManCredSSP](Enable-WSManCredSSP.md) [Get-WSManCredSSP](Get-WSManCredSSP.md) [Get-WSManInstance](Get-WSManInstance.md) [Invoke-WSManAction](Invoke-WSManAction.md) [New-WSManSessionOption](New-WSManSessionOption.md) [Remove-WSManInstance](Remove-WSManInstance.md) [Set-WSManInstance](Set-WSManInstance.md) [Set-WSManQuickConfig](Set-WSManQuickConfig.md) [Test-WSMan](Test-WSMan.md)

#File: reference/7.6/Microsoft.WSMan.Management/New-WSManSessionOption.md

--- external help file: Microsoft.WSMan.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.WSMan.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.wsman.management/new-wsmansessionoption?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: New-WSManSessionOption --- # New-WSManSessionOption ## SYNOPSIS Creates session option hash table to use as input parameters for WS-Management cmdlets. ## SYNTAX ``` New-WSManSessionOption [-ProxyAccessType <ProxyAccessType>] [-ProxyAuthentication <ProxyAuthentication>] [-ProxyCredential <PSCredential>] [-SkipCACheck] [-SkipCNCheck] [-SkipRevocationCheck] [-SPNPort <Int32>] [-OperationTimeout <Int32>] [-NoEncryption] [-UseUTF16] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `New-WSManSessionOption` cmdlet creates a WSMan Session option hash table which can be passed to WSMan cmdlets: - `Get-WSManInstance` - `Set-WSManInstance` - `Invoke-WSManAction` - `Connect-WSMan` ## EXAMPLES ### Example 1: Create a connection that uses connection options ```powershell PS C:\> $a = New-WSManSessionOption -OperationTimeout 30000 PS C:\> Connect-WSMan -ComputerName "server01" -SessionOption $a PS C:\> cd WSMan: PS WSMan:\> dir ``` ```Output WSManConfig: Microsoft.WSMan.Management\WSMan::WSMan ComputerName Type ------------ ---- localhost Container server01 Container ``` This example creates a connection to the remote server01 computer by using the connection options that are defined by `New-WSManSessionOption`. The first command uses `New-WSManSessionOption` to store a set of connection setting options in the `$a` variable. In this case, the session options set a connection time out of 30 seconds (30,000 milliseconds). The second command uses the **SessionOption** parameter to pass the credentials that are stored in the `$a` variable to `Connect-WSMan`. Then, `Connect-WSMan` connects to the remote server01 computer by using the specified session options. `Connect-WSMan` is generally used in the context of the WSMan provider to connect to a remote computer, in this case the server01 computer. However, you can use the cmdlet to establish connections to remote computers before you change to the WSMan provider. Those connections appear in the **ComputerName** list. ## PARAMETERS ### -NoEncryption Indicates that the connection does not use encryption for remote operations over HTTP. By default, unencrypted traffic is not enabled. It must be enabled in the local configuration. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OperationTimeout Specifies the time-out, in milliseconds, for the WS-Management operation. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: OperationTimeoutMSec Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProxyAccessType Specifies the mechanism by which the proxy server is located. The acceptable values for this parameter are: - `ProxyIEConfig` - Use the Internet Explorer proxy configuration for the current user. - `ProxyWinHttpConfig` - The WSMan client uses the proxy settings configured for WinHTTP, using the ProxyCfg.exe utility. - `ProxyAutoDetect` - Force auto-detection of a proxy server. - `ProxyNoProxyServer` - Do not use a proxy server. Resolve all host names locally. The default value is ProxyIEConfig. ```yaml Type: Microsoft.WSMan.Management.ProxyAccessType Parameter Sets: (All) Aliases: Accepted values: ProxyIEConfig, ProxyWinHttpConfig, ProxyAutoDetect, ProxyNoProxyServer Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProxyAuthentication Specifies the authentication method to use at the proxy. The acceptable values for this parameter are: - `Basic` - Basic is a scheme in which the user name and password are sent in clear-text to the server or proxy. - `Digest` - Digest is a challenge-response scheme that uses a server-specified data string for the challenge. - `Negotiate` - Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine which scheme to use for authentication. Examples are the Kerberos protocol and NTLM. The default value is Negotiate. ```yaml Type: Microsoft.WSMan.Management.ProxyAuthentication Parameter Sets: (All) Aliases: Accepted values: Negotiate, Basic, Digest Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProxyCredential Specifies a user account that has permission to gain access through an intermediate Web proxy. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipCACheck Specifies that, when it connects over HTTPS, the client does not validate that the server certificate is signed by a trusted certification authority (CA). Use this option only when the remote computer is trusted by another method, for example, if the remote computer is part of a network that is physically secure and isolated or the remote computer is listed as a trusted host in the WS-Management configuration. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipCNCheck Specifies that the certificate common name (CN) of the server does not have to match the host name of the server. This is used only in remote operations using HTTPS. This option should only be used for trusted computers. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipRevocationCheck Indicates that the connection does not validate the revocation status on the server certificate. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SPNPort Specifies a port number to append to the connection Service Principal Name (SPN) of the remote server. An SPN is used when the authentication mechanism is Kerberos or Negotiate. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseUTF16 Indicates that the connection encodes the request in UTF16 format instead of UTF8 format. The default is UTF8 encoding. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ## OUTPUTS ### Microsoft.WSMan.Management.SessionOption This cmdlet returns the created WSMan session option as a **SessionOption** object. ## NOTES ## RELATED LINKS [Connect-WSMan](Connect-WSMan.md) [Disable-WSManCredSSP](Disable-WSManCredSSP.md) [Disconnect-WSMan](Disconnect-WSMan.md) [Enable-WSManCredSSP](Enable-WSManCredSSP.md) [Get-WSManCredSSP](Get-WSManCredSSP.md) [Get-WSManInstance](Get-WSManInstance.md) [Invoke-WSManAction](Invoke-WSManAction.md) [New-WSManInstance](New-WSManInstance.md) [Remove-WSManInstance](Remove-WSManInstance.md) [Set-WSManInstance](Set-WSManInstance.md) [Set-WSManQuickConfig](Set-WSManQuickConfig.md) [Test-WSMan](Test-WSMan.md)

#File: reference/7.6/Microsoft.WSMan.Management/Remove-WSManInstance.md

--- external help file: Microsoft.WSMan.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.WSMan.Management ms.date: 09/20/2023 online version: https://learn.microsoft.com/powershell/module/microsoft.wsman.management/remove-wsmaninstance?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-WSManInstance --- # Remove-WSManInstance ## SYNOPSIS Deletes a management resource instance. ## SYNTAX ### ComputerName (Default) ``` Remove-WSManInstance [-ApplicationName <String>] [-ComputerName <String>] [-OptionSet <Hashtable>] [-Port <Int32>] [-ResourceURI] <Uri> [-SelectorSet] <Hashtable> [-SessionOption <SessionOption>] [-UseSSL] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ### URI ``` Remove-WSManInstance [-ConnectionURI <Uri>] [-OptionSet <Hashtable>] [-ResourceURI] <Uri> [-SelectorSet] <Hashtable> [-SessionOption <SessionOption>] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Remove-WSManInstance` cmdlet deletes an instance of a management resource that's specified in the **ResourceURI** and **SelectorSet** parameters. This cmdlet uses the WinRM connection transport layer to delete the management resource instance. ## EXAMPLES ### Example 1: Delete a listener ```powershell Remove-WSManInstance -ResourceUri winrm/config/Listener -SelectorSet @{ Address = 'test.fabrikam.com' Transport = 'http' } ``` This command deletes the WS-Management HTTP listener on a computer. ## PARAMETERS ### -ApplicationName Specifies the application name in the connection. The default value of the **ApplicationName** parameter is WSMAN. The complete identifier for the remote endpoint is in the following format: `<Transport>://<Server>:<Port>/<ApplicationName>` For example: `http://server01:8080/WSMAN` Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of WSMAN is appropriate for most uses. This parameter is designed to be used if many computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hosts Web Services for Management (WS-Management) for efficiency. ```yaml Type: System.String Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Authentication Specifies the authentication mechanism to be used at the server. The acceptable values for this parameter are: - `Basic` - Basic is a scheme in which the user name and password are sent in clear text to the server or proxy. - `Default` - Use the authentication method implemented by the WS-Management protocol. This is the default. - `Digest` - Digest is a challenge-response scheme that uses a server-specified data string for the challenge. - `Kerberos` - The client computer and the server mutually authenticate by using Kerberos certificates. - `Negotiate` - Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows for negotiation to determine whether the Kerberos protocol or NTLM is used. - `CredSSP` - Use Credential Security Support Provider (CredSSP) authentication, which lets the user delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers. > [!CAUTION] > CredSSP delegates the user credentials from the local computer to a remote computer. This practice > increases the security risk of the remote operation. If the remote computer is compromised, when > credentials are passed to it, the credentials can be used to control the network session. ```yaml Type: Microsoft.WSMan.Management.AuthenticationMechanism Parameter Sets: (All) Aliases: auth, am Accepted values: None, Default, Digest, Negotiate, Basic, Kerberos, ClientCertificate, Credssp Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to perform this action. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts. Certificates don't work with domain accounts. To get a certificate thumbprint, use the `Get-Item` or `Get-ChildItem` command in the PowerShell `Cert:` drive. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies the computer against which to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (`.`) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet. ```yaml Type: System.String Parameter Sets: ComputerName Aliases: cn Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ConnectionURI Specifies the connection endpoint. The format of this string is as follows: `<Transport>://<Server>:<Port>/<ApplicationName>` The following string is a correctly formatted value for this parameter: `http://Server01:8080/WSMAN` The URI must be fully qualified. ```yaml Type: System.Uri Parameter Sets: URI Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as `User01`, `Domain01\User01`, or `User@Domain.com`. Or, enter a **PSCredential** object, such as one returned by the `Get-Credential` cmdlet. When you type a user name, this cmdlet prompts you for a password. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: cred, c Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -OptionSet Specifies a set of switches to a service to modify or refine the nature of the request. These resemble switches used in command-line shells because they are service specific. Any number of options can be specified. The following example demonstrates the syntax that passes the values 1, 2, and 3 for the a, b, and c parameters: `-OptionSet @{a=1;b=2;c=3}` ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: os Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Port Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the **ComputerName** parameter must match the server's certificate common name (CN). However, if the **SkipCNCheck** parameter is specified as part of the **SessionOption** parameter, the certificate common name of the server does not have to match the host name of the server. The **SkipCNCheck** parameter should be used only for trusted computers. ```yaml Type: System.Int32 Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ResourceURI Specifies the URI of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer. A URI consists of a prefix and a path of a resource. For example: `http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk` `http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor` ```yaml Type: System.Uri Parameter Sets: (All) Aliases: ruri Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SelectorSet Specifies a set of value pairs that are used to select particular management resource instances. The **SelectorSet** parameter is used when more than one instance of the resource exists. The value of **SelectorSet** must be a hash table. The following example shows how to enter a value for this parameter: `-SelectorSet @{Name="WinRM";ID="yyy"}` ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: Required: True Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -SessionOption Specifies extended options for the WS-Management session. Enter a **SessionOption** object that you create by using the New-WSManSessionOption cmdlet. For more information about the options that are available, type `Get-Help New-WSManSessionOption`. ```yaml Type: Microsoft.WSMan.Management.SessionOption Parameter Sets: (All) Aliases: so Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL Specifies that the Secure Sockets Layer (SSL) protocol is used to establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all the Windows PowerShell content that is transmitted over the network. The **UseSSL** parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection, and you specify this parameter, the command fails. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerName Aliases: ssl Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES The cmdlets in the CimCmdlets module are similar. They use the DCOM connection/transport layer to create or update WMI instances. ## RELATED LINKS [Connect-WSMan](Connect-WSMan.md) [Disable-WSManCredSSP](Disable-WSManCredSSP.md) [Disconnect-WSMan](Disconnect-WSMan.md) [Enable-WSManCredSSP](Enable-WSManCredSSP.md) [Get-WSManCredSSP](Get-WSManCredSSP.md) [Get-WSManInstance](Get-WSManInstance.md) [Invoke-WSManAction](Invoke-WSManAction.md) [New-WSManInstance](New-WSManInstance.md) [New-WSManSessionOption](New-WSManSessionOption.md) [Set-WSManInstance](Set-WSManInstance.md) [Set-WSManQuickConfig](Set-WSManQuickConfig.md) [Test-WSMan](Test-WSMan.md)

#File: reference/7.6/Microsoft.WSMan.Management/Set-WSManInstance.md

--- external help file: Microsoft.WSMan.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.WSMan.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.wsman.management/set-wsmaninstance?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-WSManInstance --- # Set-WSManInstance ## SYNOPSIS Modifies the management information that is related to a resource. ## SYNTAX ### ComputerName (Default) ``` Set-WSManInstance [-ApplicationName <String>] [-ComputerName <String>] [-Dialect <Uri>] [-FilePath <String>] [-Fragment <String>] [-OptionSet <Hashtable>] [-Port <Int32>] [-ResourceURI] <Uri> [[-SelectorSet] <Hashtable>] [-SessionOption <SessionOption>] [-UseSSL] [-ValueSet <Hashtable>] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ### URI ``` Set-WSManInstance [-ConnectionURI <Uri>] [-Dialect <Uri>] [-FilePath <String>] [-Fragment <String>] [-OptionSet <Hashtable>] [-ResourceURI] <Uri> [[-SelectorSet] <Hashtable>] [-SessionOption <SessionOption>] [-ValueSet <Hashtable>] [-Credential <PSCredential>] [-Authentication <AuthenticationMechanism>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ## DESCRIPTION The `Set-WSManInstance` cmdlet modifies the management information that is related to a resource. This cmdlet uses the WinRM connection/transport layer to modify the information. ## EXAMPLES ### Example 1: Disable a listener on the local computer ```powershell Set-WSManInstance -ResourceURI winrm/config/listener -SelectorSet @{address="*";transport="https"} -ValueSet @{Enabled="false"} ``` ```Output cfg : http://schemas.microsoft.com/wbem/wsman/1/config/listener xsi : http://www.w3.org/2001/XMLSchema-instance lang : en-US Address : * Transport : HTTPS Port : 443 Hostname : Enabled : false URLPrefix : wsman CertificateThumbprint : ListeningOn : {127.0.0.1, 172.30.168.171, ::1, 2001:4898:0:fff:0:5efe:172.30.168.171...} ``` This command disables the HTTPS listener on the local computer. > [!IMPORTANT] > The **ValueSet** parameter is case-sensitive when matching the properties specified. For example, in this command, This fails: `-ValueSet @{enabled="False"}` This succeeds: `-ValueSet @{Enabled="False"}` ### Example 2: Set the maximum envelope size on the local computer ```powershell Set-WSManInstance -ResourceURI winrm/config -ValueSet @{MaxEnvelopeSizekb = "200"} ``` ```Output cfg : http://schemas.microsoft.com/wbem/wsman/1/config lang : en-US MaxEnvelopeSizekb : 200 MaxTimeoutms : 60000 MaxBatchItems : 32000 MaxProviderRequests : 4294967295 Client : Client Service : Service Winrs : Winrs ``` This command sets the **MaxEnvelopeSizekb** value to 200 on the local computer. > [!IMPORTANT] > The **ValueSet** parameter is case-sensitive when matching the properties specified. For example, using the above command. This fails: `-ValueSet @{MaxEnvelopeSizeKB ="200"}` This succeeds: `-ValueSet @{MaxEnvelopeSizekb ="200"}` ### Example 3: Disable a listener on a remote computer ```powershell Set-WSManInstance -ResourceURI winrm/config/listener -ComputerName SERVER02 -SelectorSet @{address="*";transport="https"} -ValueSet @{Enabled="false"} ``` ```Output cfg : http://schemas.microsoft.com/wbem/wsman/1/config/listener xsi : http://www.w3.org/2001/XMLSchema-instance lang : en-US Address : * Transport : HTTPS Port : 443 Hostname : Enabled : false URLPrefix : wsman CertificateThumbprint : ListeningOn : {127.0.0.1, 172.30.168.172, ::1, 2001:4898:0:fff:0:5efe:172.30.168.172...} ``` This command disables the HTTPS listener on the remote computer SERVER02. > [!IMPORTANT] > The **ValueSet** parameter is case-sensitive when matching the properties specified. For example, using the above command. This fails: `-ValueSet @{enabled="False"}` This succeeds: `-ValueSet @{Enabled="False"}` ## PARAMETERS ### -ApplicationName Specifies the application name in the connection. The default value of the **ApplicationName** parameter is "WSMAN". The complete identifier for the remote endpoint is in the following format: `<transport>://<server>:<port>/<ApplicationName>` For example: `http://server01:8080/WSMAN` Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of `WSMAN` is appropriate for most uses. This parameter is designed to be used when numerous computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hosts Web Services for Management (WS-Management) for efficiency. ```yaml Type: System.String Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: Wsman Accept pipeline input: False Accept wildcard characters: False ``` ### -Authentication Specifies the authentication mechanism to be used at the server. Possible values are: - `Basic`: Basic is a scheme in which the user name and password are sent in clear text to the server or proxy. - `Default` : Use the authentication method implemented by the WS-Management protocol. This is the default. - `Digest`: Digest is a challenge-response scheme that uses a server-specified data string for the challenge. - `Kerberos`: The client computer and the server mutually authenticate by using Kerberos certificates. - `Negotiate`: Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows negotiation to determine whether the Kerberos protocol or NTLM is used. - `CredSSP`: Use Credential Security Support Provider (CredSSP) authentication, which allows the user to delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers. > [!CAUTION] > CredSSP delegates the user's credentials from the local computer to a remote computer. This > practice increases the security risk of the remote operation. If the remote computer is > compromised, when credentials are passed to it, the credentials can be used to control the network > session. ```yaml Type: Microsoft.WSMan.Management.AuthenticationMechanism Parameter Sets: (All) Aliases: auth, am Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to perform this action. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they do not work with domain accounts. To get a certificate thumbprint, use the `Get-Item` or `Get-ChildItem` command in the PowerShell `Cert:` drive. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies the computer against which you want to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, `localhost`, or a dot (`.`) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name. You can pipe a value for this parameter to the cmdlet. ```yaml Type: System.String Parameter Sets: ComputerName Aliases: cn Required: False Position: Named Default value: Localhost Accept pipeline input: False Accept wildcard characters: False ``` ### -ConnectionURI Specifies the connection endpoint. The format of this string is: `<Transport>://<Server>:<Port>/<ApplicationName>` The following string is a properly formatted value for this parameter: `http://Server01:8080/WSMAN` The URI must be fully qualified. ```yaml Type: System.Uri Parameter Sets: URI Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as `User01`, `Domain01\User01`, or `User@Domain.com`. Alternatively, enter a **PSCredential** object, such as one returned by the `Get-Credential` cmdlet. When you type a user name, you will be prompted for a password. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: cred, c Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Dialect Specifies the dialect to use in the filter predicate. This can be any dialect that is supported by the remote service. The following aliases can be used for the dialect URI: - `WQL`: `http://schemas.microsoft.com/wbem/wsman/1/WQL` - `Selector`: `http://schemas.microsoft.com/wbem/wsman/1/wsman/SelectorFilter` - `Association`: `http://schemas.dmtf.org/wbem/wsman/1/cimbinding/associationFilter` ```yaml Type: System.Uri Parameter Sets: (All) Aliases: Required: False Position: Named Default value: http://schemas.microsoft.com/wbem/wsman/1/WQL Accept pipeline input: False Accept wildcard characters: False ``` ### -FilePath Specifies the path of a file that is used to update a management resource. You specify the management resource by using the **ResourceURI** parameter and the **SelectorSet** parameter. For example, the following command uses the **FilePath** parameter: `Invoke-WSManAction -Action StopService -ResourceUri wmicimv2/Win32_Service -SelectorSet @{Name="spooler"} -FilePath:C:\input.xml -Authentication Default` This command calls the **StopService** method on the Spooler service by using input from a file. The file, `Input.xml`, contains the following content: `<p:StopService_INPUT xmlns:p="http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_Service" />` ```yaml Type: System.String Parameter Sets: (All) Aliases: Path Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Fragment Specifies a section inside the instance that is to be updated or retrieved for the specified operation. For example, to get the status of a spooler service, specify `-Fragment Status`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -OptionSet Passes a set of switches to a service to modify or refine the nature of the request. These are similar to switches used in command-line shells because they are service specific. Any number of options can be specified. The following example demonstrates the syntax that passes the values `1`, `2`, and `3` for the `a`, `b`, and `c` parameters: `-OptionSet @{a=1;b=2;c=3}` ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: os Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Port Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the **ComputerName** parameter must match the server's certificate common name (CN). However, if the **SkipCNCheck** parameter is specified as part of the **SessionOption** parameter, then the certificate common name of the server does not have to match the host name of the server. The **SkipCNCheck** parameter should be used only for trusted machines. ```yaml Type: System.Int32 Parameter Sets: ComputerName Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ResourceURI Contains the Uniform Resource Identifier (URI) of the resource class or instance. The URI is used to identify a specific type of resource, such as disks or processes, on a computer. A URI consists of a prefix and a path to a resource. For example: `http://schemas.microsoft.com/wbem/wsman/1/wmi/root/cimv2/Win32_LogicalDisk` `http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_NumericSensor` ```yaml Type: System.Uri Parameter Sets: (All) Aliases: ruri Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SelectorSet Specifies a set of value pairs that are used to select particular management resource instances. The **SelectorSet** parameter is used when more than one instance of the resource exists. The value of the **SelectorSet** parameter must be a hash table. The following example shows how to enter a value for this parameter: `-SelectorSet @{Name="WinRM";ID="yyy"}` ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: None Accept pipeline input: True (ByPropertyName, ByValue) Accept wildcard characters: False ``` ### -SessionOption Defines a set of extended options for the WS-Management session. Enter a **SessionOption** object that you create with the `New-WSManSessionOption` cmdlet. For more information about the options that are available, see [New-WSManSessionOption](New-WSManSessionOption.md). ```yaml Type: Microsoft.WSMan.Management.SessionOption Parameter Sets: (All) Aliases: so Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL Specifies that the Secure Sockets Layer (SSL) protocol should be used to establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all the Windows PowerShell content that is transmitted over the network. The **UseSSL** parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection and you specify this parameter, the command fails. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: ComputerName Aliases: ssl Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ValueSet Specifies a hash table that helps modify a management resource. You specify the management resource by using the **ResourceURI** parameter and the **SelectorSet** parameter. The value of the **ValueSet** parameter must be a hash table. ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](../Microsoft.PowerShell.Core/About/about_CommonParameters.md). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Xml.XmlElement This cmdlet returns the updated WSMan instance as an **XmlElement** object. ## NOTES ## RELATED LINKS [Connect-WSMan](Connect-WSMan.md) [Disable-WSManCredSSP](Disable-WSManCredSSP.md) [Disconnect-WSMan](Disconnect-WSMan.md) [Enable-WSManCredSSP](Enable-WSManCredSSP.md) [Get-WSManCredSSP](Get-WSManCredSSP.md) [Get-WSManInstance](Get-WSManInstance.md) [Invoke-WSManAction](Invoke-WSManAction.md) [New-WSManInstance](New-WSManInstance.md) [New-WSManSessionOption](New-WSManSessionOption.md) [Remove-WSManInstance](Remove-WSManInstance.md) [Set-WSManQuickConfig](Set-WSManQuickConfig.md) [Test-WSMan](Test-WSMan.md)

#File: reference/7.6/Microsoft.WSMan.Management/Set-WSManQuickConfig.md

--- external help file: Microsoft.WSMan.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.WSMan.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.wsman.management/set-wsmanquickconfig?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-WSManQuickConfig --- # Set-WSManQuickConfig ## SYNOPSIS Configures the local computer for remote management. ## SYNTAX ### All ``` Set-WSManQuickConfig [-UseSSL] [-Force] [-SkipNetworkProfileCheck] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Set-WSManQuickConfig` cmdlet configures the computer to receive PowerShell remote commands that are sent by using the Web Services for Management (WS-Management) technology. `Set-WSManQuickConfig` performs the following actions: - Checks whether the WinRM service is running. If the WinRM service isn't running, the service is started. - Sets the WinRM service startup type to automatic. - Creates a listener to accept requests on any IP address. The default transport is **HTTP**. - Enables a firewall exception for WinRM traffic. To run `Set-WSManQuickConfig`, start PowerShell with the **Run as Administrator** option. ## EXAMPLES ### Example 1: Enable remote management of the local computer over HTTP This example sets the required configuration to enable remote management of the local computer. By default, this command creates a WS-Management listener on **HTTP**. ```powershell Set-WSManQuickConfig ``` ### Example 2: Enable remote management of the local computer over HTTPS This example sets the required configuration to enable remote management of the local computer. The **UseSSL** parameter specifies that **HTTPS** is used to communicate with the computer. ```powershell Set-WSManQuickConfig -UseSSL ``` > [!NOTE] > **HTTPS** requires manual configuration. For more information, see the **UseSSL** parameter's > description. ## PARAMETERS ### -Force Forces the command to run without asking for user confirmation. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -SkipNetworkProfileCheck Configures Windows client versions for remoting when the computer is on a public network. This parameter enables a firewall rule for public networks that allows remote access only from computers in the same local subnet. This parameter has no effect on server versions of Windows, that by default, have a local subnet firewall rule for public networks. If the local subnet firewall rule is disabled on the server version of Windows, `Enable-PSRemoting` re-enables it, regardless of this parameter's value. To remove the local subnet restriction and enable remote access from all locations on public networks, use the `Set-NetFirewallRule` cmdlet in the **NetSecurity** module. This parameter was introduced in PowerShell 3.0. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL Specifies that the Secure Sockets Layer (SSL) protocol is used to establish a connection to the remote computer. By default, SSL isn't used. WS-Management encrypts all the PowerShell content that is transmitted over the network. The **UseSSL** parameter lets you specify the additional protection of HTTPS instead of HTTP. If you use this parameter and SSL isn't available on the port that's used for the connection, the command fails. **HTTPS** requires manual configuration of WinRM and firewall rules. For more information, see [How To: Configure WINRM for HTTPS](https://support.microsoft.com/help/2019527/how-to-configure-winrm-for-https). ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.String This cmdlet returns a message as a **String** object describing the state of the configuration after the operation. ## NOTES ## RELATED LINKS [Connect-WSMan](Connect-WSMan.md) [Disable-WSManCredSSP](Disable-WSManCredSSP.md) [Disconnect-WSMan](Disconnect-WSMan.md) [Enable-PSRemoting](../Microsoft.PowerShell.Core/Enable-PSRemoting.md) [Enable-WSManCredSSP](Enable-WSManCredSSP.md) [Get-WSManCredSSP](Get-WSManCredSSP.md) [Get-WSManInstance](Get-WSManInstance.md) [How To: Configure WINRM for HTTPS](https://support.microsoft.com/help/2019527/how-to-configure-winrm-for-https) [Invoke-WSManAction](Invoke-WSManAction.md) [New-PSSession](../Microsoft.PowerShell.Core/New-PSSession.md) [New-WSManInstance](New-WSManInstance.md) [New-WSManSessionOption](New-WSManSessionOption.md) [Test-WSMan](Test-WSMan.md)

#File: reference/7.6/Microsoft.WSMan.Management/Test-WSMan.md

--- external help file: Microsoft.WSMan.Management.dll-Help.xml Locale: en-US Module Name: Microsoft.WSMan.Management ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/microsoft.wsman.management/test-wsman?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Test-WSMan --- # Test-WSMan ## SYNOPSIS Tests whether the WinRM service is running on a local or remote computer. ## SYNTAX ``` Test-WSMan [[-ComputerName] <String>] [-Authentication <AuthenticationMechanism>] [-Port <Int32>] [-UseSSL] [-ApplicationName <String>] [-Credential <PSCredential>] [-CertificateThumbprint <String>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** The `Test-WSMan` cmdlet submits an identification request that determines whether the WinRM service is running on a local or remote computer. If the tested computer is running the service, the cmdlet displays the WS-Management identity schema, the protocol version, the product vendor, and the product version of the tested service. ## EXAMPLES ### Example 1: Determine the status of the WinRM service ```powershell Test-WSMan ``` This command determines whether the WinRM service is running on the local computer or on a remote computer. ### Example 2: Determine the status of the WinRM service on a remote computer ```powershell Test-WSMan -ComputerName "server01" ``` This command determines whether the WinRM service is running on the server01 computer. ### Example 3: Determine the status of the WinRM service and the operating system version ```powershell Test-WSMan -Authentication Default ``` This command tests to see whether the WS-Management (WinRM) service is running on the local computer by using the **Authentication** parameter. Using the **Authentication** parameter enables `Test-WSMan` to return the operating system version. ### Example 4: Determine the status of the WinRM service and the OS version on a remote computer ```powershell Test-WSMan -ComputerName "server01" -Authentication Default ``` This command tests to see whether the WS-Management (WinRM) service is running on the computer named server01 using the **Authentication** parameter. Using the **Authentication** parameter enables `Test-WSMan` to return the operating system version. ## PARAMETERS ### -ApplicationName Specifies the application name in the connection. The default value of the **ApplicationName** parameter is WSMAN. The complete identifier for the remote endpoint is in the following format: `<Transport>://<Server>:<Port>/<ApplicationName>` For example: `http://server01:8080/WSMAN` Internet Information Services (IIS), which hosts the session, forwards requests with this endpoint to the specified application. This default setting of WSMAN is appropriate for most uses. This parameter is designed to be used if many computers establish remote connections to one computer that is running Windows PowerShell. In this case, IIS hosts Web Services for Management (WS-Management) for efficiency. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Authentication Specifies the authentication mechanism to be used at the server. The acceptable values for this parameter are: - `Basic` - Basic is a scheme in which the user name and password are sent in clear text to the server or proxy. - `Default` - Use the authentication method implemented by the WS-Management protocol. This is the default. - 1 - Digest is a challenge-response scheme that uses a server-specified data string for the challenge. - `Kerberos` - The client computer and the server mutually authenticate by using Kerberos certificates. - `Negotiate` - Negotiate is a challenge-response scheme that negotiates with the server or proxy to determine the scheme to use for authentication. For example, this parameter value allows for negotiation to determine whether the Kerberos protocol or NTLM is used. - `CredSSP` - Use Credential Security Support Provider (CredSSP) authentication, which lets the user delegate credentials. This option is designed for commands that run on one remote computer but collect data from or run additional commands on other remote computers. > [!CAUTION] > CredSSP delegates the user credentials from the local computer to a remote computer. This practice > increases the security risk of the remote operation. If the remote computer is compromised, when > credentials are passed to it, the credentials can be used to control the network session. > [!IMPORTANT] > If you do not specify the **Authentication** parameter, the `Test-WSMan` request is sent to the > remote computer anonymously, without using authentication. If the request is made anonymously, it > returns no information that is specific to the operating-system version. Instead, this cmdlet > displays null values for the operating system version and service pack level (OS: 0.0.0 SP: 0.0). ```yaml Type: Microsoft.WSMan.Management.AuthenticationMechanism Parameter Sets: (All) Aliases: auth, am Accepted values: None, Default, Digest, Negotiate, Basic, Kerberos, ClientCertificate, Credssp Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CertificateThumbprint Specifies the digital public key certificate (X509) of a user account that has permission to perform this action. Enter the certificate thumbprint of the certificate. Certificates are used in client certificate-based authentication. They can be mapped only to local user accounts; they do not work with domain accounts. To get a certificate thumbprint, use the Get-Item or `Get-ChildItem` command in the Windows PowerShell Cert: drive. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ComputerName Specifies the computer against which to run the management operation. The value can be a fully qualified domain name, a NetBIOS name, or an IP address. Use the local computer name, use localhost, or use a dot (`.`) to specify the local computer. The local computer is the default. When the remote computer is in a different domain from the user, you must use a fully qualified domain name must be used. You can pipe a value for this parameter to the cmdlet. ```yaml Type: System.String Parameter Sets: (All) Aliases: cn Required: False Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Credential Specifies a user account that has permission to perform this action. The default is the current user. Type a user name, such as User01, Domain01\User01, or User@Domain.com. Or, enter a **PSCredential** object, such as one returned by the `Get-Credential` cmdlet. When you type a user name, this cmdlet prompts you for a password. ```yaml Type: System.Management.Automation.PSCredential Parameter Sets: (All) Aliases: cred, c Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Port Specifies the port to use when the client connects to the WinRM service. When the transport is HTTP, the default port is 80. When the transport is HTTPS, the default port is 443. When you use HTTPS as the transport, the value of the **ComputerName** parameter must match the server's certificate common name (CN). ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -UseSSL Specifies that the Secure Sockets Layer (SSL) protocol is used to establish a connection to the remote computer. By default, SSL is not used. WS-Management encrypts all the Windows PowerShell content that is transmitted over the network. The **UseSSL** parameter lets you specify the additional protection of HTTPS instead of HTTP. If SSL is not available on the port that is used for the connection, and you specify this parameter, the command fails. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### System.Xml.XmlElement This cmdlet returns an **XmlElement** object representing the result of the test. ## NOTES By default, the `Test-WSMan` cmdlet queries the WinRM service without using authentication, and it returns no information that is specific to the operating-system version. Instead, it displays null values for the operating system version and service pack level (OS: 0.0.0 SP: 0.0). ## RELATED LINKS [Connect-WSMan](Connect-WSMan.md) [Disable-WSManCredSSP](Disable-WSManCredSSP.md) [Disconnect-WSMan](Disconnect-WSMan.md) [Enable-WSManCredSSP](Enable-WSManCredSSP.md) [Get-WSManCredSSP](Get-WSManCredSSP.md) [Get-WSManInstance](Get-WSManInstance.md) [Invoke-WSManAction](Invoke-WSManAction.md) [New-WSManInstance](New-WSManInstance.md) [New-WSManSessionOption](New-WSManSessionOption.md) [Remove-WSManInstance](Remove-WSManInstance.md) [Set-WSManInstance](Set-WSManInstance.md) [Set-WSManQuickConfig](Set-WSManQuickConfig.md)

#File: reference/7.6/PSDiagnostics/Disable-PSTrace.md

--- external help file: PSDiagnostics-help.xml Locale: en-US Module Name: PSDiagnostics ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/psdiagnostics/disable-pstrace?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Disable-PSTrace --- # Disable-PSTrace ## SYNOPSIS Disables the Microsoft-Windows-PowerShell event provider logs. ## SYNTAX ``` Disable-PSTrace [-AnalyticOnly] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** This cmdlet disables the Operational and Analytic event logs of the Microsoft-Windows-PowerShell event provider. You must run this cmdlet from an elevated PowerShell session. ## EXAMPLES ### Example 1: Disable the Analytic event log for PowerShell The following example disables only the Analytic event log of the Microsoft-Windows-PowerShell provider. ```powershell Disable-PSTrace -AnalyticOnly ``` ## PARAMETERS ### -AnalyticOnly When this parameter is used, the cmdlet disables the Analytic event log of the Microsoft-Windows-PowerShell provider. The Operational event log is not changed. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES This cmdlet uses the `Get-LogProperties` and `Set-LogProperties` cmdlets. You must run this cmdlet from an elevated PowerShell session. ## RELATED LINKS [Get-LogProperties](Get-LogProperties.md) [Set-LogProperties](Set-LogProperties.md) [Enable-PSTrace](Enable-PSTrace.md)

#File: reference/7.6/PSDiagnostics/Disable-PSWSManCombinedTrace.md

--- external help file: PSDiagnostics-help.xml Locale: en-US Module Name: PSDiagnostics ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/psdiagnostics/disable-pswsmancombinedtrace?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Disable-PSWSManCombinedTrace --- # Disable-PSWSManCombinedTrace ## SYNOPSIS Stop the logging session started by Enable-PSWSManCombinedTrace. ## SYNTAX ``` Disable-PSWSManCombinedTrace [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** This cmdlet stops the logging session started by `Enable-PSWSManCombinedTrace`. This cmdlet uses the `Stop-Trace` cmdlet. You must run this cmdlet from an elevated PowerShell session. ## EXAMPLES ### Example 1: Disable the combined logging session ```powershell Disable-PSWSManCombinedTrace ``` ## PARAMETERS ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES ## RELATED LINKS [Event Tracing](/windows/desktop/ETW/event-tracing-portal) [Stop-Trace](stop-trace.md) [Enable-PSWSManCombinedTrace](Enable-PSWSManCombinedTrace.md)

#File: reference/7.6/PSDiagnostics/Disable-WSManTrace.md

--- external help file: PSDiagnostics-help.xml Locale: en-US Module Name: PSDiagnostics ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/psdiagnostics/disable-wsmantrace?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Disable-WSManTrace --- # Disable-WSManTrace ## SYNOPSIS Stop the WSMan logging session started by Enable-WSManTrace. ## SYNTAX ``` Disable-WSManTrace [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** This cmdlet stops the WSMan logging session started by Enable-WSManTrace. This cmdlet uses the `Stop-Trace` cmdlet. You must run this cmdlet from an elevated PowerShell session. ## EXAMPLES ### Example 1: Stop a WSMan trace ```powershell Disable-WSManTrace ``` ## PARAMETERS ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES ## RELATED LINKS [Event Tracing](/windows/desktop/ETW/event-tracing-portal) [Stop-Trace](stop-trace.md) [Enable-WSManTrace](Enable-WSManTrace.md)

#File: reference/7.6/PSDiagnostics/Enable-PSTrace.md

--- external help file: PSDiagnostics-help.xml Locale: en-US Module Name: PSDiagnostics ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/psdiagnostics/enable-pstrace?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Enable-PSTrace --- # Enable-PSTrace ## SYNOPSIS Enables the Microsoft-Windows-PowerShell event provider logs. ## SYNTAX ``` Enable-PSTrace [-Force] [-AnalyticOnly] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** This cmdlet enables the Operational and Analytic event logs of the Microsoft-Windows-PowerShell event provider. You must run this cmdlet from an elevated PowerShell session. ## EXAMPLES ### Example 1: Enable the Analytic event log for PowerShell The following example enables only the Analytic event log of the Microsoft-Windows-PowerShell provider. ```powershell Enable-PSTrace -AnalyticOnly ``` ## PARAMETERS ### -AnalyticOnly When this parameter is used, the cmdlet enables the Analytic event log of the Microsoft-Windows-PowerShell provider. The Operational event log is not changed. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force Used to force the change without prompting. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES This cmdlet uses the `Get-LogProperties` and `Set-LogProperties` cmdlets. You must run this cmdlet from an elevated PowerShell session. ## RELATED LINKS [Get-LogProperties](Get-LogProperties.md) [Set-LogProperties](Set-LogProperties.md) [Disable-PSTrace](Disable-PSTrace.md)

#File: reference/7.6/PSDiagnostics/Enable-PSWSManCombinedTrace.md

--- external help file: PSDiagnostics-help.xml Locale: en-US Module Name: PSDiagnostics ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/psdiagnostics/enable-pswsmancombinedtrace?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Enable-PSWSManCombinedTrace --- # Enable-PSWSManCombinedTrace ## SYNOPSIS Start a logging session with the WSMan and PowerShell providers enabled. ## SYNTAX ``` Enable-PSWSManCombinedTrace [-DoNotOverwriteExistingTrace] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** This cmdlet starts a logging session with the following PowerShell providers enabled: - Microsoft-Windows-PowerShell - Microsoft-Windows-WinRM The session is named 'PSTrace'. This cmdlet uses the `Start-Trace` cmdlet. You must run this cmdlet from an elevated PowerShell session. ## EXAMPLES ### Example 1: Start a combined logging session ```powershell Enable-PSWSManCombinedTrace ``` ## PARAMETERS ### -DoNotOverwriteExistingTrace By default, the events are written to `$PSHOME\Traces\PSTrace.etl`. When this parameter is used, the cmdlet creates a unique filename: `$PSHOME\Traces\PSTrace_{guid}.etl` ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES ## RELATED LINKS [Event Tracing](/windows/desktop/ETW/event-tracing-portal) [Start-Trace](start-trace.md) [Disable-PSWSManCombinedTrace](Disable-PSWSManCombinedTrace.md)

#File: reference/7.6/PSDiagnostics/Enable-WSManTrace.md

--- external help file: PSDiagnostics-help.xml Locale: en-US Module Name: PSDiagnostics ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/psdiagnostics/enable-wsmantrace?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Enable-WSManTrace --- # Enable-WSManTrace ## SYNOPSIS Start a logging session with the WSMan providers enabled. ## SYNTAX ``` Enable-WSManTrace [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** This cmdlet starts a logging session with the WSMan providers enabled. The following event providers are enabled: - `Event Forwarding` - `IpmiDrv` - `IPMIPrv` - `WinRM` - `WinrsCmd` - `WinrsExe` - `WinrsMgr` - `WSManProvHost` The session is named `wsmlog`. This cmdlet uses the `Start-Trace` cmdlet. You must run this cmdlet from an elevated PowerShell session. ## EXAMPLES ### Example 1: Start a WSMan logging session ```powershell Enable-WSManTrace ``` ## PARAMETERS ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES ## RELATED LINKS [Event Tracing](/windows/desktop/ETW/event-tracing-portal) [Start-Trace](start-trace.md) [Disable-WSManTrace](Disable-WSManTrace.md)

#File: reference/7.6/PSDiagnostics/Get-LogProperties.md

--- external help file: PSDiagnostics-help.xml Locale: en-US Module Name: PSDiagnostics ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/psdiagnostics/get-logproperties?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-LogProperties --- # Get-LogProperties ## SYNOPSIS Retrieves the properties of a Windows event log. ## SYNTAX ``` Get-LogProperties [-Name] <Object> [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** This cmdlet gets the configuration settings of a Windows event log. This cmdlet is used by the `Enable-PSTrace` and `Disable-PSTrace` cmdlets. ## EXAMPLES ### Example 1: Get the configuration settings of the Windows PowerShell event log ```powershell Get-LogProperties 'Windows PowerShell' ``` ```Output Name : Windows PowerShell Enabled : True Type : Admin Retention : False AutoBackup : False MaxLogSize : 15728640 ``` ## PARAMETERS ### -Name The name of the event provider. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String You can pipe a string containing the name of a log provider to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.Diagnostics.LogDetails This cmdlet returns a **LogDetails** object. The **PSDiagnostics** module adds the **LogDetails** class to the `Microsoft.PowerShell.Diagnostics` namespace. ## NOTES ## RELATED LINKS [Set-LogProperties](Set-LogProperties.md) [Enable-PSTrace](Enable-PSTrace.md) [Disable-PSTrace](Disable-PSTrace.md)

#File: reference/7.6/PSDiagnostics/PSDiagnostics.md

--- Download Help Link: https://aka.ms/powershell75-help Help Version: 7.6.0.0 Locale: en-US Module Guid: c61d6278-02a3-4618-ae37-a524d40a7f44 Module Name: PSDiagnostics ms.date: 11/27/2018 schema: 2.0.0 title: PSDiagnostics Module --- # PSDiagnostics Module ## Description The PowerShell Diagnostics Module contains a set of cmdlets that enables the use of ETW tracing in PowerShell on Windows. This module is only available on the Windows platform. ## PSDiagnostics Cmdlets ### [Disable-PSTrace](Disable-PSTrace.md) Disables the Microsoft-Windows-PowerShell event provider logs. ### [Disable-PSWSManCombinedTrace](Disable-PSWSManCombinedTrace.md) Stop the logging session started by Enable-PSWSManCombinedTrace. ### [Disable-WSManTrace](Disable-WSManTrace.md) Stop the WSMan logging session started by Enable-WSManTrace. ### [Enable-PSTrace](Enable-PSTrace.md) Enables the Microsoft-Windows-PowerShell event provider logs. ### [Enable-PSWSManCombinedTrace](Enable-PSWSManCombinedTrace.md) Start a logging session with the WSMan and PowerShell providers enabled. ### [Enable-WSManTrace](Enable-WSManTrace.md) Start a logging session with the WSMan providers enabled. ### [Get-LogProperties](Get-LogProperties.md) Retrieves the properties of a Windows event log. ### [Set-LogProperties](Set-LogProperties.md) Changes the properties of a Windows event log. ### [Start-Trace](Start-Trace.md) Start an Event Trace logging session. ### [Stop-Trace](Stop-Trace.md) Stop an Event Trace logging session.

#File: reference/7.6/PSDiagnostics/Set-LogProperties.md

--- external help file: PSDiagnostics-help.xml Locale: en-US Module Name: PSDiagnostics ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/psdiagnostics/set-logproperties?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-LogProperties --- # Set-LogProperties ## SYNOPSIS Changes the properties of a Windows event log. ## SYNTAX ``` Set-LogProperties [-LogDetails] <LogDetails> [-Force] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** This cmdlet changes the configuration settings of a Windows event log. This cmdlet is used by the `Enable-PSTrace` and `Disable-PSTrace` cmdlets. You must run this cmdlet from an elevated PowerShell session. ## EXAMPLES ### Example 1: Change the retention setting of the Windows PowerShell event log ```powershell $logDetails = Get-LogProperties 'Windows PowerShell' $logDetails.Retention = $true Set-LogProperties -LogDetails $logDetails Get-LogProperties 'Windows PowerShell' ``` ```Output Name : Windows PowerShell Enabled : True Type : Admin Retention : True AutoBackup : False MaxLogSize : 15728640 ``` ## PARAMETERS ### -Force Used to force the change without prompting. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LogDetails The updated configuration settings to be assigned to the event log. ```yaml Type: Microsoft.PowerShell.Diagnostics.LogDetails Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### Microsoft.PowerShell.Diagnostics.LogDetails You can pipe a fully configured **LogDetails** object to this cmdlet. Therefore, to change one setting, you should use `Get-LogProperties` to retrieve the current configuration. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES You must run this cmdlet from an elevated PowerShell session. ## RELATED LINKS [Get-LogProperties](Get-LogProperties.md) [Enable-PSTrace](Enable-PSTrace.md) [Disable-PSTrace](Disable-PSTrace.md)

#File: reference/7.6/PSDiagnostics/Start-Trace.md

--- external help file: PSDiagnostics-help.xml Locale: en-US Module Name: PSDiagnostics ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/psdiagnostics/start-trace?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Start-Trace --- # Start-Trace ## SYNOPSIS Start an Event Trace logging session. ## SYNTAX ``` Start-Trace [-SessionName] <String> [[-OutputFilePath] <String>] [[-ProviderFilePath] <String>] [-ETS] [-Format <String>] [-MinBuffers <Int32>] [-MaxBuffers <Int32>] [-BufferSizeInKB <Int32>] [-MaxLogFileSizeInMB <Int32>] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** This cmdlet starts a Windows Event Trace logging session. This cmdlet is used by the following cmdlets: - `Enable-PSWSManCombinedTrace` - `Enable-WSManTrace` You must run this cmdlet from an elevated PowerShell session. ## EXAMPLES ### Example 1: Start a WSMan Trace logging session ```powershell $parameters = @{ SessionName = 'wsmlog' ETS = $true OutputFilePath = "$Env:windir\system32\wsmtraces.log" Format = 'bincirc' MinBuffers = 16 MaxBuffers = 256 BufferSizeInKb = 64 MaxLogFileSizeInMB = 256 ProviderFilePath = "$Env:windir\system32\wsmtraceproviders.txt" } Start-Trace @parameters ``` ## PARAMETERS ### -BufferSizeInKB Event Trace Session buffer size in kilobytes (KB). ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 0 Accept pipeline input: False Accept wildcard characters: False ``` ### -ETS Send commands to Event Trace Sessions directly without saving or scheduling. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Format Specifies the log format for the data collector. For SQL database format, you must use the **OutputFilePath** option in the command line with the `dsn!log` value. The default is binary (bin). The possible values are: - bin - binary - bincirc - binary with circular logging - csv - Comma-separated values - tsv - Tab-separated values - sql - SQL database ```yaml Type: System.Object Parameter Sets: (All) Aliases: Accepted values: bin, bincirc, csv, tsv, sql Required: False Position: Named Default value: bin Accept pipeline input: False Accept wildcard characters: False ``` ### -MaxBuffers Sets the maximum number of Event Trace Session buffers. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 256 Accept pipeline input: False Accept wildcard characters: False ``` ### -MaxLogFileSizeInMB Sets the maximum log file size in megabytes (MB) or number of records for SQL logs. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 0 (no limit) Accept pipeline input: False Accept wildcard characters: False ``` ### -MinBuffers Sets the minimum number of Event Trace Session buffers. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 0 Accept pipeline input: False Accept wildcard characters: False ``` ### -OutputFilePath Path of the output log file or the DSN and log set name in a SQL database. The default path is `$Env:SystemDrive\PerfLogs\Admin`. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 1 Default value: $Env:SystemDrive\PerfLogs\Admin Accept pipeline input: False Accept wildcard characters: False ``` ### -ProviderFilePath File listing multiple Event Trace providers to enable. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: 2 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SessionName The name of the Event Trace session. To stop a trace session you must know the session name. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES ## RELATED LINKS [Event Tracing](/windows/desktop/ETW/event-tracing-portal) [Stop-Trace](stop-trace.md) [Disable-PSWSManCombinedTrace](Disable-PSWSManCombinedTrace.md) [Disable-WSManTrace](Disable-WSManTrace.md) [Enable-PSWSManCombinedTrace](Enable-PSWSManCombinedTrace.md) [Enable-WSManTrace](Enable-WSManTrace.md)

#File: reference/7.6/PSDiagnostics/Stop-Trace.md

--- external help file: PSDiagnostics-help.xml Locale: en-US Module Name: PSDiagnostics ms.date: 12/12/2022 online version: https://learn.microsoft.com/powershell/module/psdiagnostics/stop-trace?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Stop-Trace --- # Stop-Trace ## SYNOPSIS Stop an Event Trace logging session. ## SYNTAX ``` Stop-Trace [-SessionName] <Object> [-ETS] [<CommonParameters>] ``` ## DESCRIPTION > **This cmdlet is only available on the Windows platform.** This cmdlet stops a Windows Event Trace logging session. This cmdlet is used by the following cmdlets: - `Disable-PSWSManCombinedTrace` - `Disable-WSManTrace` You must run this cmdlet from an elevated PowerShell session. ## EXAMPLES ### Example 1: Stop a WSMan Trace logging session ```powershell Stop-Trace -SessionName 'wsmlog' ``` ## PARAMETERS ### -ETS Send commands to Event Trace Sessions directly without saving or scheduling. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -SessionName The name of the Event Trace session to be stopped. ```yaml Type: System.Object Parameter Sets: (All) Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES ## RELATED LINKS [Event Tracing](/windows/desktop/ETW/event-tracing-portal) [Start-Trace](start-trace.md) [Disable-PSWSManCombinedTrace](Disable-PSWSManCombinedTrace.md) [Disable-WSManTrace](Disable-WSManTrace.md) [Enable-PSWSManCombinedTrace](Enable-PSWSManCombinedTrace.md) [Enable-WSManTrace](Enable-WSManTrace.md)

#File: reference/7.6/PSReadLine/Get-PSReadLineKeyHandler.md

--- external help file: Microsoft.PowerShell.PSReadLine2.dll-Help.xml Locale: en-US Module Name: PSReadLine ms.date: 12/13/2022 online version: https://learn.microsoft.com/powershell/module/psreadline/get-psreadlinekeyhandler?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-PSReadLineKeyHandler --- # Get-PSReadLineKeyHandler ## SYNOPSIS Gets the key bindings for the PSReadLine module. ## SYNTAX ### FullListing (default) ``` Get-PSReadLineKeyHandler [-Bound] [-Unbound] [<CommonParameters>] ``` ### SpecificBindings ``` Get-PSReadLineKeyHandler [-Chord] <String[]> [<CommonParameters>] ``` ## DESCRIPTION If no parameter is specified, returns the currently bound key functions for the PSReadLine module. If **Chord** parameter is specified, the cmdlet returns the specific bound keys. ## EXAMPLES ### Example 1: Get all key mappings This command returns all key mappings, bound and unbound. ```powershell Get-PSReadLineKeyHandler -Bound -Unbound ``` ```Output Key Function Description --- -------- ----------- Enter AcceptLine Accept the input or move to the next line if input is missing a closing token. Shift+Enter AddLine Move the cursor to the next line without attempting to execute the input Escape RevertLine Equivalent to undo all edits (clears the line except lines imported from history) LeftArrow BackwardChar Move the cursor back one character RightArrow ForwardChar Move the cursor forward one character Ctrl+LeftArrow BackwardWord Move the cursor to the beginning of the current or previous word Ctrl+RightArrow NextWord Move the cursor forward to the start of the next word Shift+LeftArrow SelectBackwardChar Adjust the current selection to include the previous character Shift+RightArrow SelectForwardChar Adjust the current selection to include the next character Ctrl+Shift+LeftArrow SelectBackwardWord Adjust the current selection to include the previous word Ctrl+Shift+RightArrow SelectNextWord Adjust the current selection to include the next word UpArrow PreviousHistory Replace the input with the previous item in the history DownArrow NextHistory Replace the input with the next item in the history Home BeginningOfLine Move the cursor to the beginning of the line End EndOfLine Move the cursor to the end of the line Shift+Home SelectBackwardsLine Adjust the current selection to include from the cursor to the end of the line Shift+End SelectLine Adjust the current selection to include from the cursor to the start of the line Delete DeleteChar Delete the character under the cursor Backspace BackwardDeleteChar Delete the character before the cursor Ctrl+Spacebar MenuComplete Complete the input if there is a single completion, otherwise complete the input by selecting from a menu o... Tab TabCompleteNext Complete the input using the next completion Shift+Tab TabCompletePrevious Complete the input using the previous completion Ctrl+a SelectAll Select the entire line. Moves the cursor to the end of the line Ctrl+c CopyOrCancelLine Either copy selected text to the clipboard, or if no text is selected, cancel editing the line with Cancel... Ctrl+C Copy Copy selected region to the system clipboard. If no region is selected, copy the whole line Ctrl+l ClearScreen Clear the screen and redraw the current line at the top of the screen Ctrl+r ReverseSearchHistory Search history backwards interactively ... ``` ### Example 2: Get bound keys This command returns only bound keys and key combinations. ```powershell Get-PSReadLineKeyHandler ``` ```Output Key Function Description --- -------- ----------- Enter AcceptLine Accept the input or move to the next line if input is missing a closing token. Shift+Enter AddLine Move the cursor to the next line without attempting to execute the input Escape RevertLine Equivalent to undo all edits (clears the line except lines imported from history) LeftArrow BackwardChar Move the cursor back one character RightArrow ForwardChar Move the cursor forward one character Ctrl+LeftArrow BackwardWord Move the cursor to the beginning of the current or previous word Ctrl+RightArrow NextWord Move the cursor forward to the start of the next word Shift+LeftArrow SelectBackwardChar Adjust the current selection to include the previous character Shift+RightArrow SelectForwardChar Adjust the current selection to include the next character Ctrl+Shift+LeftArrow SelectBackwardWord Adjust the current selection to include the previous word Ctrl+Shift+RightArrow SelectNextWord Adjust the current selection to include the next word UpArrow PreviousHistory Replace the input with the previous item in the history DownArrow NextHistory Replace the input with the next item in the history Home BeginningOfLine Move the cursor to the beginning of the line End EndOfLine Move the cursor to the end of the line Shift+Home SelectBackwardsLine Adjust the current selection to include from the cursor to the end of the line Shift+End SelectLine Adjust the current selection to include from the cursor to the start of the line Delete DeleteChar Delete the character under the cursor Backspace BackwardDeleteChar Delete the character before the cursor Ctrl+Spacebar MenuComplete Complete the input if there is a single completion, otherwise complete the input by selecting from a menu o... Tab TabCompleteNext Complete the input using the next completion ... ``` ### Example 3: Get specific key bindings This command returns only the bindings for the specified keys. ```powershell Get-PSReadLineKeyHandler -Chord Enter, Shift+Enter ``` ```Output Key Function Description --- -------- ----------- Enter AcceptLine Accept the input or move to the next line if input is missing a closing token. Shift+Enter AddLine Move the cursor to the next line without attempting to execute the input ... ``` ## PARAMETERS ### -Bound Indicates that this cmdlet returns functions that are bound. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: FullListing Aliases: Required: False Position: Named Default value: True Accept pipeline input: False Accept wildcard characters: False ``` ### -Chord Return only functions bound to specific keys or sequences. ```yaml Type: System.String[] Parameter Sets: SpecificBindings Aliases: Key Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Unbound Indicates that this cmdlet returns functions that are unbound. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: FullListing Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.KeyHandler This cmdlet returns a **KeyHandler** object. ## NOTES ## RELATED LINKS [Remove-PSReadLineKeyHandler](Remove-PSReadLineKeyHandler.md) [Get-PSReadLineOption](Get-PSReadLineOption.md) [Set-PSReadLineOption](Set-PSReadLineOption.md) [Set-PSReadLineKeyHandler](Set-PSReadLineKeyHandler.md)

#File: reference/7.6/PSReadLine/Get-PSReadLineOption.md

--- external help file: Microsoft.PowerShell.PSReadLine2.dll-Help.xml Locale: en-US Module Name: PSReadLine ms.date: 10/11/2023 online version: https://learn.microsoft.com/powershell/module/psreadline/get-psreadlineoption?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Get-PSReadLineOption --- # Get-PSReadLineOption ## SYNOPSIS Gets values for the options that can be configured. ## SYNTAX ``` Get-PSReadLineOption [<CommonParameters>] ``` ## DESCRIPTION The `Get-PSReadLineOption` cmdlet returns the current state of the settings that can be configured using the `Set-PSReadLineOption` cmdlet. You can use the returned object to change **PSReadLine** options. This provides a slightly simpler way to set syntax coloring options for multiple kinds of tokens. ## EXAMPLES ### Example 1: Get options and their values ```powershell Get-PSReadLineOption ``` ```Output EditMode : Windows AddToHistoryHandler : System.Func`2[System.String,System.Object] HistoryNoDuplicates : True HistorySavePath : C:\Users\user1\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt HistorySaveStyle : SaveIncrementally HistorySearchCaseSensitive : False HistorySearchCursorMovesToEnd : False MaximumHistoryCount : 4096 ContinuationPrompt : >> ExtraPromptLineCount : 0 PromptText : {> } BellStyle : Audible DingDuration : 50 DingTone : 1221 CommandsToValidateScriptBlockArguments : {ForEach-Object, %, Invoke-Command, icm…} CommandValidationHandler : CompletionQueryItems : 100 MaximumKillRingCount : 10 ShowToolTips : True ViModeIndicator : None WordDelimiters : ;:,.[]{}()/\|!?^&*-=+'"–—― AnsiEscapeTimeout : 100 PredictionSource : HistoryAndPlugin PredictionViewStyle : InlineView TerminateOrphanedConsoleApps : False CommandColor : "`e[93m" CommentColor : "`e[32m" ContinuationPromptColor : "`e[37m" DefaultTokenColor : "`e[37m" EmphasisColor : "`e[96m" ErrorColor : "`e[91m" InlinePredictionColor : "`e[97;2;3m" KeywordColor : "`e[92m" ListPredictionColor : "`e[33m" ListPredictionSelectedColor : "`e[48;5;238m" ListPredictionTooltipColor : "`e[97;2;3m" MemberColor : "`e[37m" NumberColor : "`e[97m" OperatorColor : "`e[90m" ParameterColor : "`e[90m" SelectionColor : "`e[30;47m" StringColor : "`e[36m" TypeColor : "`e[37m" VariableColor : "`e[92m" ``` This command returns the list of available PSReadLine options and their current values. ## PARAMETERS ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### Microsoft.PowerShell.PSConsoleReadLineOptions This cmdlet returns an instance of the current options. Changing the property values of this object updates the settings in PSReadLine directly without invoking `Set-PSReadLineOption`. ## NOTES ## RELATED LINKS [Remove-PSReadLineKeyHandler](Remove-PSReadLineKeyHandler.md) [Get-PSReadLineKeyHandler](Get-PSReadLineKeyHandler.md) [Set-PSReadLineOption](Set-PSReadLineOption.md) [Set-PSReadLineKeyHandler](Set-PSReadLineKeyHandler.md)

#File: reference/7.6/PSReadLine/PSConsoleHostReadLine.md

--- external help file: PSReadLine-help.xml Locale: en-US Module Name: PSReadLine ms.date: 01/09/2025 online version: https://learn.microsoft.com/powershell/module/psreadline/psconsolehostreadline?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: PSConsoleHostReadLine --- # PSConsoleHostReadLine ## SYNOPSIS This function is the main entry point for PSReadLine. ## SYNTAX ``` PSConsoleHostReadLine ``` ## DESCRIPTION `PSConsoleHostReadLine` is the main entry point for the PSReadLine module. The PowerShell console host automatically loads the PSReadLine module and calls this function. Under normal operating conditions, this function isn't intended to be used from the command line. The extension point `PSConsoleHostReadLine` is special to the console host. The host calls any alias, function, or script with this name. PSReadLine defines this function so that it is called from the console host. ## EXAMPLES ### Example 1 This function isn't intended to be used from the command line. ```powershell PSConsoleHostReadLine ``` ## PARAMETERS ## INPUTS ### None ## OUTPUTS ### None ## NOTES The purpose of this article is to document that this function exists and is used by the PSReadLine module. ## RELATED LINKS [about_PSReadLine](./About/about_PSReadLine.md)

#File: reference/7.6/PSReadLine/PSReadLine.md

--- Download Help Link: https://aka.ms/powershell75-help Help Version: 7.6.0.0 Locale: en-US Module Guid: 5714753b-2afd-4492-a5fd-01d9e2cff8b5 Module Name: PSReadLine ms.date: 09/17/2024 schema: 2.0.0 title: PSReadLine --- # PSReadLine Module ## Description The PSReadLine module contains cmdlets that let you customize the command-line editing environment in PowerShell. There have been many updates to PSReadLine since the version that ships in Windows PowerShell 5.1. - v2.3.5 first shipped in PowerShell 7.4.2 and 7.5.0-preview.3 - v2.3.4 first shipped in PowerShell 7.4.0-rc.1 - v2.2.6 first shipped in PowerShell 7.3.0 - v2.1.0 first shipped in PowerShell 7.2.5 - v2.0.4 first shipped in PowerShell 7.0.11 - v2.0.0 ships in Windows PowerShell 5.1 For more information about version differences, see [about_PSReadLine_Release_Notes](about/about_PSReadLine_Release_Notes.md). These articles document version 2.3.5 of PSReadLine. > [!NOTE] > Beginning with PowerShell 7.0, PowerShell skips auto-loading PSReadLine on > Windows if a screen reader program is detected. Currently, PSReadLine doesn't > work well with the screen readers. The default rendering and formatting of > PowerShell 7.0 on Windows works properly. You can manually load the module if > necessary. ## PSReadLine Cmdlets ### [Get-PSReadLineKeyHandler](Get-PSReadLineKeyHandler.md) Gets the key bindings for the PSReadLine module. ### [Get-PSReadLineOption](Get-PSReadLineOption.md) Gets values for the options that can be configured. ### [PSConsoleHostReadLine](PSConsoleHostReadLine.md) This function is the main entry point for PSReadLine. ### [Remove-PSReadLineKeyHandler](Remove-PSReadLineKeyHandler.md) Removes a key binding. ### [Set-PSReadLineKeyHandler](Set-PSReadLineKeyHandler.md) Binds keys to user-defined or PSReadLine key handler functions. ### [Set-PSReadLineOption](Set-PSReadLineOption.md) Customizes the behavior of command line editing in **PSReadLine**.

#File: reference/7.6/PSReadLine/Remove-PSReadLineKeyHandler.md

--- external help file: Microsoft.PowerShell.PSReadLine2.dll-Help.xml Locale: en-US Module Name: PSReadLine ms.date: 12/13/2022 online version: https://learn.microsoft.com/powershell/module/psreadline/remove-psreadlinekeyhandler?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Remove-PSReadLineKeyHandler --- # Remove-PSReadLineKeyHandler ## SYNOPSIS Removes a key binding. ## SYNTAX ``` Remove-PSReadLineKeyHandler [-Chord] <String[]> [-ViMode <ViMode>] [<CommonParameters>] ``` ## DESCRIPTION The `Remove-PSReadLineKeyHandler` cmdlet removes a specified key binding. ## EXAMPLES ### Example 1: Remove a binding ```powershell Remove-PSReadLineKeyHandler -Chord Ctrl+B ``` This command removes the binding from the key combination, or chord, `Ctrl+B`. The `Ctrl+B` chord is created in the `Set-PSReadLineKeyHandler` article. ## PARAMETERS ### -Chord Specifies an array of keys or sequences of keys to be removed. A single binding is specified by using a single string. If the binding is a sequence of keys, separate the keys by a comma, as in the following example: `Ctrl+x,Ctrl+l` This parameter accepts an array of strings. Each string is a separate binding, not a sequence of keys for a single binding. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Key Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ViMode Specify which vi mode the binding applies to. Possible values are: Insert, Command. ```yaml Type: Microsoft.PowerShell.ViMode Parameter Sets: (All) Aliases: Accepted values: Insert, Command Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES ## RELATED LINKS [Get-PSReadLineKeyHandler](Get-PSReadLineKeyHandler.md) [Get-PSReadLineOption](Get-PSReadLineOption.md) [Set-PSReadLineOption](Set-PSReadLineOption.md) [Set-PSReadLineKeyHandler](Set-PSReadLineKeyHandler.md)

#File: reference/7.6/PSReadLine/Set-PSReadLineKeyHandler.md

--- external help file: Microsoft.PowerShell.PSReadLine2.dll-Help.xml Locale: en-US Module Name: PSReadLine ms.date: 10/02/2023 online version: https://learn.microsoft.com/powershell/module/psreadline/set-psreadlinekeyhandler?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-PSReadLineKeyHandler --- # Set-PSReadLineKeyHandler ## SYNOPSIS Binds keys to user-defined or PSReadLine key handler functions. ## SYNTAX ### ScriptBlock ``` Set-PSReadLineKeyHandler [-ScriptBlock] <ScriptBlock> [-BriefDescription <String>] [-Description <String>] [-Chord] <String[]> [-ViMode <ViMode>] [<CommonParameters>] ``` ### Function ``` Set-PSReadLineKeyHandler [-Chord] <String[]> [-ViMode <ViMode>] [-Function] <String> [<CommonParameters>] ``` ## DESCRIPTION The `Set-PSReadLineKeyHandler` cmdlet customizes the result when a key or sequence of keys is pressed. With user-defined key bindings, you can do almost anything that's possible from within a PowerShell script. ## EXAMPLES ### Example 1: Bind the arrow key to a function This command binds the up arrow key to the **HistorySearchBackward** function. This function searches command history for command lines that start with the current contents of the command line. ```powershell Set-PSReadLineKeyHandler -Chord UpArrow -Function HistorySearchBackward ``` ### Example 2: Bind a key to a script block This example shows how a single key can be used to run a command. The command binds the key `Ctrl+b` to a script block that clears the line, inserts the word "build", and then accepts the line. ```powershell Set-PSReadLineKeyHandler -Chord Ctrl+b -ScriptBlock { [Microsoft.PowerShell.PSConsoleReadLine]::RevertLine() [Microsoft.PowerShell.PSConsoleReadLine]::Insert('build') [Microsoft.PowerShell.PSConsoleReadLine]::AcceptLine() } ``` ## PARAMETERS ### -BriefDescription A brief description of the key binding. This description is displayed by the `Get-PSReadLineKeyHandler` cmdlet. ```yaml Type: System.String Parameter Sets: ScriptBlock Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Chord The key or sequence of keys to be bound to a function or script block. Use a single string to specify a single binding. If the binding is a sequence of keys, separate the keys by a comma. For example: `Ctrl+x,Ctrl+l` Letter key references are defined using lowercase letters. If you want to define a chord that uses an uppercase letter, the chord must include the **Shift** key. For example, `Ctrl+Shift+x` and `Ctrl+x` create different bindings. This parameter accepts an array of strings. Each string is a separate binding, not a sequence of keys for a single binding. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Key Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Description Specifies a more detailed description of the key binding that's visible in the output of the `Get-PSReadLineKeyHandler` cmdlet. ```yaml Type: System.String Parameter Sets: ScriptBlock Aliases: LongDescription Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Function Specifies the name of an existing key handler provided by PSReadLine. This parameter lets you rebind existing key bindings, or bind a handler that's currently unbound. ```yaml Type: System.String Parameter Sets: Function Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ScriptBlock Specifies a script block value to run when the chord is entered. PSReadLine passes one or two parameters to this script block. The first parameter is a **ConsoleKeyInfo** object representing the key pressed. The second argument can be any object depending on the context. ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: ScriptBlock Aliases: Required: True Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ViMode Specify which vi mode the binding applies to. Valid values are: - `Insert` - `Command` ```yaml Type: Microsoft.PowerShell.ViMode Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES ## RELATED LINKS [Get-PSReadLineKeyHandler](Get-PSReadLineKeyHandler.md) [Remove-PSReadLineKeyHandler](Remove-PSReadLineKeyHandler.md) [Get-PSReadLineOption](Get-PSReadLineOption.md) [Set-PSReadLineOption](Set-PSReadLineOption.md)

#File: reference/7.6/PSReadLine/Set-PSReadLineOption.md

--- external help file: Microsoft.PowerShell.PSReadLine2.dll-Help.xml Locale: en-US Module Name: PSReadLine ms.date: 02/24/2025 online version: https://learn.microsoft.com/powershell/module/psreadline/set-psreadlineoption?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Set-PSReadLineOption --- # Set-PSReadLineOption ## SYNOPSIS Customizes the behavior of command line editing in **PSReadLine**. ## SYNTAX ``` Set-PSReadLineOption [-EditMode <EditMode>] [-ContinuationPrompt <string>] [-HistoryNoDuplicates] [-AddToHistoryHandler <Func[string,Object]>] [-CommandValidationHandler <Action[CommandAst]>] [-HistorySearchCursorMovesToEnd] [-MaximumHistoryCount <int>] [-MaximumKillRingCount <int>] [-ShowToolTips] [-ExtraPromptLineCount <int>] [-DingTone <int>] [-DingDuration <int>] [-BellStyle <BellStyle>] [-CompletionQueryItems <int>] [-WordDelimiters <string>] [-HistorySearchCaseSensitive] [-HistorySaveStyle <HistorySaveStyle>] [-HistorySavePath <string>] [-AnsiEscapeTimeout <int>] [-PromptText <string[]>] [-ViModeIndicator <ViModeStyle>] [-ViModeChangeHandler <scriptblock>] [-PredictionSource <PredictionSource>] [-PredictionViewStyle <PredictionViewStyle>] [-Colors <hashtable>] [-TerminateOrphanedConsoleApps] [<CommonParameters>] ``` ## DESCRIPTION The `Set-PSReadLineOption` cmdlet customizes the behavior of the **PSReadLine** module when you're editing the command line. To view the **PSReadLine** settings, use `Get-PSReadLineOption`. The options set by this command only apply to the current session. To persist any options, add them to a profile script. For more information, see [about_Profiles](../Microsoft.PowerShell.Core/About/about_Profiles.md) and [Customizing your shell environment](/powershell/scripting/learn/shell/creating-profiles). ## EXAMPLES ### Example 1: Set foreground and background colors This example sets **PSReadLine** to display the **Comment** token with green foreground text on a gray background. In the escape sequence used in the example, **32** represents the foreground color and **47** represents the background color. ```powershell Set-PSReadLineOption -Colors @{ "Comment"="`e[32;47m" } ``` You can choose to set only a foreground text color. For example, a bright green foreground text color for the **Comment** token: ``"Comment"="`e[92m"``. ### Example 2: Set bell style In this example, **PSReadLine** will respond to errors or conditions that require user attention. The **BellStyle** is set to emit an audible beep at 1221 Hz for 60 ms. ```powershell Set-PSReadLineOption -BellStyle Audible -DingTone 1221 -DingDuration 60 ``` > [!NOTE] > This feature may not work in all hosts on platforms. ### Example 3: Set multiple options `Set-PSReadLineOption` can set multiple options with a hash table. ```powershell $PSReadLineOptions = @{ EditMode = "Emacs" HistoryNoDuplicates = $true HistorySearchCursorMovesToEnd = $true Colors = @{ "Command" = "#8181f7" } } Set-PSReadLineOption @PSReadLineOptions ``` The `$PSReadLineOptions` hash table sets the keys and values. `Set-PSReadLineOption` uses the keys and values with `@PSReadLineOptions` to update the **PSReadLine** options. You can view the keys and values entering the hash table name, `$PSReadLineOptions` on the PowerShell command line. ### Example 4: Set multiple color options This example shows how to set more than one color value in a single command. ```powershell Set-PSReadLineOption -Colors @{ Command = 'Magenta' Number = 'DarkGray' Member = 'DarkGray' Operator = 'DarkGray' Type = 'DarkGray' Variable = 'DarkGreen' Parameter = 'DarkGreen' ContinuationPrompt = 'DarkGray' Default = 'DarkGray' } ``` ### Example 5: Set color values for multiple types This example shows three different methods for how to set the color of tokens displayed in **PSReadLine**. ```powershell Set-PSReadLineOption -Colors @{ # Use a ConsoleColor enum "Error" = [ConsoleColor]::DarkRed # 24 bit color escape sequence "String" = "$([char]0x1b)[38;5;100m" # RGB value "Command" = "#8181f7" } ``` ### Example 6: Use ViModeChangeHandler to display Vi mode changes This example emits a cursor change VT escape in response to a **Vi** mode change. ```powershell function OnViModeChange { if ($args[0] -eq 'Command') { # Set the cursor to a blinking block. Write-Host -NoNewline "`e[1 q" } else { # Set the cursor to a blinking line. Write-Host -NoNewline "`e[5 q" } } Set-PSReadLineOption -ViModeIndicator Script -ViModeChangeHandler $Function:OnViModeChange ``` The **OnViModeChange** function sets the cursor options for the **Vi** modes: insert and command. **ViModeChangeHandler** uses the `Function:` provider to reference **OnViModeChange** as a script block object. For more information, see [about_Providers](/powershell/module/microsoft.powershell.core/about/about_providers). ### Example 7: Use HistoryHandler to filter commands added to history The following example shows how to use the `AddToHistoryHandler` to prevent saving any git commands to history. ```powershell $ScriptBlock = { param ([string]$Line) if ($Line -match "^git") { return $false } else { return $true } } Set-PSReadLineOption -AddToHistoryHandler $ScriptBlock ``` The scriptblock returns `$false` if the command started with `git`. This has the same effect as returning the `SkipAdding` **AddToHistory** enum. If the command doesn't start with `git`, the handler returns `$true` and PSReadLine saves the command in history. ### Example 8: Use CommandValidationHandler to validate a command before its executed This example shows how to use the **CommandValidationHandler** parameter to run a validate a command before it's executed. The example specifically checks for the command `git` with the sub command `cmt` and replaces that with the full name `commit`. This way you can create shorthand aliases for subcommands. ```powershell # Load the namespace so you can use the [CommandAst] object type using namespace System.Management.Automation.Language Set-PSReadLineOption -CommandValidationHandler { param([CommandAst]$CommandAst) switch ($CommandAst.GetCommandName()) { 'git' { $gitCmd = $CommandAst.CommandElements[1].Extent switch ($gitCmd.Text) { 'cmt' { [Microsoft.PowerShell.PSConsoleReadLine]::Replace( $gitCmd.StartOffset, $gitCmd.EndOffset - $gitCmd.StartOffset, 'commit') } } } } } # This checks the validation script when you hit enter Set-PSReadLineKeyHandler -Chord Enter -Function ValidateAndAcceptLine ``` ### Example 9: Using the PromptText parameter When there's a parse error, **PSReadLine** changes a part of the prompt red. The **PromptText** parameter tells **PSReadLine** the part of the prompt string to make red. For example, the following example creates a prompt that contains the current path followed by the greater-than character (`>`) and a space. ```powershell function prompt { "PS $PWD> " }` Set-PSReadLineOption -PromptText '> ' # change the '>' character red Set-PSReadLineOption -PromptText '> ', 'X ' # replace the '>' character with a red 'X' ``` The first string is the portion of your prompt string that you want to make red when there is a parse error. The second string is an alternate string to use for when there is a parse error. ## PARAMETERS ### -AddToHistoryHandler Specifies a **ScriptBlock** that controls how commands get added to **PSReadLine** history. The **ScriptBlock** receives the command line as input. The **ScripBlock** should return a member of the **AddToHistoryOption** enum, the string name of one of those members, or a boolean value. The list below describes the possible values and their effects. - `MemoryAndFile` - Add the command to the history file and the current session. - `MemoryOnly` - Add the command to history for the current session only. - `SkipAdding` - Don't add the command to the history file for current session. - `$false` - Same as if the value was `SkipAdding`. - `$true` - Same as if the value was `MemoryAndFile`. ```yaml Type: System.Func`2[System.String,System.Object] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -AnsiEscapeTimeout This option is specific to Windows when input is redirected, for example, when running under `tmux` or `screen`. With redirected input on Windows, many keys are sent as a sequence of characters starting with the escape character. It's impossible to distinguish between a single escape character followed by more characters and a valid escape sequence. The assumption is that the terminal can send the characters faster than a user types. **PSReadLine** waits for this timeout before concluding that it has received a complete escape sequence. If you see random or unexpected characters when you type, you can adjust this timeout. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 100 Accept pipeline input: False Accept wildcard characters: False ``` ### -BellStyle Specifies how **PSReadLine** responds to various error and ambiguous conditions. The valid values are as follows: - **Audible**: A short beep. - **Visual**: Text flashes briefly. - **None**: No feedback. ```yaml Type: Microsoft.PowerShell.BellStyle Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Audible Accept pipeline input: False Accept wildcard characters: False ``` ### -Colors The **Colors** parameter specifies various colors used by **PSReadLine**. The argument is a hash table where the keys specify the elements and the values specify the color. For more information, see [about_Hash_Tables](/powershell/module/microsoft.powershell.core/about/about_hash_tables). Colors can be either a value from **ConsoleColor**, for example `[ConsoleColor]::Red`, or a valid ANSI escape sequence. Valid escape sequences depend on your terminal. In PowerShell 5.0, an example escape sequence for red text is `$([char]0x1b)[91m`. In PowerShell 6 and newer, the same escape sequence is `` `e[91m``. You can specify other escape sequences including the following types: Two color settings were added to support customization of the `ListView` in PSReadLine 2.2.0: - **ListPredictionColor** - set color for the leading `>` character and the trailing source name, such as `[History]`. By default, it uses `DarkYellow` as the foreground color. - **ListPredictionSelectedColor** - set color for indicating a list item is selected. By default, it uses `DarkBlack` as the background color. - 256 color - 24-bit color - Foreground, background, or both - Inverse, bold For more information about ANSI color codes, see the Wikipedia article [ANSI escape code](https://wikipedia.org/wiki/ANSI_escape_code#Colors_). The valid keys include: - **ContinuationPrompt**: The color of the continuation prompt. - **Emphasis**: The emphasis color. For example, the matching text when searching history. - **Error**: The error color. For example, in the prompt. - **Selection**: The color to highlight the menu selection or selected text. - **Default**: The default token color. - **Comment**: The comment token color. - **Keyword**: The keyword token color. - **String**: The string token color. - **Operator**: The operator token color. - **Variable**: The variable token color. - **Command**: The command token color. - **Parameter**: The parameter token color. - **Type**: The type token color. - **Number**: The number token color. - **Member**: The member name token color. - **InlinePrediction**: The color for the inline view of the predictive suggestion. - **ListPrediction**: The color for the leading `>` character and prediction source name. - **ListPredictionSelected**: The color for the selected prediction in list view. ```yaml Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CommandValidationHandler Specifies a **ScriptBlock** that is called from **ValidateAndAcceptLine**. If an exception is thrown, validation fails and the error is reported. Before throwing an exception, the validation handler can place the cursor at the point of the error to make it easier to fix. A validation handler can also change the command line to correct common typographical errors. **ValidateAndAcceptLine** is used to avoid cluttering your history with commands that can't work. ```yaml Type: System.Action`1[System.Management.Automation.Language.CommandAst] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -CompletionQueryItems Specifies the maximum number of completion items that are shown without prompting. If the number of items to show is greater than this value, **PSReadLine** prompts **yes/no** before displaying the completion items. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 100 Accept pipeline input: False Accept wildcard characters: False ``` ### -ContinuationPrompt Specifies the string displayed at the beginning of the subsequent lines when multi-line input is entered. The default is double greater-than signs (`>>`). An empty string is valid. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: >> Accept pipeline input: False Accept wildcard characters: False ``` ### -DingDuration Specifies the duration of the beep when **BellStyle** is set to **Audible**. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 50ms Accept pipeline input: False Accept wildcard characters: False ``` ### -DingTone Specifies the tone in Hertz (Hz) of the beep when **BellStyle** is set to **Audible**. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 1221 Accept pipeline input: False Accept wildcard characters: False ``` ### -EditMode Specifies the command line editing mode. Using this parameter resets any key bindings set by `Set-PSReadLineKeyHandler`. The valid values are as follows: - **Windows**: Key bindings emulate PowerShell, cmd, and Visual Studio. (default on Windows) - **Emacs**: Key bindings emulate Bash or Emacs. (default on non-Windows platforms) - **Vi**: Key bindings emulate Vi. Use `Get-PSReadLineKeyHandler` to see the key bindings for the currently configured **EditMode**. ```yaml Type: Microsoft.PowerShell.EditMode Parameter Sets: (All) Aliases: Required: False Position: Named Default value: Windows Accept pipeline input: False Accept wildcard characters: False ``` ### -ExtraPromptLineCount Specifies the number of extra lines. If your prompt spans more than one line, specify a value for this parameter. Use this option when you want extra lines to be available when **PSReadLine** displays the prompt after showing some output. For example, **PSReadLine** returns a list of completions. This option is needed less than in previous versions of **PSReadLine**, but is useful when the `InvokePrompt` function is used. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 0 Accept pipeline input: False Accept wildcard characters: False ``` ### -HistoryNoDuplicates This option controls the recall behavior. Duplicate commands are still added to the history file. When this option is set, only the most recent invocation appears when recalling commands. Repeated commands are added to history to preserve ordering during recall. However, you typically don't want to see the command multiple times when recalling or searching the history. By default, the **HistoryNoDuplicates** property of the global **PSConsoleReadLineOptions** object is set to `True`. To change the property value, you must specify the value of the **SwitchParameter** as follows: `-HistoryNoDuplicates:$false`. You can set back to `True` by using just the **SwitchParameter**, `-HistoryNoDuplicates`. Using the following command, you can set the property value directly: `(Get-PSReadLineOption).HistoryNoDuplicates = $false` ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -HistorySavePath Specifies the path to the file where history is saved. Computers running Windows or non-Windows platforms store the file in different locations. The filename is stored in a variable `$($Host.Name)_history.txt`, for example `ConsoleHost_history.txt`. If you don't use this parameter, the default path is as follows: **Windows** - `$Env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine\$($Host.Name)_history.txt` **non-Windows** - `$Env:XDG_DATA_HOME/powershell/PSReadLine/$($Host.Name)_history.txt` - `$HOME/.local/share/powershell/PSReadLine/$($Host.Name)_history.txt` ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: A file named $($Host.Name)_history.txt in $Env:APPDATA\Microsoft\Windows\PowerShell\PSReadLine on Windows and $Env:XDG_DATA_HOME/powershell/PSReadLine or $HOME/.local/share/powershell/PSReadLine on non-Windows platforms Accept pipeline input: False Accept wildcard characters: False ``` ### -HistorySaveStyle Specifies how **PSReadLine** saves history. Valid values are as follows: - `SaveIncrementally`: Save history after each command is executed and share across multiple instances of PowerShell. - `SaveAtExit`: Append history file when PowerShell exits. - `SaveNothing`: Don't use a history file. > [!NOTE] > If you set **HistorySaveStyle** to `SaveNothing` and then set it to `SaveIncrementally` later in > the same session, PSReadLine saves all the commands previously run in the session. ```yaml Type: Microsoft.PowerShell.HistorySaveStyle Parameter Sets: (All) Aliases: Required: False Position: Named Default value: SaveIncrementally Accept pipeline input: False Accept wildcard characters: False ``` ### -HistorySearchCaseSensitive Specifies that history searching is case-sensitive in functions like **ReverseSearchHistory** or **HistorySearchBackward**. By default, the **HistorySearchCaseSensitive** property of the global **PSConsoleReadLineOptions** object is set to `False`. Using this **SwitchParameter** sets the property value to `True`. To change the property value back, you must specify the value of the **SwitchParameter** as follows: `-HistorySearchCaseSensitive:$false`. Using the following command, you can set the property value directly: `(Get-PSReadLineOption).HistorySearchCaseSensitive = $false` ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -HistorySearchCursorMovesToEnd Indicates that the cursor moves to the end of commands that you load from history by using a search. When this parameter is set to `$false`, the cursor remains at the position it was when you pressed the up or down arrows. By default, the **HistorySearchCursorMovesToEnd** property of the global **PSConsoleReadLineOptions** object is set to `False`. Using this **SwitchParameter** set the property value to `True`. To change the property value back, you must specify the value of the **SwitchParameter** as follows: `-HistorySearchCursorMovesToEnd:$false`. Using the following command, you can set the property value directly: `(Get-PSReadLineOption).HistorySearchCursorMovesToEnd = $false` ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumHistoryCount Specifies the maximum number of commands to save in **PSReadLine** history. **PSReadLine** history is separate from PowerShell history. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -MaximumKillRingCount Specifies the maximum number of items stored in the kill ring. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 10 Accept pipeline input: False Accept wildcard characters: False ``` ### -PredictionSource Specifies the source for PSReadLine to get predictive suggestions. Valid values are: - **None** - disable the predictive IntelliSense feature (default). - **History** - enable the predictive IntelliSense feature and use the PSReadLine history as the only source. - **Plugin** - enable the predictive IntelliSense feature and use the plugins (`CommandPrediction`) as the only source. This value was added in PSReadLine 2.2.0 - **HistoryAndPlugin** - enable the predictive IntelliSense feature and use both history and plugin as the sources. This value was added in PSReadLine 2.2.0 ```yaml Type: Microsoft.PowerShell.PredictionSource Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -PredictionViewStyle Sets the style for the display of the predictive text. The default is **InlineView**. - **InlineView** - the style as existing today, similar as in fish shell and zsh. (default) - **ListView** - suggestions are rendered in a drop down list, and users can select using <kbd>UpArrow</kbd> and <kbd>DownArrow</kbd>. This parameter was added in PSReadLine 2.2.0 ```yaml Type: Microsoft.PowerShell.PredictionViewStyle Parameter Sets: (All) Aliases: Required: False Position: Named Default value: InlineView Accept pipeline input: False Accept wildcard characters: False ``` ### -PromptText This parameter sets the value of the **PromptText** property. The default value is `"> "`. **PSReadLine** analyzes your prompt function to determine how to change only the color of part of your prompt. This analysis isn't 100% reliable. Use this option if **PSReadLine** is changing your prompt in unexpected ways. Include any trailing whitespace. The value of this parameter can be a single string or an array of two strings. The first string is the portion of your prompt string that you want to be changed to red when there is a parse error. The second string is an alternate string to use for when there is a parse error. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: > Accept pipeline input: False Accept wildcard characters: False ``` ### -ShowToolTips When displaying possible completions, tooltips are shown in the list of completions. This option is enabled by default. This option wasn't enabled by default in prior versions of **PSReadLine**. To disable, set this option to `$false`. This parameter and option were added in PSReadLine 2.3.4. By default, the **ShowToolTips** property of the global **PSConsoleReadLineOptions** object is set to `True`. Using this **SwitchParameter** sets the property value to `True`. To change the property value, you must specify the value of the **SwitchParameter** as follows: `-ShowToolTips:$false`. Using the following command, you can set the property value directly: `(Get-PSReadLineOption).ShowToolTips = $false` ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: True Accept pipeline input: False Accept wildcard characters: False ``` ### -TerminateOrphanedConsoleApps This parameter sets the **TerminateOrphanedConsoleApps** option to `$true`. On Windows, when you press <kbd>Ctrl</kbd>+<kbd>c</kbd> to terminate a process, each process attached to a console receives a terminate signal, as opposed to just the active shell. Sometimes, when a shell has launched some large tree of child processes, (imagine a build system, for example) some processes may exit, leaving multiple processes concurrently trying to consume console input. When setting the **TerminateOrphanedConsoleApps** option to `$true`, PSReadLine records the list of processes that are currently attached to the console. Afterwards, whenever PSReadLine runs, it will get a new list of processes attached to the console, and terminate those that aren't in the original list. This parameter and option were added in PSReadLine 2.3.4. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ViModeChangeHandler When the **ViModeIndicator** is set to `Script`, the script block provided will be invoked every time the mode changes. The script block is provided one argument of type `ViMode`. This parameter was introduced in PowerShell 7. ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ViModeIndicator This option sets the visual indicator for the current **Vi** mode. Either insert mode or command mode. The valid values are as follows: - **None**: There's no indicator. - **Prompt**: The prompt changes color. - **Cursor**: The cursor changes size. - **Script**: User-specified text is printed. ```yaml Type: Microsoft.PowerShell.ViModeStyle Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -WordDelimiters Specifies the characters that delimit words for functions like **ForwardWord** or **KillWord**. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: ;:,.[]{}()/\|^&*-=+'"--- Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None You can't pipe objects to this cmdlet. ## OUTPUTS ### None This cmdlet returns no output. ## NOTES ## RELATED LINKS [about_PSReadLine](./About/about_PSReadLine.md) [Get-PSReadLineKeyHandler](Get-PSReadLineKeyHandler.md) [Get-PSReadLineOption](Get-PSReadLineOption.md) [Remove-PSReadLineKeyHandler](Remove-PSReadLineKeyHandler.md) [Set-PSReadLineKeyHandler](Set-PSReadLineKeyHandler.md)

#File: reference/7.6/ThreadJob/Start-ThreadJob.md

--- external help file: Microsoft.PowerShell.ThreadJob.dll-Help.xml Locale: en-US Module Name: ThreadJob ms.date: 07/07/2022 online version: https://learn.microsoft.com/powershell/module/threadjob/start-threadjob?view=powershell-7.6&WT.mc_id=ps-gethelp schema: 2.0.0 title: Start-ThreadJob --- # Start-ThreadJob ## SYNOPSIS Creates background jobs similar to the `Start-Job` cmdlet. ## SYNTAX ### ScriptBlock ``` Start-ThreadJob [-ScriptBlock] <ScriptBlock> [-Name <String>] [-InitializationScript <ScriptBlock>] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [-ThrottleLimit <Int32>] [-StreamingHost <PSHost>] [<CommonParameters>] ``` ### FilePath ``` Start-ThreadJob [-FilePath] <String> [-Name <String>] [-InitializationScript <ScriptBlock>] [-InputObject <PSObject>] [-ArgumentList <Object[]>] [-ThrottleLimit <Int32>] [-StreamingHost <PSHost>] [<CommonParameters>] ``` ## DESCRIPTION `Start-ThreadJob` creates background jobs similar to the `Start-Job` cmdlet. The main difference is that the jobs which are created run in separate threads within the local process. By default, the jobs use the current working directory of the caller that started the job. The cmdlet also supports a **ThrottleLimit** parameter to limit the number of jobs running at one time. As more jobs are started, they are queued and wait until the current number of jobs drops below the throttle limit. ## EXAMPLES ### Example 1 - Create background jobs with a thread limit of 2 ```powershell Start-ThreadJob -ScriptBlock { 1..100 | % { sleep 1; "Output $_" } } -ThrottleLimit 2 Start-ThreadJob -ScriptBlock { 1..100 | % { sleep 1; "Output $_" } } Start-ThreadJob -ScriptBlock { 1..100 | % { sleep 1; "Output $_" } } Get-Job ``` ```Output Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 1 Job1 ThreadJob Running True PowerShell 1..100 | % { sleep 1;... 2 Job2 ThreadJob Running True PowerShell 1..100 | % { sleep 1;... 3 Job3 ThreadJob NotStarted False PowerShell 1..100 | % { sleep 1;... ``` ### Example 2 - Compare the performance of Start-Job and Start-ThreadJob This example shows the difference between `Start-Job` and `Start-ThreadJob`. The jobs run the `Start-Sleep` cmdlet for 1 second. Since the jobs run in parallel, the total execution time is about 1 second, plus any time required to create the jobs. ```powershell # start five background jobs each running 1 second Measure-Command {1..5 | % {Start-Job {Start-Sleep 1}} | Wait-Job} | Select-Object TotalSeconds Measure-Command {1..5 | % {Start-ThreadJob {Start-Sleep 1}} | Wait-Job} | Select-Object TotalSeconds ``` ```Output TotalSeconds ------------ 5.7665849 1.5735008 ``` After subtracting 1 second for execution time, you can see that `Start-Job` takes about 4.8 seconds to create five jobs. `Start-ThreadJob` is 8 times faster, taking about 0.6 seconds to create five jobs. The results may vary in your environment but the relative improvement should be the same. ### Example 3 - Create jobs using InputObject In this example, the script block uses the `$input` variable to receive input from the **InputObject** parameter. This can also be done by piping objects to `Start-ThreadJob`. ```powershell $j = Start-ThreadJob -InputObject (Get-Process pwsh) -ScriptBlock { $input | Out-String } $j | Wait-Job | Receive-Job ``` ```Output NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 94 145.80 159.02 18.31 18276 1 pwsh 101 163.30 222.05 29.00 35928 1 pwsh ``` ```powershell $j = Get-Process pwsh | Start-ThreadJob -ScriptBlock { $input | Out-String } $j | Wait-Job | Receive-Job ``` ```Output NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName ------ ----- ----- ------ -- -- ----------- 94 145.80 159.02 18.31 18276 1 pwsh 101 163.30 222.05 29.00 35928 1 pwsh ``` ### Example 4 - Stream job output to parent host Using the **StreamingHost** parameter you can tell a job to direct all host output to a specific host. Without this parameter the output goes to the job data stream collection and doesn't appear in a host console until you receive the output from the job. For this example, the current host is passed to `Start-ThreadJob` using the `$Host` automatic variable. ```powershell PS> Start-ThreadJob -ScriptBlock { Read-Host 'Say hello'; Write-Warning 'Warning output' } -StreamingHost $Host Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 7 Job7 ThreadJob NotStarted False PowerShell Read-Host 'Say hello'; ... PS> Say hello: Hello WARNING: Warning output PS> Receive-Job -Id 7 Hello WARNING: Warning output PS> ``` Notice that the prompt from `Read-Host` is displayed and you are able to type input. Then, the message from `Write-Warning` is displayed. The `Receive-Job` cmdlet returns all the output from the job. ### Example 5 - Download multiple files at the same time The `Invoke-WebRequest` cmdlet can only download one file at a time. The following example uses `Start-ThreadJob` to create multiple thread jobs to download multiple files at the same time. ```powershell $baseUri = 'https://github.com/PowerShell/PowerShell/releases/download' $files = @( @{ Uri = "$baseUri/v7.3.0-preview.5/PowerShell-7.3.0-preview.5-win-x64.msi" OutFile = 'PowerShell-7.3.0-preview.5-win-x64.msi' }, @{ Uri = "$baseUri/v7.3.0-preview.5/PowerShell-7.3.0-preview.5-win-x64.zip" OutFile = 'PowerShell-7.3.0-preview.5-win-x64.zip' }, @{ Uri = "$baseUri/v7.2.5/PowerShell-7.2.5-win-x64.msi" OutFile = 'PowerShell-7.2.5-win-x64.msi' }, @{ Uri = "$baseUri/v7.2.5/PowerShell-7.2.5-win-x64.zip" OutFile = 'PowerShell-7.2.5-win-x64.zip' } ) $jobs = @() foreach ($file in $files) { $jobs += Start-ThreadJob -Name $file.OutFile -ScriptBlock { $params = $Using:file Invoke-WebRequest @params } } Write-Host "Downloads started..." Wait-Job -Job $jobs foreach ($job in $jobs) { Receive-Job -Job $job } ``` ## PARAMETERS ### -ArgumentList Specifies an array of arguments, or parameter values, for the script that is specified by the **FilePath** or **ScriptBlock** parameters. **ArgumentList** must be the last parameter on the command line. All the values that follow the parameter name are interpreted values in the argument list. ```yaml Type: System.Object[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FilePath Specifies a script file to run as a background job. Enter the path and filename of the script. The script must be on the local computer or in a folder that the local computer can access. When you use this parameter, PowerShell converts the contents of the specified script file to a script block and runs the script block as a background job. ```yaml Type: System.String Parameter Sets: FilePath Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InitializationScript Specifies commands that run before the job starts. Enclose the commands in braces (`{}`) to create a script block. Use this parameter to prepare the session in which the job runs. For example, you can use it to add functions and modules to the session. ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -InputObject Specifies the objects used as input to the script block. It also allows for pipeline input. Use the `$input` automatic variable in the script block to access the input objects. ```yaml Type: System.Management.Automation.PSObject Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Name Specifies a friendly name for the new job. You can use the name to identify the job to other job cmdlets, such as the `Stop-Job` cmdlet. The default friendly name is "Job#", where "#" is an ordinal number that is incremented for each job. ```yaml Type: System.String Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ScriptBlock Specifies the commands to run in the background job. Enclose the commands in braces (`{}`) to create a script block. Use the `$input` automatic variable to access the value of the **InputObject** parameter. This parameter is required. ```yaml Type: System.Management.Automation.ScriptBlock Parameter Sets: ScriptBlock Aliases: Required: True Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -StreamingHost This parameter provides a thread safe way to allow `Write-Host` output to go directly to the passed in **PSHost** object. Without it, `Write-Host` output goes to the job information data stream collection and doesn't appear in a host console until after the jobs finish running. ```yaml Type: System.Management.Automation.Host.PSHost Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ThrottleLimit This parameter limits the number of jobs running at one time. As jobs are started, they are queued and wait until a thread is available in the thread pool to run the job. The default limit is 5 threads. The thread pool size is global to the PowerShell session. Specifying a **ThrottleLimit** in one call sets the limit for subsequent calls in the same session. ```yaml Type: System.Int32 Parameter Sets: (All) Aliases: Required: False Position: Named Default value: 5 Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.Management.Automation.PSObject ## OUTPUTS ### ThreadJob.ThreadJob ## NOTES ## RELATED LINKS [Start-Job](../Microsoft.PowerShell.Core/Start-Job.md) [Stop-Job](../Microsoft.PowerShell.Core/Stop-Job.md) [Receive-Job](../Microsoft.PowerShell.Core/Receive-Job.md)

#File: reference/7.6/ThreadJob/ThreadJob.md

--- Download Help Link: https://aka.ms/powershell75-help Help Version: 7.6.0.0 Locale: en-US Module Guid: 0e7b895d-2fec-43f7-8cae-11e8d16f6e40 Module Name: ThreadJob ms.date: 07/09/2019 title: ThreadJob Module --- # ThreadJob Module ## Description This module extends the existing PowerShell BackgroundJob to include a new thread based **ThreadJob** job. This is a lighter weight solution for running concurrent PowerShell scripts that works within the existing PowerShell job infrastructure. ## ThreadJob Cmdlets ### [Start-ThreadJob](Start-ThreadJob.md) Creates background jobs similar to the `Start-Job` cmdlet.

””” } ::: </powershell_reference_excerpts> </input_data> ```

URL: https://ib.bsb.br/pwsh