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