about_Preference_Variables
简短说明
自定义 PowerShell 行为的变量。
长说明
PowerShell 包含一组变量,可用于自定义其行为。 这些首选项变量的工作方式类似于基于 GUI 的系统中的选项。
首选项变量会影响 PowerShell 操作环境和所有命令在环境中运行。 在许多情况下,cmdlet 具有可用于替代特定命令的首选项行为的参数。
下表列出了首选项变量及其默认值。
变量 | 默认值 |
---|---|
$ConfirmPreference |
High |
$DebugPreference |
SilentlyContinue |
$ErrorActionPreference |
Continue |
$ErrorView |
ConciseView |
$FormatEnumerationLimit |
4 |
$InformationPreference |
SilentlyContinue |
$LogCommandHealthEvent |
$False (未记录) |
$LogCommandLifecycleEvent |
$False (未记录) |
$LogEngineHealthEvent |
$True (记录) |
$LogEngineLifecycleEvent |
$True (记录) |
$LogProviderLifecycleEvent |
$True (记录) |
$LogProviderHealthEvent |
$True (记录) |
$MaximumHistoryCount |
4096 |
$OFS |
空格字符 (" " ) |
$OutputEncoding |
(属于UTF8Encoding 对象)的父级。 |
$ProgressPreference |
Continue |
$PSDefaultParameterValues |
@{} (空哈希表) |
$PSEmailServer |
$Null (无) |
$PSModuleAutoLoadingPreference |
All |
$PSSessionApplicationName |
'wsman' |
$PSSessionConfigurationName |
'http://schemas.microsoft.com/powershell/Microsoft.PowerShell' |
$PSSessionOption |
(属于PSSessionOption 对象)的父级。 |
$Transcript |
$Null (无) |
$VerbosePreference |
SilentlyContinue |
$WarningPreference |
Continue |
$WhatIfPreference |
$False |
PowerShell 包含以下用于存储用户首选项的环境变量。 有关这些环境变量的详细信息,请参阅 about_Environment_Variables。
env:PSExecutionPolicyPreference
$env:PSModulePath
注意
仅当这些脚本或函数在与使用首选项的范围相同的范围内定义时,对首选项变量的更改才会在脚本和函数中生效。 有关详细信息,请参阅 about_Scopes。
使用首选项变量
本文档介绍每个首选项变量。
若要显示特定首选项变量的当前值,请键入变量的名称。 例如,以下命令显示 $ConfirmPreference
变量的值。
$ConfirmPreference
High
若要更改变量的值,请使用赋值语句。 例如,以下语句将 $ConfirmPreference
参数的值更改为 Medium。
$ConfirmPreference = "Medium"
设置的值特定于当前 PowerShell 会话。 若要使变量在所有 PowerShell 会话中有效,请将其添加到 PowerShell 配置文件。 有关详细信息,请参阅 about_Profiles。
远程工作
在远程计算机上运行命令时,远程命令仅受远程计算机 PowerShell 客户端中设置的首选项的约束。 例如,运行远程命令时,远程计算机的 $DebugPreference
变量的值将确定 PowerShell 如何响应调试消息。
有关远程命令的详细信息,请参阅 about_Remote。
$ConfirmPreference
确定 PowerShell 在运行 cmdlet 或函数之前是否自动提示你进行确认。
变量 $ConfirmPreference
采用 的一个ConfirmImpact
枚举值: 高、 中、 低或 无。
Cmdlet 和函数的风险为 高、 中或 低。 当变量的值 $ConfirmPreference
小于或等于分配给 cmdlet 或函数的风险时,PowerShell 会在运行 cmdlet 或函数之前自动提示你进行确认。
如果变量的 $ConfirmPreference
值为 None,则 PowerShell 在运行 cmdlet 或函数之前永远不会自动提示你。
若要更改会话中所有 cmdlet 和函数的确认行为,请更改 $ConfirmPreference
变量的值。
若要替代 $ConfirmPreference
单个命令的 ,请使用 cmdlet 或函数的 Confirm 参数。 若要请求确认,请使用 -Confirm
。 若要禁止确认,请使用 -Confirm:$false
。
的有效值 $ConfirmPreference
:
- 无:PowerShell 不会自动提示。 若要请求特定命令的确认,请使用 cmdlet 或函数的 Confirm 参数。
- 低:在运行低、中或高风险的 cmdlet 或函数之前,PowerShell 会提示进行确认。
- 中等:PowerShell 在运行具有中等或高风险的 cmdlet 或函数之前,会提示进行确认。
- 高:在运行具有高风险的 cmdlet 或函数之前,PowerShell 会提示进行确认。
详细说明
PowerShell 可以在执行操作之前自动提示你进行确认。 例如,当 cmdlet 或函数显著影响系统以删除数据或使用大量系统资源时。
Remove-Item -Path C:\file.txt
Confirm
Are you sure you want to perform this action?
Performing operation "Remove File" on Target "C:\file.txt".
[Y] Yes [A] Yes to All [N] No [L] No to All [?] Help (default is "Y"):
风险估算是 cmdlet 或称为 ConfirmImpact 的函数的属性。 用户无法更改它。
可能会给系统带来风险的 Cmdlet 和函数具有 一个 Confirm 参数,可用于请求或禁止对单个命令进行确认。
由于大多数 cmdlet 和函数使用中的默认风险值 ConfirmImpact,默认值$ConfirmPreference
为“高”,因此很少发生自动确认。 但是,可以通过将 的值 $ConfirmPreference
更改为 “中” 或“ 低”来激活自动确认。
示例
此示例演示变量默认值 High 的效果$ConfirmPreference
。 高值仅确认高风险 cmdlet 和函数。 由于大多数 cmdlet 和函数的风险中等,因此它们不会自动确认并 Remove-Item
删除文件。 添加到 -Confirm
命令会提示用户进行确认。
$ConfirmPreference
High
Remove-Item -Path C:\temp1.txt
使用 -Confirm
请求确认。
Remove-Item -Path C:\temp2.txt -Confirm
Confirm
Are you sure you want to perform this action?
Performing operation "Remove File" on Target "C:\temp2.txt".
[Y] Yes [A] Yes to All [N] No [L] No to All
[?] Help (default is "Y"):
以下示例演示将 的值 $ConfirmPreference
更改为 Medium 的效果。 由于大多数 cmdlet 和函数风险中等,因此会自动确认。 若要取消单个命令的确认提示,请使用值为 的 $false
Confirm 参数。
$ConfirmPreference = "Medium"
Remove-Item -Path C:\temp2.txt
Confirm
Are you sure you want to perform this action?
Performing operation "Remove File" on Target "C:\temp2.txt".
[Y] Yes [A] Yes to All [N] No [L] No to All
[?] Help (default is "Y"):
Remove-Item -Path C:\temp3.txt -Confirm:$false
$DebugPreference
确定 PowerShell 如何响应脚本、cmdlet 或提供程序 Write-Debug
或命令行中的命令生成的调试消息。
变量 $DebugPreference
采用 的一个ActionPreference
枚举值: SilentlyContinue、 Stop、 Continue、 Inquire、 Ignore、 Suspend 或 Break。
某些 cmdlet 显示调试消息,这些消息通常是专为程序员和技术支持专业人员设计的技术消息。 默认情况下,不会显示调试消息,但可以通过更改 的值 $DebugPreference
来显示调试消息。
可以使用 cmdlet 的 Debug 通用参数来显示或隐藏特定命令的调试消息。 有关详细信息,请参阅 about_CommonParameters。
有效值如下:
- 停止:显示调试消息并停止执行。 将错误写入控制台。
- 查询:显示调试消息并询问是否要继续。 将 Debug 公共参数添加到命令时,当命令配置为生成调试消息时,会将
$DebugPreference
变量的值更改为 “查询”。 - 继续:显示调试消息并继续执行。
- SilentlyContinue: (默认) 无效。 不会显示调试消息,并且将继续执行而不会中断。
示例
以下示例演示在命令行上输入命令时Write-Debug
更改 的值$DebugPreference
的效果。
此更改会影响所有调试消息,包括 cmdlet 和脚本生成的消息。 这些示例演示 Debug 参数,该参数显示或隐藏与单个命令相关的调试消息。
此示例演示变量的默认值 SilentlyContinue 的效果$DebugPreference
。 默认情况下, Write-Debug
不会显示 cmdlet 的调试消息,并继续处理。 使用 Debug 参数时,它会替代单个命令的首选项。 将显示调试消息。
$DebugPreference
SilentlyContinue
Write-Debug -Message "Hello, World"
Write-Debug -Message "Hello, World" -Debug
DEBUG: Hello, World
此示例显示了 具有 Continue 值的效果$DebugPreference
。 将显示调试消息,命令将继续处理。
$DebugPreference = "Continue"
Write-Debug -Message "Hello, World"
DEBUG: Hello, World
此示例使用值为 的 $false
Debug 参数来禁止显示单个命令的消息。 不会显示调试消息。
Write-Debug -Message "Hello, World" -Debug:$false
此示例演示设置为 Stop 值的效果$DebugPreference
。 将显示调试消息并停止命令。
$DebugPreference = "Stop"
Write-Debug -Message "Hello, World"
DEBUG: Hello, World
Write-Debug : The running command stopped because the preference variable
"DebugPreference" or common parameter is set to Stop: Hello, World
At line:1 char:1
+ Write-Debug -Message "Hello, World"
此示例使用值为 的 $false
Debug 参数来禁止显示单个命令的消息。 不会显示调试消息,也不会停止处理。
Write-Debug -Message "Hello, World" -Debug:$false
此示例演示设置为“查询”值的效果$DebugPreference
。 此时会显示调试消息,并提示用户进行确认。
$DebugPreference = "Inquire"
Write-Debug -Message "Hello, World"
DEBUG: Hello, World
Confirm
Continue with this operation?
[Y] Yes [A] Yes to All [H] Halt Command [?] Help (default is "Y"):
此示例使用值为 的 $false
Debug 参数来禁止显示单个命令的消息。 不会显示调试消息,并且处理仍在继续。
Write-Debug -Message "Hello, World" -Debug:$false
$ErrorActionPreference
确定 PowerShell 如何响应非终止错误,该错误不会停止 cmdlet 处理。 例如,在命令行或脚本、cmdlet 或提供程序中,例如 cmdlet 生成的 Write-Error
错误。
变量 $ErrorActionPreference
采用 的一个ActionPreference
枚举值: SilentlyContinue、 Stop、 Continue、 Inquire、 Ignore、 Suspend 或 Break。
可以使用 cmdlet 的 ErrorAction 通用参数替代特定命令的首选项。
有效值如下:
- 中断 - 在发生错误或引发异常时输入调试器。
- 继续: (默认) 显示错误消息并继续执行。
- 忽略:禁止显示错误消息并继续执行命令。 Ignore 值适用于每个命令的使用,而不是用作保存的首选项。 Ignore 不是变量的有效值
$ErrorActionPreference
。 - 查询:显示错误消息并询问是否要继续。
- SilentlyContinue:无效果。 不会显示错误消息,并且继续执行而不会中断。
- 停止:显示错误消息并停止执行。 除了生成的错误之外, Stop 值还会向错误流生成 ActionPreferenceStopException 对象。 流 (stream)
- 挂起:自动挂起工作流作业以允许进一步调查。 调查后,可以恢复工作流。 Suspend 值适用于按命令使用,而不是用作保存的首选项。 挂起 不是变量的有效值
$ErrorActionPreference
。
$ErrorActionPreference
和 ErrorAction 参数不会影响 PowerShell 响应停止 cmdlet 处理的终止错误的方式。 有关 ErrorAction 通用参数的详细信息,请参阅 about_CommonParameters。
示例
这些示例演示变量的不同值 $ErrorActionPreference
的效果。 ErrorAction 参数用于替代$ErrorActionPreference
值。
此示例显示 $ErrorActionPreference
默认值 Continue。 生成非终止错误。 显示消息并继续进行处理。
# Change the ErrorActionPreference to 'Continue'
$ErrorActionPreference = 'Continue'
# Generate a non-terminating error and continue processing the script.
Write-Error -Message 'Test Error' ; Write-Host 'Hello World'
Write-Error: Test Error
Hello World
此示例显示 $ErrorActionPreference
默认值 “查询”。 生成错误并显示操作提示。
# Change the ErrorActionPreference to 'Inquire'
$ErrorActionPreference = 'Inquire'
Write-Error -Message 'Test Error' ; Write-Host 'Hello World'
Confirm
Test Error
[Y] Yes [A] Yes to All [H] Halt Command [S] Suspend [?] Help (default is "Y"):
此示例显示 设置为 $ErrorActionPreference
SilentlyContinue 的 。
错误消息被禁止显示。
# Change the ErrorActionPreference to 'SilentlyContinue'
$ErrorActionPreference = 'SilentlyContinue'
# Generate an error message
Write-Error -Message 'Test Error' ; Write-Host 'Hello World'
# Error message is suppressed and script continues processing
Hello World
此示例显示设置为 $ErrorActionPreference
Stop 的 。 它还显示为变量生成的 $Error
额外对象。
# Change the ErrorActionPreference to 'Stop'
$ErrorActionPreference = 'Stop'
# Error message is is generated and script stops processing
Write-Error -Message 'Test Error' ; Write-Host 'Hello World'
# Show the ActionPreferenceStopException and the error generated
$Error[0]
$Error[1]
Write-Error: Test Error
ErrorRecord : Test Error
WasThrownFromThrowStatement : False
TargetSite : System.Collections.ObjectModel.Collection`1[System.Management.Automation.PSObject]
Invoke(System.Collections.IEnumerable)
StackTrace : at System.Management.Automation.Runspaces.PipelineBase.Invoke(IEnumerable input)
at Microsoft.PowerShell.Executor.ExecuteCommandHelper(Pipeline tempPipeline,
Exception& exceptionThrown, ExecutionOptions options)
Message : The running command stopped because the preference variable "ErrorActionPreference" or
common parameter is set to Stop: Test Error
Data : {System.Management.Automation.Interpreter.InterpretedFrameInfo}
InnerException :
HelpLink :
Source : System.Management.Automation
HResult : -2146233087
Write-Error: Test Error
$ErrorView
确定 PowerShell 中错误消息的显示格式。
变量 $ErrorView
采用下列枚举值之 ErrorView
一: NormalView、 CategoryView 或 ConciseView。
有效值如下:
ConciseView: (默认) 为高级模块生成器提供简明的错误消息和重构视图。 如果错误来自命令行,则为单行错误消息。 否则,将收到多行错误消息,其中包含错误和指向错误的指针,显示该错误在该行中发生的位置。 如果终端支持虚拟终端,则 ANSI 颜色代码用于提供颜色强调色。 可以在 处更改
$Host.PrivateData.ErrorAccentColor
强调色。 使用Get-Error
cmdlet 全面详细查看完全限定的错误,包括内部异常。在 PowerShell 7 中添加了 ConciseView。
NormalView:专为大多数用户设计的详细视图。 由错误说明和错误中涉及的对象的名称组成。
CategoryView:专为生产环境设计的简洁结构化视图。 其格式如下所示:
{Category}: ({TargetName}:{TargetType}) :[{Activity}], {Reason}
有关 CategoryView 中字段的详细信息,请参阅 ErrorCategoryInfo 类。
示例
此示例演示当 的值为 $ErrorView
默认值 时,如何显示错误。 Get-ChildItem
用于查找不存在的目录。
Get-ChildItem -path 'C:\NoRealDirectory'
Get-ChildItem: Cannot find path 'C:\NoRealDirectory' because it does not exist.
此示例演示当 的值为 $ErrorView
默认值 时,如何显示错误。 Script.ps1
运行 并从 语句中引发错误 Get-Item
。
./Script.ps1
Get-Item: C:\Script.ps1
Line |
11 | Get-Item -Path .\stuff
| ^ Cannot find path 'C:\demo\stuff' because it does not exist.
此示例显示 当 的值 $ErrorView
更改为 NormalView 时,错误显示的方式。 Get-ChildItem
用于查找不存在的文件。
Get-ChildItem -Path C:\nofile.txt
Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist.
At line:1 char:1
+ Get-ChildItem -Path C:\nofile.txt
此示例演示当 的值 $ErrorView
更改为 CategoryView 时,如何显示相同的错误。
$ErrorView = "CategoryView"
Get-ChildItem -Path C:\nofile.txt
ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundException
此示例演示 的值 $ErrorView
仅影响错误显示。 它不会更改存储在自动变量中的 $Error
错误对象的结构。 有关自动变量的信息 $Error
,请参阅 about_automatic_variables。
以下命令采用与错误数组中最新错误(元素 0)关联的 ErrorRecord 对象,并在列表中设置所有错误对象的属性的格式。
$Error[0] | Format-List -Property * -Force
PSMessageDetails :
Exception : System.Management.Automation.ItemNotFoundException:
Cannot find path 'C:\nofile.txt' because it does
not exist.
at System.Management.Automation.SessionStateInternal.
GetChildItems(String path, Boolean recurse, UInt32
depth, CmdletProviderContext context)
at System.Management.Automation.ChildItemCmdlet
ProviderIntrinsics.Get(String path, Boolean
recurse, UInt32 depth, CmdletProviderContext context)
at Microsoft.PowerShell.Commands.GetChildItemCommand.
ProcessRecord()
TargetObject : C:\nofile.txt
CategoryInfo : ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem],
ItemNotFoundException
FullyQualifiedErrorId : PathNotFound,
Microsoft.PowerShell.Commands.GetChildItemCommand
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {0, 1}
$FormatEnumerationLimit
确定显示中包含多少个枚举项。 此变量不会影响基础对象,仅影响显示。 当 的值 $FormatEnumerationLimit
小于枚举项数时,PowerShell 将添加省略号 (...
) 以指示未显示的项目。
有效值:整数 (Int32
)
默认值:4
示例
此示例演示如何使用 $FormatEnumerationLimit
变量改进枚举项的显示。
此示例中的 命令生成一个表,其中列出了计算机上运行的所有服务,分为两个组:一个组用于 正在运行 的服务,另一个用于 停止 的服务。 它使用 Get-Service
命令获取所有服务,然后通过管道 Group-Object
将结果发送到 cmdlet,cmdlet 按服务状态对结果进行分组。
结果为一个表,其中列出了 “名称” 列中的状态,以及 “组 ”列中的进程。 若要更改列标签,请使用哈希表,请参阅 about_Hash_Tables。 有关详细信息,请参阅 Format-Table 中的示例。
查找 的 $FormatEnumerationLimit
当前值。
$FormatEnumerationLimit
4
列出按 状态分组的所有服务。 每个状态的 “组” 列中最多列出了四个服务,因为 $FormatEnumerationLimit
其值为 4。
Get-Service | Group-Object -Property Status
Count Name Group
----- ---- -----
60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...}
41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart...}
若要增加列出的项数,请将 的值 $FormatEnumerationLimit
增加到 1000。 使用 Get-Service
和 Group-Object
显示服务。
$FormatEnumerationLimit = 1000
Get-Service | Group-Object -Property Status
Count Name Group
----- ---- -----
60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec...
41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc...
与 Format-Table
Wrap 参数一起使用以显示服务列表。
Get-Service | Group-Object -Property Status | Format-Table -Wrap
Count Name Group
----- ---- -----
60 Running {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec,
Client for NFS, CryptSvc, DcomLaunch, Dhcp, dmserver,
Dnscache, ERSvc, Eventlog, EventSystem, FwcAgent, helpsvc,
HidServ, IISADMIN, InoRPC, InoRT, InoTask, lanmanserver,
lanmanworkstation, LmHosts, MDM, Netlogon, Netman, Nla,
NtLmSsp, PlugPlay, PolicyAgent, ProtectedStorage, RasMan,
RemoteRegistry, RpcSs, SamSs, Schedule, seclogon, SENS,
SharedAccess, ShellHWDetection, SMT PSVC, Spooler,
srservice, SSDPSRV, stisvc, TapiSrv, TermService, Themes,
TrkWks, UMWdf, W32Time, W3SVC, WebClient, winmgmt, wscsvc,
wuauserv, WZCSVC, zzInterix}
41 Stopped {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc,
ClipSrv, clr_optimization_v2.0.50727_32, COMSysApp,
CronService, dmadmin, FastUserSwitchingCompatibility,
HTTPFilter, ImapiService, Mapsvc, Messenger, mnmsrvc,
MSDTC, MSIServer, msvsmon80, NetDDE, NetDDEdsdm, NtmsSvc,
NVSvc, ose, RasAuto, RDSessMgr, RemoteAccess, RpcLocator,
SCardSvr, SwPrv, SysmonLog, TlntSvr, upnphost, UPS, VSS,
WmdmPmSN, Wmi, WmiApSrv, xmlprov}
$InformationPreference
变量 $InformationPreference
允许设置要向用户显示的信息流首选项。 具体而言,是通过添加 Write-Information cmdlet 添加到命令或脚本的信息性消息。 如果使用 InformationAction 参数,则其值将替代变量的值 $InformationPreference
。 Write-Information
已在 PowerShell 5.0 中引入。
变量 $InformationPreference
采用 的一个ActionPreference
枚举值: SilentlyContinue、 Stop、 Continue、 Inquire、 Ignore、 Suspend 或 Break。
有效值如下:
- 停止:在命令出现
Write-Information
时停止命令或脚本。 - 查询:显示在命令中指定的
Write-Information
信息性消息,然后询问是否要继续。 - 继续:显示信息性消息,并继续运行。
- 挂起 仅适用于 PowerShell 6 及更高版本不支持的工作流。
- SilentlyContinue: (默认) 无效。 不会显示信息性消息,并且脚本会继续,而不会中断。
$Log*事件
Log*事件首选项变量确定在 事件查看器 中写入 PowerShell 事件日志的事件类型。 默认情况下,仅记录引擎和提供程序事件。 但是,可以使用 Log*事件 首选项变量来自定义日志,例如记录有关命令的事件。
Log*事件首选项变量如下所示:
$LogCommandHealthEvent
:记录命令初始化和处理中的错误和异常。 默认值为$false
(未记录) 。$LogCommandLifecycleEvent
:记录命令发现中的命令和命令管道的启动和停止以及安全异常。 默认值为$false
(未记录) 。$LogEngineHealthEvent
:记录会话的错误和失败。 默认值为$true
(记录) 。$LogEngineLifecycleEvent
:记录会话的开始和结束。 默认值为$true
(记录) 。$LogProviderHealthEvent
:记录提供程序错误,例如读取和写入错误、查找错误和调用错误。 默认值为$true
(记录) 。$LogProviderLifecycleEvent
:添加和删除 PowerShell 提供程序的日志。 默认值为$true
(记录) 。 有关 PowerShell 提供程序的信息,请参阅 about_Providers。
若要启用 Log*事件,请键入值为 的 $true
变量,例如:
$LogCommandLifeCycleEvent = $true
若要禁用事件类型,请键入值为 的 $false
变量,例如:
$LogCommandLifeCycleEvent = $false
启用的事件仅对当前 PowerShell 控制台有效。 若要将配置应用到所有控制台,请将变量设置保存在 PowerShell 配置文件中。 有关详细信息,请参阅 about_Profiles。
$MaximumHistoryCount
确定当前会话的命令历史记录中保存的命令数。
有效值:1 - 32768 (Int32
)
默认值:4096
若要确定命令历史记录中当前保存的命令数,请键入:
(Get-History).Count
若要查看会话历史记录中保存的命令,请使用 Get-History
cmdlet。 有关详细信息,请参阅 about_History。
$OFS
输出字段分隔符 (OFS) 指定分隔转换为字符串的数组元素的字符。
有效值:任何字符串。
默认值:空格
默认情况下, $OFS
变量不存在,输出文件分隔符为空格,但你可以添加此变量并将其设置为任何字符串。 可以通过键入 $OFS="<value>"
来更改会话中的 值$OFS
。
注意
如果预期脚本、模块或配置输出中) (空格 " "
的默认值,请注意 $OFS
,默认值未在代码中的其他位置更改。
示例
此示例显示,当数组转换为字符串时,使用空格分隔值。 在这种情况下,整数数组存储在变量中,然后将该变量强制转换为字符串。
$array = 1,2,3,4
[string]$array
1 2 3 4
若要更改分隔符,请通过向变量赋值来添加 $OFS
变量。
变量必须命名为 $OFS
。
$OFS = "+"
[string]$array
1+2+3+4
若要还原默认行为,可以为 的值分配一个空间 (" "
) $OFS
,或删除变量。 以下命令删除变量,然后验证分隔符是否为空格。
Remove-Variable OFS
[string]$array
1 2 3 4
$OutputEncoding
确定 PowerShell 在向其他应用程序发送文本时使用的字符编码方法。
例如,如果应用程序将 Unicode 字符串返回到 PowerShell,则可能需要将值更改为 UnicodeEncoding 才能正确发送字符。
有效值如下所示:派生自 Encoding 类的对象,例如 ASCIIEncoding、 UTF7Encoding、 UTF8Encoding、 UTF32Encoding 和 UnicodeEncoding。
默认值: UTF8Encoding 对象。
示例
此示例演示如何使 Windows findstr.exe 命令在已针对使用 Unicode 字符(如中文)的语言进行本地化的计算机上在 PowerShell 中正常工作。
第一个命令查找 的值 $OutputEncoding
。 由于 值是编码对象,因此仅显示其 EncodingName 属性。
$OutputEncoding.EncodingName
在此示例中, findstr.exe 命令用于搜索文件中存在的 Test.txt
两个中文字符。 在 Windows 命令提示符 (cmd.exe) 中运行此findstr.exe 命令时, findstr.exe 在文本文件中查找 字符。 但是,在 PowerShell 中运行相同的 findstr.exe 命令时,找不到这些字符,因为 PowerShell 以 ASCII 文本(而不是 Unicode 文本)将它们发送到 findstr.exe 。
findstr <Unicode-characters>
若要使命令在 PowerShell 中正常工作,请将 的值 $OutputEncoding
设置为控制台的 OutputEncoding 属性的值,该值基于为 Windows 选择的区域设置。 由于 OutputEncoding 是控制台的静态属性,因此请在 命令中使用双冒号 (::
) 。
$OutputEncoding = [console]::OutputEncoding
$OutputEncoding.EncodingName
OEM United States
更改编码后, findstr.exe 命令将查找 Unicode 字符。
findstr <Unicode-characters>
test.txt: <Unicode-characters>
$ProgressPreference
确定 PowerShell 如何响应脚本、cmdlet 或提供程序生成的进度更新,例如 Write-Progress cmdlet 生成的进度栏。
cmdlet Write-Progress
创建显示命令状态的进度栏。
变量 $ProgressPreference
采用 的一个ActionPreference
枚举值: SilentlyContinue、 Stop、 Continue、 Inquire、 Ignore、 Suspend 或 Break。
有效值如下:
- 停止:不显示进度栏。 而是显示错误消息并停止执行。
- 查询:不显示进度栏。 提示提供继续权限。 如果使用 或
A
进行答复Y
,它将显示进度栏。 - 继续: (默认) 显示进度栏并继续执行。
- SilentlyContinue:执行命令,但不显示进度栏。
$PSDefaultParameterValues
指定 cmdlet 和高级函数的参数的默认值。
的值 $PSDefaultParameterValues
是一个哈希表,其中键由 cmdlet 名称和参数名称组成,由冒号分隔 (:
) 。 该值是指定的自定义默认值。
$PSDefaultParameterValues
已在 PowerShell 3.0 中引入。
有关此首选项变量的详细信息,请参阅 about_Parameters_Default_Values。
$PSEmailServer
指定用于发送电子邮件的默认电子邮件服务器。 此首选项变量由发送电子邮件的 cmdlet 使用,例如 Send-MailMessage cmdlet。
$PSModuleAutoloadingPreference
在会话中启用和禁用模块的自动导入。 所有 为默认值。 若要导入模块,请获取或使用模块中的任何命令。 例如,使用 Get-Command
。 默认情况下,变量 $PSModuleAutoloadingPreference
不存在。 未定义变量时的默认行为与 相同 $PSModuleAutoloadingPreference = 'All'
。
无论变量的值如何,都可以使用 Import-Module 导入模块。
变量 $PSModuleAutoloadingPreference
采用PSModuleAutoLoadingPreference
枚举值: None、 ModuleQualified 或 All。
有效值为:
- 全部:模块在首次使用时自动导入。
- ModuleQualified:仅当用户在模块中使用命令的模块限定名称时,才会自动导入模块。 例如,如果用户键入
MyModule\MyCommand
,PowerShell 将导入 MyModule 模块。 - 无:会话中禁用模块的自动导入。 若要导入模块,请使用
Import-Module
cmdlet。
有关模块自动导入的详细信息,请参阅 about_Modules。
$PSSessionApplicationName
指定远程命令的默认应用程序名称,该命令使用 Web Services 进行管理 (WS-Management) 技术。 有关详细信息,请参阅 关于 Windows 远程管理。
系统默认应用程序名称为 WSMAN
,但可以使用此首选项变量更改默认值。
应用程序名称是连接 URI 中的最后一个节点。 例如,以下示例 URI 中的应用程序名称为 WSMAN
。
http://Server01:8080/WSMAN
当远程命令未指定连接 URI 或应用程序名称时,将使用默认应用程序名称。
WinRM 服务使用应用程序名称来选择一个侦听器来为连接请求提供服务。 参数的值应与远程计算机上侦听器的 URLPrefix 属性值匹配。
若要替代系统默认值和此变量的值,并为特定会话选择其他应用程序名称,请使用 New-PSSession、Enter-PSSession 或 Invoke-Command cmdlet 的 ConnectionURI 或 ApplicationName 参数。
首选项 $PSSessionApplicationName
变量在本地计算机上设置,但它指定远程计算机上的侦听器。 如果指定的应用程序名称在远程计算机上不存在,则用于建立会话的命令将失败。
$PSSessionConfigurationName
指定用于在当前会话中创建 的 PSSession 的默认会话配置。
此首选项变量在本地计算机上设置,但它指定位于远程计算机上的会话配置。
变量的值 $PSSessionConfigurationName
是完全限定的资源 URI。
默认值 http://schemas.microsoft.com/PowerShell/microsoft.PowerShell
指示远程计算机上的 Microsoft.PowerShell 会话配置。
如果仅指定配置名称,则会在前面添加以下架构 URI:
http://schemas.microsoft.com/PowerShell/
可以使用 、 Enter-PSSession
或 Invoke-Command
cmdlet 的 ConfigurationName 参数New-PSSession
替代默认值并为特定会话选择不同的会话配置。
可以随时更改此变量的值。 执行此操作时,请记住,所选的会话配置必须存在于远程计算机上。 否则,用于创建使用会话配置的会话的命令将失败。
此首选项变量不能确定在远程用户创建连接到此计算机的会话时使用哪些本地会话配置。 但是,可以使用本地会话配置的权限来确定哪些用户可以使用它们。
$PSSessionOption
为远程会话中的高级用户选项建立默认值。 这些选项首选项将替代会话选项的系统默认值。
变量 $PSSessionOption
包含 PSSessionOption 对象。 有关详细信息,请参阅 System.Management.Automation.Remoting.PSSessionOption。
对象的每个属性都表示一个会话选项。 例如, NoCompression 属性在会话期间进行数据压缩。
默认情况下, $PSSessionOption
变量包含一个 PSSessionOption 对象,其中包含所有选项的默认值,如下所示。
MaximumConnectionRedirectionCount : 5
NoCompression : False
NoMachineProfile : False
ProxyAccessType : None
ProxyAuthentication : Negotiate
ProxyCredential :
SkipCACheck : False
SkipCNCheck : False
SkipRevocationCheck : False
OperationTimeout : 00:03:00
NoEncryption : False
UseUTF16 : False
IncludePortInSPN : False
OutputBufferingMode : None
Culture :
UICulture :
MaximumReceivedDataSizePerCommand :
MaximumReceivedObjectSize : 209715200
ApplicationArguments :
OpenTimeout : 00:03:00
CancelTimeout : 00:01:00
IdleTimeout : -00:00:00.0010000
有关这些选项的说明和详细信息,请参阅 New-PSSessionOption。 有关远程命令和会话的详细信息,请参阅 about_Remote 和 about_PSSessions。
若要更改首选项变量的值 $PSSessionOption
,请使用 New-PSSessionOption
cmdlet 创建具有首选选项值的 PSSessionOption 对象。 将输出保存在名为 的 $PSSessionOption
变量中。
$PSSessionOption = New-PSSessionOption -NoCompression
$PSSessionOption
若要在每个 PowerShell 会话中使用首选项变量,请将创建New-PSSessionOption
变量的$PSSessionOption
命令添加到 PowerShell 配置文件。 有关详细信息,请参阅 about_Profiles。
可以为特定远程会话设置自定义选项。 设置的选项优先于系统默认值和首选项变量的值 $PSSessionOption
。
若要设置自定义会话选项,请使用 New-PSSessionOption
cmdlet 创建 PSSessionOption 对象。 然后,使用 PSSessionOption 对象作为创建会话的 cmdlet 中 SessionOption 参数的值,例如 New-PSSession
、 Enter-PSSession
和 Invoke-Command
。
$Transcript
Start-Transcript
用于指定脚本文件的名称和位置。 如果未为 Path 参数指定值, Start-Transcript
请使用全局变量的值 $Transcript
中的路径。 如果尚未创建此变量,Start-Transcript
请将脚本作为\PowerShell_transcript.<time-stamp>.txt
文件存储在目录中$Home\My Documents
。
$VerbosePreference
确定 PowerShell 如何响应脚本、cmdlet 或提供程序生成的详细消息,例如 Write-Verbose cmdlet 生成的消息。 详细消息描述为执行命令而执行的操作。
默认情况下,不会显示详细消息,但可以通过更改 的值 $VerbosePreference
来更改此行为。
变量 $VerbosePreference
采用ActionPreference
枚举值: SilentlyContinue、 Stop、 Continue、 Inquire、 Ignore、 Suspend 或 Break。
有效值如下:
- 停止:显示详细消息和错误消息,然后停止执行。
- 查询:显示详细消息,然后显示询问是否要继续的提示。
- 继续:显示详细消息,然后继续执行。
- SilentlyContinue: (默认) 不显示详细消息。 继续执行。
可以使用 cmdlet 的 Verbose 通用参数来显示或隐藏特定命令的详细消息。 有关详细信息,请参阅 about_CommonParameters。
示例
这些示例演示 的不同值 $VerbosePreference
和 Verbose 参数替代首选项值的效果。
此示例显示了 SilentlyContinue 值(默认值)的效果。 命令使用 Message 参数,但不将消息写入 PowerShell 控制台。
Write-Verbose -Message "Verbose message test."
使用 Verbose 参数时,将写入消息。
Write-Verbose -Message "Verbose message test." -Verbose
VERBOSE: Verbose message test.
此示例显示 Continue 值的效果。 变量 $VerbosePreference
设置为 Continue ,并显示消息。
$VerbosePreference = "Continue"
Write-Verbose -Message "Verbose message test."
VERBOSE: Verbose message test.
此示例使用 Verbose 参数,其值为 $false
重写 Continue 值。 不会显示该消息。
Write-Verbose -Message "Verbose message test." -Verbose:$false
此示例显示 Stop 值的效果。 变量 $VerbosePreference
设置为 Stop ,并显示消息。 命令已停止。
$VerbosePreference = "Stop"
Write-Verbose -Message "Verbose message test."
VERBOSE: Verbose message test.
Write-Verbose : The running command stopped because the preference variable
"VerbosePreference" or common parameter is set to Stop: Verbose message test.
At line:1 char:1
+ Write-Verbose -Message "Verbose message test."
此示例使用 Verbose 参数,其值为 $false
重写 Stop 值。 不会显示该消息。
Write-Verbose -Message "Verbose message test." -Verbose:$false
此示例显示了 查询 值的效果。 变量 $VerbosePreference
设置为 “查询”。 将显示消息,并提示用户进行确认。
$VerbosePreference = "Inquire"
Write-Verbose -Message "Verbose message test."
VERBOSE: Verbose message test.
Confirm
Continue with this operation?
[Y] Yes [A] Yes to All [H] Halt Command [?] Help (default is "Y"):
此示例使用 Verbose 参数,其值为 $false
替代 查询 值。 系统不会提示用户,也不会显示消息。
Write-Verbose -Message "Verbose message test." -Verbose:$false
$WarningPreference
确定 PowerShell 如何响应脚本、cmdlet 或提供程序生成的警告消息,例如 Write-Warning cmdlet 生成的消息。
默认情况下,将显示警告消息并继续执行,但可以通过更改 的值 $WarningPreference
来更改此行为。
变量 $WarningPreference
采用ActionPreference
枚举值: SilentlyContinue、 Stop、 Continue、 Inquire、 Ignore、 Suspend 或 Break。
有效值如下:
- 停止:显示警告消息和错误消息,然后停止执行。
- 查询:显示警告消息,然后提示继续权限。
- 继续: (默认) 显示警告消息,然后继续执行。
- SilentlyContinue:不显示警告消息。 继续执行。
可以使用 cmdlet 的 WarningAction 通用参数来确定 PowerShell 如何响应来自特定命令的警告。 有关详细信息,请参阅 about_CommonParameters。
示例
这些示例演示 的不同值 $WarningPreference
的效果。
WarningAction 参数将替代首选项值。
此示例显示默认值 Continue 的效果。
$m = "This action can delete data."
Write-Warning -Message $m
WARNING: This action can delete data.
此示例使用值为 SilentlyContinue 的 WarningAction 参数来禁止显示警告。 不会显示该消息。
$m = "This action can delete data."
Write-Warning -Message $m -WarningAction SilentlyContinue
此示例将 $WarningPreference
变量更改为 SilentlyContinue 值。 不会显示该消息。
$WarningPreference = "SilentlyContinue"
$m = "This action can delete data."
Write-Warning -Message $m
此示例使用 WarningAction 参数在生成警告时停止。
$m = "This action can delete data."
Write-Warning -Message $m -WarningAction Stop
WARNING: This action can delete data.
Write-Warning : The running command stopped because the preference variable
"WarningPreference" or common parameter is set to Stop:
This action can delete data.
At line:1 char:1
+ Write-Warning -Message $m -WarningAction Stop
此示例将 $WarningPreference
变量更改为 “查询 ”值。 系统会提示用户进行确认。
$WarningPreference = "Inquire"
$m = "This action can delete data."
Write-Warning -Message $m
WARNING: This action can delete data.
Confirm
Continue with this operation?
[Y] Yes [A] Yes to All [H] Halt Command [?] Help (default is "Y"):
此示例使用值为 SilentlyContinue 的 WarningAction 参数。 命令将继续执行,并且不显示任何消息。
$m = "This action can delete data."
Write-Warning -Message $m -WarningAction SilentlyContinue
此示例将 $WarningPreference
值更改为 Stop。
$WarningPreference = "Stop"
$m = "This action can delete data."
Write-Warning -Message $m
WARNING: This action can delete data.
Write-Warning : The running command stopped because the preference variable
"WarningPreference" or common parameter is set to Stop:
This action can delete data.
At line:1 char:1
+ Write-Warning -Message $m
此示例使用具有“查询”值的 WarningAction。 发生警告时,系统会提示用户。
$m = "This action can delete data."
Write-Warning -Message $m -WarningAction Inquire
WARNING: This action can delete data.
Confirm
Continue with this operation?
[Y] Yes [A] Yes to All [H] Halt Command [?] Help (default is "Y"):
$WhatIfPreference
确定是否为每个支持它的命令自动启用 WhatIf 。 启用 WhatIf 后,cmdlet 会报告命令的预期效果,但不执行命令。
有效值如下:
- false (0,未启用) : (默认) WhatIf 未自动启用。 若要手动启用它,请使用 cmdlet 的 WhatIf 参数。
- true (1,已启用) : WhatIf 在支持它的任何命令上自动启用。 用户可以使用值为 False 的 WhatIf 参数手动禁用它,例如
-WhatIf:$false
。
示例
这些示例演示 的不同值 $WhatIfPreference
的效果。
它们演示如何使用 WhatIf 参数替代特定命令的首选项值。
此示例演示变量设置为默认值 False 的效果$WhatIfPreference
。 使用 Get-ChildItem
验证文件是否存在。
Remove-Item
删除文件。 删除文件后,可以使用 验证删除 Get-ChildItem
。
Get-ChildItem -Path .\test.txt
Remove-Item -Path ./test.txt
Directory: C:\Test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 9/13/2019 10:53 10 test.txt
Get-ChildItem -Path .\test.txt
Get-ChildItem : Cannot find path 'C:\Test\test.txt' because it does not exist.
At line:1 char:1
+ Get-ChildItem -File test.txt
此示例演示当 的值为 $WhatIfPreference
False 时使用 WhatIf 参数的效果。
请确保该文件已存在。
Get-ChildItem -Path .\test2.txt
Directory: C:\Test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2/28/2019 17:06 12 test2.txt
使用 WhatIf 参数确定尝试删除文件的结果。
Remove-Item -Path .\test2.txt -WhatIf
What if: Performing the operation "Remove File" on target "C:\Test\test2.txt".
验证文件是否未删除。
Get-ChildItem -Path .\test2.txt
Directory: C:\Test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2/28/2019 17:06 12 test2.txt
此示例演示变量设置为值 True 的效果$WhatIfPreference
。 使用 Remove-Item
删除文件时,将显示文件的路径,但不会删除该文件。
尝试删除文件。 将显示一条消息,说明如果 Remove-Item
已运行,但文件未删除,会发生什么情况。
$WhatIfPreference = "True"
Remove-Item -Path .\test2.txt
What if: Performing the operation "Remove File" on target "C:\Test\test2.txt".
使用 Get-ChildItem
验证文件是否未删除。
Get-ChildItem -Path .\test2.txt
Directory: C:\Test
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 2/28/2019 17:06 12 test2.txt
此示例演示如何在 的值为 $WhatIfPreference
True 时删除文件。 它使用值为 的 $false
WhatIf 参数。 使用 Get-ChildItem
验证文件是否已删除。
Remove-Item -Path .\test2.txt -WhatIf:$false
Get-ChildItem -Path .\test2.txt
Get-ChildItem : Cannot find path 'C:\Test\test2.txt' because it does not exist.
At line:1 char:1
+ Get-ChildItem -Path .\test2.txt
下面是不支持 WhatIf 且Stop-Process
支持 WhatIf 的 cmdlet 的示例。Get-Process
变量 $WhatIfPreference
的值为 True。
Get-Process
不支持 WhatIf。 执行命令时,它会显示 Winword 进程。
Get-Process -Name Winword
NPM(K) PM(M) WS(M) CPU(s) Id SI ProcessName
------ ----- ----- ------ -- -- -----------
130 119.84 173.38 8.39 15024 4 WINWORD
Stop-Process
支持 WhatIf。 Winword 进程未停止。
Stop-Process -Name Winword
What if: Performing the operation "Stop-Process" on target "WINWORD (15024)".
可以使用值为 $false
的 WhatIf 参数来替代 Stop-Process
WhatIf 行为。 Winword 进程已停止。
Stop-Process -Name Winword -WhatIf:$false
若要验证 Winword 进程是否已停止,请使用 Get-Process
。
Get-Process -Name Winword
Get-Process : Cannot find a process with the name "Winword".
Verify the process name and call the cmdlet again.
At line:1 char:1
+ Get-Process -Name Winword