about_Preference_Variables

应用到: Windows PowerShell 2.0, Windows PowerShell 3.0, Windows PowerShell 4.0

主题

首选项变量

简短说明

自定义 Windows PowerShell 的行为的变量

详细说明

Windows PowerShell 包括一组可让你自定义其行为的变量。这些“首选项变量”的工作方式与基于 GUI 的系统中的选项相同。

首选项变量会影响 Windows PowerShell 操作环境和该环境中运行的所有命令。在许多情况下,这些 cmdlet 具有可用于替代特定命令的首选项行为的参数。

下表列出了首选项变量及其默认值。

    Variable                             Default Value
    --------                             -------------
    $ConfirmPreference                   High
    $DebugPreference                     SilentlyContinue
    $ErrorActionPreference               Continue
    $ErrorView                           NormalView
    $FormatEnumerationLimit              4
    $LogCommandHealthEvent               False (not logged)
    $LogCommandLifecycleEvent            False (not logged)
    $LogEngineHealthEvent                True (logged)
    $LogEngineLifecycleEvent             True (logged)
    $LogProviderLifecycleEvent           True (logged)
    $LogProviderHealthEvent              True (logged)
    $MaximumAliasCount                   4096
    $MaximumDriveCount                   4096
    $MaximumErrorCount                   256
    $MaximumFunctionCount                4096
    $MaximumHistoryCount                 4096
    $MaximumVariableCount                4096
    $OFS                                 (Space character (" "))
    $OutputEncoding                      ASCIIEncoding object
    $ProgressPreference                  Continue
    $PSDefaultParameterValues            (None - empty hash table)     
    $PSEmailServer                       (None)
    $PSModuleAutoLoadingPreference       All
    $PSSessionApplicationName            WSMAN
    $PSSessionConfigurationName          https://schemas.microsoft.com/PowerShell/microsoft.PowerShell 
    $PSSessionOption                     (See below)
    $VerbosePreference                   SilentlyContinue
    $WarningPreference                   Continue
    $WhatIfPreference                    0

Windows PowerShell 也包括以下用于存储用户首选项的环境变量。有关这些环境变量的详细信息,请参阅 about_Environment_Variables。

    Variable                                         
    --------    
    PSExecutionPolicyPreference                     
    PSModulePath                        

使用首选项变量

本文档介绍每个首选项变量。

若要显示特定首选项变量的当前值,请键入变量的名称。作为响应,Windows PowerShell 提供其值。例如,下面的命令显示 $ConfirmPreference 变量的值。

        PS> $ConfirmPreference
        High

若要更改变量的值,请使用赋值语句。例如,下面的语句将值“Medium”赋给 $ConfirmPreference 变量。

        PS> $ConfirmPreference = "Medium"

与所有变量一样,你设置的值都是特定于当前 Windows PowerShell 会话的。若要使它们在所有 Windows PowerShell 会话中有效,请将其添加到 Windows PowerShell 配置文件。有关详细信息,请参阅 about_Profiles。

远程工作

在远程计算机上运行命令时,远程命令仅受在远程计算机上的 Windows PowerShell 客户端中设置的首选项的约束。例如,运行远程命令时,远程计算机中的 $DebugPreference 变量值将确定 Windows PowerShell 如何响应调试消息。

有关远程命令的详细信息,请参阅 about_remote。

$ConfirmPreference
------------------

确定 Windows PowerShell 是否会在运行 cmdlet 或函数前自动提示你进行确认。

当 $ConfirmPreference 变量的值(High、Medium、Low)小于或等于分配给 cmdlet 或函数的风险(High、Medium、Low)时,Windows PowerShell 会在运行 cmdlet 或函数前自动提示你进行确认。

如果 $ConfirmPreference 变量的值为 None,则 Windows PowerShell 从不会在运行 cmdlet 或函数前自动发出提示。

若要更改会话中所有 cmdlet 和函数的确认行为,请更改 $ConfirmPreference 变量的值。

若要替代一个命令的 $ConfirmPreference,请使用 cmdlet 或函数的 Confirm 参数。若要请求确认,请使用 -Confirm。若要取消确认,请使用 -Confirm:$false

$ConfirmPreference 的有效值:

None:Windows PowerShell 不会自动发出提示。若要请求特定命令的确认,请使用 cmdlet 或函数的 Confirm 参数。

Low:Windows PowerShell 在运行低、中或高风险的 cmdlet 或函数前提示确认。

Medium:Windows PowerShell 在运行中、高风险的 cmdlet 或函数前提示确认。

High:Windows PowerShell 在运行高风险的 cmdlet 或函数前提示确认。

详细说明

当一个 cmdlet 或函数的操作(如那些删除数据或使用大量系统资源的操作)会对系统造成显著影响时,Windows PowerShell 可以在执行操作前自动提示你进行确认。

例如,

    PS> remove-item 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  [S] Suspend  [?] Help (default is "Y"):

风险估计是 cmdlet 或函数的一个特性,被称为其“ConfirmImpact”。用户无法更改该特性。

可能对系统构成风险的 cmdlet 和函数具有一个 Confirm 参数,可使用该参数请求或取消单个命令的确认。

由于大多数 cmdlet 和函数使用默认风险值 (ConfirmImpact) Medium,而 $ConfirmPreference 的默认值为 High,因此很少出现自动确认。但是,你可以通过将 $ConfirmPreference 的值更改为 Medium 或 Low 来激活自动确认。

示例

此示例演示 $ConfirmPreference 的默认值的效果。值为 High 仅确认高风险的 cmdlet 和函数。由于大多数 cmdlet 和函数为中等风险,因此不会自动确认。

          PS> $confirmpreference              #Get the current value of the
          High                                 variable
          
          PS> remove-item temp1.txt           #Delete a file
          PS>                                 #Deleted without confirmation

           
          PS> remove-item temp2.txt -confirm  #Use the Confirm parameter to
                                               request confirmation

          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  [S] Suspend  [?] Help (default is "Y"):

下面的示例演示将 $ConfirmPreference 的值更改为 Medium 的效果。由于大多数 cmdlet 和函数风险为中等风险,因此将自动进行确认。若要取消单个命令的确认提示,请使用值为 $false 的 Confirm 参数

            
          PS> $confirmpreference = "Medium"  #Change the value of $ConfirmPreference
          PS> remove-item temp2.txt          #Deleting a file triggers confirmation         
                                     
          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  [S] Suspend  [?] Help (default is "Y"):


          PS> remove-item temp3.txt -confirm:$false   #Use Confirm parameter
                                                       to suppress confirmation
          PS>

$DebugPreference
------------------

确定 Windows PowerShell 如何响应由脚本、cmdlet、提供程序,或命令行处的 Write-Debug 命令生成的调试消息。

某些 cmdlet 显示调试消息,这些消息通常专供编程人员和技术支持专业人员使用,具有很强的技术性。默认情况下,不显示调试消息,但可以通过更改 $DebugPreference 的值来显示调试消息。

也可以使用 cmdlet 的 Debug 通用参数来显示或隐藏特定命令的调试消息。有关详细信息,请键入:“get-help about_commonparameters”。

有效值:

Stop:显示调试消息并停止执行。将错误写入控制台。

Inquire:显示调试消息并询问是否要继续。请注意,在命令配置为生成调试消息时,将 Debug 通用参数添加到命令会将 $DebugPreference 变量的值更改为 Inquire。

Continue:显示调试消息并继续执行。

SilentlyContinue:(默认值) 不起作用。不显示调试消息,并继续执行而不中断。

示例

下面的示例演示在命令行输入 Write-debug 命令时更改 $DebugPreference 的值的效果。此更改将影响所有调试消息,包括由 cmdlet 和脚本生成的消息。这些示例还演示了 Debug 通用参数的用法,该参数显示或隐藏与单个命令相关的调试消息。

此示例演示默认值“SilentlyContinue”的效果。不显示调试消息并继续进行处理。最后一个命令使用 Debug 参数来替代单个命令的首选项。

        PS> $debugpreference                    # Get the current value of
        SilentlyContinue                          $DebugPreference

        PS> write-debug "Hello, World"
        PS>                                     # The debug message is not
                                                  displayed.

        PS> write-debug "Hello, World" -Debug   # Use the Debug parameter
        DEBUG: Hello, World                     # The debug message is
                                                  is requested.                                                                                                    displayed and confirmation
        Confirm
        Continue with this operation?
        [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):

此示例演示值“Continue”的效果。最后一个命令使用值为 $false 的 Debug 参数来取消显示单个命令的消息。

        PS> $debugpreference = "Continue"   # Change the value to "Continue"

        PS> write-debug "Hello, World"
        DEBUG: Hello, World                 # The debug message is displayed
        PS>                                   and processing continues.
                                           

        PS> write-debug "Hello, World" -Debug:$false   
                                            # Use the Debug parameter with
                                              false.
        PS>                                 # The debug message is not
                                              displayed.

此示例演示值“Stop”的效果。最后一个命令使用值为 $false 的 Debug 参数来取消显示单个命令的消息。

        PS> $debugpreference = "Stop"       #Change the value to "Stop"
        PS> write-debug "Hello, World"
        DEBUG: Hello, World
        Write-Debug : Command execution stopped because the shell variable "DebugPreference" is
        set to Stop.
        At line:1 char:12
        + write-debug  <<<< "Hello, World"

        PS> write-debug "Hello, World" -Debug:$false   
                                            # Use the Debug parameter with
                                              $false
        PS>                                 # The debug message is not 
                                              displayed and processing is
                                              not stopped.

此示例演示值“Inquire”的效果。最后一个命令使用值为 $false 的 Debug 参数来取消显示单个命令的消息。

        PS> $debugpreference = "Inquire"
        PS> write-debug "Hello, World"
        DEBUG: Hello, World

        Confirm
        Continue with this operation?
        [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):

        PS> write-debug "Hello, World" -Debug:$false   
                                            # Use the Debug parameter with
                                              $false
        PS>                                 # The debug message is not
                                              displayed and processing
                                              continues without interruption.

$ErrorActionPreference
----------------------

确定 Windows PowerShell 如何响应命令行处,或者脚本、cmdlet 或提供程序中的非终止错误(不会停止 cmdlet 处理的错误),例如,由 Write-Error cmdlet 生成的错误。

还可以使用 Cmdlet 的 ErrorAction 通用参数来替代特定命令的首选项。

有效值:

Stop:显示错误消息并停止执行。

Inquire:显示错误消息并询问是否要继续。

Continue(默认值):显示错误消息并继续执行。

Suspend:自动挂起工作流作业以允许进一步的调查。在调查之后,可以继续工作流。

SilentlyContinue:不起作用。不显示错误消息,并继续执行而不中断。

注意:

ErrorAction 通用参数的 Ignore 值不是有效的 $ErrorActionPreference 变量值。Ignore 值供每个命令使用,而不作为已保存的首选项使用。

$ErrorActionPreference 和 ErrorAction 通用参数都不影响 Windows PowerShell 响应终止错误(会停止 cmdlet 处理的错误)的方式。

有关 ErrorAction 通用参数的详细信息,请参阅 about_CommonParameters (https://go.microsoft.com/fwlink/?LinkID=113216)。

示例

这些示例显示不用 $ErrorActionPreference 值的效果,以及如何使用 ErrorAction 通用参数替代单个命令的首选项。ErrorAction 参数与 $ErrorActionPreference 变量具有相同的有效值。

此示例演示默认值 Continue 的效果。

        PS> $erroractionpreference                      
        Continue# Display the value of the preference.          
                                  
        PS> write-error "Hello, World"                  
                                # Generate a non-terminating error.

        write-error "Hello, World" : Hello, World       
                                # The error message is displayed and
                                  execution continues.

        PS> write-error "Hello, World" -ErrorAction:SilentlyContinue
                                # Use the ErrorAction parameter with a 
                                  value of "SilentlyContinue".
        PS>                                             
                                # The error message is not displayed and
                                  execution continues.

此示例演示值 SilentlyContinue 的效果。

        PS> $ErrorActionPreference = "SilentlyContinue"
                                # Change the value of the preference.
        PS> write-error "Hello, World"                  
                                # Generate an error message.
        PS>                     
                                # Error message is suppressed.
        PS> write-error "Hello, World" -erroraction:continue
                                # Use the ErrorAction parameter with a
                                  value of "Continue".
        write-error "Hello, World" -erroraction:continue : Hello, World
                                # The error message is displayed and
                                  execution continues.

此示例演示真正的错误的效果。在此例中,命令获取不存在文件 nofile.txt。此示例还使用 ErrorAction 通用参数来替代首选项。

        PS> $erroractionpreference                      
        SilentlyContinue        # Display the value of the preference.     
                                

        PS> get-childitem -path nofile.txt
        PS>                     # Error message is suppressed.

        PS> $ErrorActionPreference = "Continue" 
                                # Change the value to Continue.

        PS> get-childitem -path nofile.txt
        Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist.
        At line:1 char:4
        + get-childitem  <<<< nofile.txt

        PS> get-childitem -path nofile.txt -erroraction SilentlyContinue
                                # Use the ErrorAction parameter
        PS>                     
                                # Error message is suppressed.
  
        PS> $ErrorActionPreference = "Inquire"          
                                # Change the value to Inquire.
        PS> get-childitem -path nofile.txt

        Confirm
        Cannot find path 'C:\nofile.txt' because it does not exist.
        [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): y
        
        Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist.
        At line:1 char:4
        + get-childitem  <<<< nofile.txt

        PS> $ErrorActionPreference = "Continue"                  
                                # Change the value to Continue.
        PS> Get-Childitem nofile.txt -erroraction "Inquire"      
                                # Use the ErrorAction parameter to override
                                  the preference value.

        Confirm
        Cannot find path 'C:\nofile.txt' because it does not exist.         
        [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):

$ErrorView
----------

确定 Windows PowerShell 中错误消息的显示格式。

有效值

NormalView(默认值):专为大多数用户而设计的详细视图。包括错误说明、错误中涉及的对象的名称,以及指向命令中引起错误的单词的箭头 (<<<<)。

CategoryView:旨在用于生产环境的简洁的结构化视图。格式为:{Category}:({TargetName}:{TargetType}):[{Activity}], {Reason}

有关 CategoryView 中的字段的详细信息,请参阅 Windows PowerShell SDK 中的“ErrorCategoryInfo 类”。

示例

这些示例显示值 ErrorView 的效果。

此示例演示 $ErrorView 的值为 NormalView 时显示错误的方式。在此例中,Get-ChildItem 命令用于查找不存在的文件。

        PS> $ErrorView                         # Verify the value.
        NormalView

        PS> get-childitem nofile.txt           # Find a non-existent file.
        Get-ChildItem : Cannot find path 'C:\nofile.txt' because it does not exist.
        At line:1 char:14
        + get-childitem  <<<< nofile.txt

此示例演示 $ErrorView 的值为 CategoryView 时同一错误的显示方式。

        PS> $ErrorView = "CategoryView"        # Change the value to 
                                                 CategoryView

        PS> get-childitem nofile.txt
        ObjectNotFound: (C:\nofile.txt:String) [Get-ChildItem], ItemNotFoundException

此示例演示 ErrorView 的值仅影响错误显示;它不会更改 $error 自动变量中存储的错误对象的结构。有关 $error 自动变量的信息,请参阅 about_automatic_variables。

此命令采用与错误数组(元素 0)中最近的错误关联的 ErrorRecord 对象,并设置列表中错误对象的所有属性的格式。

        PS> $error[0] | format-list -property * -force

        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, CmdletProviderContext context)
                       at System.Management.Automation.ChildItemCmdletProviderIntrinsics.Get(String path,
                       Boolean recurse, 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

$FormatEnumerationLimit
-----------------------

确定显示时包含的枚举项数目。此变量不会影响基础对象;只会影响显示。当 $FormatEnumerationLimit 的值小于枚举项的数目时,Windows PowerShell 将添加一个省略号 (...) 以指示有未显示的项。

        Valid values: Integers (Int32)
        Default value: 4

示例

此示例演示如何使用 $FormatEnumerationLimit 变量来改进枚举项的显示。

此示例中的命令生成一个表,分两组列出计算机上运行的所有服务;一组为正在运行的服务,另一组为已停止的服务。它使用 Get-service 命令来获取所有服务,然后将结果通过管道发送给 Group-Object cmdlet,后者按服务状态对结果进行分组。

生成的显示是一个表,在 Name 列中列出状态,在 Group 列中列出具有该状态的进程。(若要更改列标签,请使用哈希表。有关详细信息,请参阅“get-help format-table -examples”中的示例。)

Group 列中最多列出每种状态的 4 个服务。若要增加列出的项数,请将 $FormatEnumerationLimit 的值增加到 1000。

在生成的显示中,Group 列中列出的内容现在受行长度的限制。在此示例的最后一个命令中,使用 Format-Table 的 Wrap 参数可显示每个 Status 组中的所有进程。

        PS> $formatenumerationlimit         # Find the current value
        4
        
        PS> get-service | group-object -property status           
                                            # List all services grouped by
                                              status

        Count Name                      Group
        ----- ----                      -----
           60 Running                   {AdtAgent, ALG, Ati HotKey Poller, AudioSrv...}   
           41 Stopped                   {Alerter, AppMgmt, aspnet_state, ATI Smart...}

                                           # The list is truncated after
                                             4 items.


        PS> $formatenumerationlimit = 1000
                                           # Increase the limit to 1000.
        
        PS> get-service | group-object -property status           
                                           # Repeat the command.

        Count Name     Group
        ----- ----     -----
           60 Running  {AdtAgent, ALG, Ati HotKey Poller, AudioSrv, BITS, CcmExec...
           41 Stopped  {Alerter, AppMgmt, aspnet_state, ATI Smart, Browser, CiSvc...


        PS> get-service | group-object -property status | format-table -wrap
                                           # Add the Wrap parameter.

        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}

$Log*Event
----------

Log*Event 首选项变量用于确定将写入事件查看器中的 Windows PowerShell 事件日志的事件类型。默认情况下,仅记录引擎和提供程序事件,但你可以使用 Log*Event 首选项变量来自定义你的日志,例如有关命令的日志记录事件。

Log*Event 首选项变量如下所示:

            $LogCommandHealthEvent: Logs errors and exceptions in command initialization
                and processing. Default = $false (not logged).

            $LogCommandLifecycleEvent: 
                Logs the starting and stopping of commands and command pipelines
                and security exceptions in command discovery. Default = $false (not logged).

            $LogEngineHealthEvent: Logs errors and failures of sessions. Default = $true (logged).

            $LogEngineLifecycleEvent: Logs the opening and closing of sessions. 
                Default = $true (logged).

            $LogProviderHealthEvent: Logs provider errors, such as read and write errors,
                lookup errors, and invocation errors. Default = $true (logged).

            $LogProviderLifecycleEvent: Logs adding and removing of Windows PowerShell providers.
                Default = $true (logged). (For information about Windows PowerShell providers, type:
                "get-help about_provider".

若要启用 Log*Event,请键入值为 $true 的变量,例如:

            $LogCommandLifeCycleEvent

            - or -

            $LogCommandLifeCycleEvent = $true

若要禁用某个事件类型,请键入值为 $false 的变量,例如:

            $LogCommandLifeCycleEvent = $false

启用的事件仅对当前 Windows PowerShell 控制台有效。若要将配置应用于所有控制台,请在 Windows PowerShell 配置文件中保存变量设置。

$MaximumAliasCount
------------------

确定 Windows PowerShell 会话中允许的别名数。默认值 4096 应当可以满足大多数用途,但你可以进行调整以满足你的需求。

        Valid values: 1024 - 32768 (Int32)
        Default: 4096
      
        To count the aliases on your system, type: 

(get-alias).count

$MaximumDriveCount
------------------

确定给定会话中允许的 Windows PowerShell 驱动器数目。这包括文件系统驱动器,以及由 Windows PowerShell 提供程序公开并显示为驱动器的文件存储,例如 Alias:和 HKLM:驱动器。

        Valid values: 1024 - 32768 (Int32)
        Default: 4096
      
        To count the aliases on your system, type: 

(get-psdrive).count

$MaximumErrorCount
------------------

确定会话的错误历史记录中保存的错误数。

        Valid values: 256 - 32768 (Int32)
        Default: 256

表示每个保留的错误的对象都存储在 $Error 自动变量中。此变量包含错误记录对象数组,每个数组对应一个错误。最近的错误是数组中第一个对象 ($Error[0])。

若要计算系统中的错误数,请使用 $Error 数组的 Count 属性。请键入:

$Error.count

若要显示一个特定的错误,请使用数组表示法来显示错误。例如,若要查看最近的错误,请键入:

                $Error[0]

若要显示保留的最早的错误,请键入:

                $Error[($Error.Count -1]

若要显示 ErrorRecord 对象的属性,请键入:

                $Error[0] | format-list -property * -force

在此命令中,Force 参数替代 ErrorRecord 对象的特殊格式,并还原为常规格式。

若要删除错误历史记录中的错误,请使用错误数组的 Clear 方法。

               PS> $Error.count
               17
               PS> $Error.clear()
               PS>
               PS> $Error.count
               0

若要查找错误数组的所有属性和方法,请使用 Get-Member cmdlet 及其 InputObject 参数。当你通过管道将对象的集合传递给 Get-Member 时,Get-Member 将显示该集合中的对象的属性和方法。当使用 Get-Member 的 InputObject 参数时,Get-Member 显示集合的属性和方法。

$MaximumFunctionCount
------------------

确定给定会话中允许的函数数目。

        Valid values: 1024 - 32768 (Int32)
        Default: 4096

若要查看会话中的函数,请使用 Windows PowerShell Function:驱动器,该驱动器由 Windows PowerShell Function 提供程序公开。(若要获取 Function 提供程序的详细信息,请键入“get-help function”)。

若要列出当前会话中的函数,请键入:

            get-childitem function:

若要计算当前会话中的函数数目,请键入:

            (get-childitem function:).count

$MaximumHistoryCount
------------------

确定当前会话的命令历史记录中保存的命令数。

        Valid values: 1 - 32768 (Int32)
        Default: 4096

若要确定当前命令历史记录中保存的命令数,请键入:

            (get-history).count

若要查看会话历史记录中保存的命令,使用 Get-History cmdlet。有关详细信息,请参阅 about_History (https://go.microsoft.com/fwlink/?LinkID=113233)。

注意:在 Windows PowerShell 2.0 中,$MaximumHistoryCount 变量的默认值为 64。

$MaximumVariableCount
------------------

确定给定会话中允许的变量数(包括自动变量、首选项变量以及你在命令和脚本中创建的变量)。

        Valid values: 1024 - 32768 (Int32)
        Default: 4096

若要查看会话中的变量,使用 Get-Variable cmdlet 以及 Windows PowerShell Variable:驱动器和 Windows PowerShell Variable 提供程序的功能。若要获取有关 Variable 提供程序的信息,请键入“get-help variable”。

若要查找系统上的当前变量数目,请键入:

            (get-variable).count

$OFS
----

输出字段分隔符。指定用于在数组转换为字符串时分隔数组元素的字符。

        Valid values: Any string.
        Default: Space

默认情况下,$OFS 变量不存在,且输出文件分隔符为空格,但你可以添加此变量,并将其设置为任何字符串。

示例

此示例演示当数组转换为一个字符串时使用空格来分隔值。在此例中,整数数组存储在变量中,然后该变量转换为字符串。

       PS> $array = 1,2,3                 # Store an array of integers.       

       PS> [string]$array                 # Cast the array to a string.
       1 2 3                              # Spaces separate the elements

若要更改分隔符,请添加 $OFS 变量,方法是向其赋值。若要正常工作,该变量必须名为 $OFS。

       PS> $OFS = "+"                     # Create $OFS and assign a "+"

       PS> [string]$array                 # Repeat the command
       1+2+3                              # Plus signs separate the elements

若要还原默认行为,你可以向 $OFS 的值分配一个空格(“ ”)或删除该变量。此命令删除变量,然后验证该分隔符是否是空格。

       PS> Remove-Variable OFS            # Delete $OFS
       PS>

       PS> [string]$array                 # Repeat the command
       1 2 3                              # Spaces separate the elements
       

$OutputEncoding
---------------

确定 Windows PowerShell 在向其他应用程序发送文本时使用的字符编码方法。

例如,如果应用程序向 Windows PowerShell 返回 Unicode 字符串,可能需要将值更改为 UnicodeEncoding 以正确发送字符。

        Valid values: Objects derived from an Encoding class, such as
                      ASCIIEncoding, SBCSCodePageEncoding, UTF7Encoding, 
                      UTF8Encoding, UTF32Encoding, and UnicodeEncoding.

        Default: ASCIIEncoding object (System.Text.ASCIIEncoding)

示例

此示例演示如何使 Windows 中的 FINDSTR 命令在计算机上的 Windows PowerShell 中运行,该计算机已针对使用 Unicode 字符的语言(例如中文)进行了本地化。第一个命令查找 $OutputEncoding 的值。因为值为编码对象,因此仅显示其 EncodingName 属性。

          PS> $OutputEncoding.EncodingName  # Find the current value
          US-ASCII

在此示例中,FINDSTR 命令用于搜索 Test.txt 文件中存在的两个中文字符。当此 FINDSTR 命令在 Windows 命令提示符 (Cmd.exe) 中运行时,FINDSTR 在文本文件中找到这些字符。但是,当在 Windows PowerShell 中运行相同的 FINDSTR 命令时,未找到这些字符,因为 Windows PowerShell 采用 ASCII 文本而不是 Unicode 文本将其发送到 FINDSTR。

          PS> findstr <Unicode-characters>  # Use findstr to search.
          PS>                               # None found.

若要使该命令在 Windows PowerShell 中起作用,请将 $OutputEncoding 的值设置为控制台的 OutputEncoding 属性值,该属性值基于为 windows 选择的区域设置。因为 OutputEncoding 是控制台的一个静态属性,因此在命令中使用双冒号 (::)。

          PS> $OutputEncoding = [console]::outputencoding
          PS>                               # Set the value equal to the
                                              OutputEncoding property of the
                                              console.
          PS> $OutputEncoding.EncodingName               
          OEM United States
                                            # Find the resulting value.

进行此更改后,FINDSTR 命令找到字符。

          PS> findstr <Unicode-characters>               
          test.txt:         <Unicode-characters>        

# Use findstr to search. It find the
                                          characters in the text file.

$ProgressPreference
-------------------

确定 Windows PowerShell 如何响应由脚本、cmdlet 或提供程序生成的进度更新,例如由 Write-Progress cmdlet 生成的进度栏。Write-progress cmdlet 将创建一个描述命令状态的进度栏。

有效值:

Stop:不显示进度栏。相反,它将显示一条错误消息并停止执行。

Inquire:不显示进度栏。提示需要相应权限才可继续。如果回答 Y 或 A,它将显示进度栏。

Continue(默认值):显示进度栏并继续执行。

SilentlyContinue:执行命令,但不显示进度栏。

$PSEmailServer
--------------

指定用于发送电子邮件的默认电子邮件服务器。此首选项变量由发送电子邮件的 cmdlet(如 Send-MailMessage cmdlet)使用。

$PSDefaultParameterValues
-------------------------

指定 cmdlet 和高级函数的参数默认值。$PSDefaultParameterValues 的值是一个哈希表,其中的密钥由 cmdlet 名称和参数名组成(以冒号 (:) 分隔),并且该值是指定的自定义默认值。

Windows PowerShell 3.0 中引入了此变量

有关此首选项变量的详细信息,请参阅 about_Parameters_Default_Values。

$PSModuleAutoloadingPreference
------------------------------

在会话中启用和禁用自动模块导入。默认值为“All”。无论此变量为何值,你均可以使用 Import-Module cmdlet 导入模块。

有效值包括:

All 首次使用时自动导入模块。若要导入模块,请在模块中获取 (Get-Command) 或使用任何命令。

ModuleQualified

仅当用户在模块中使用命令的模块限定名称时自动导入模块。例如,如果用户键入“MyModule\MyCommand”,则 Windows PowerShell 导入 MyModule 模块。

None 在会话中禁用自动模块导入。若要导入模块,请使用 Import-Module cmdlet。

有关自动模块导入的详细信息,请参阅 about_Modules (https://go.microsoft.com/fwlink/?LinkID=144311)。

$PSSessionApplicationName
---------------------------

为使用 WS-Management 技术的远程命令指定默认应用程序名称。

系统默认应用程序名称为 WSMAN,但你可以使用此首选项变量更改默认名称。

应用程序名称是连接 URI 中的最后一个节点。例如,下面的示例 URI 中的应用程序名称为 WSMAN。

           http://Server01:8080/WSMAN

远程命令未指定连接 URI 或应用程序名称时,使用默认应用程序名称。

WinRM 服务使用应用程序名称来选择为连接请求提供服务的侦听器。此参数的值应与远程计算机上的侦听器的 URLPrefix 属性值相匹配。

若要替代系统默认值和此变量的值,并为特定会话选择不同的应用程序名称,请使用 New-PSSession、Enter-PSSession 或 Invoke-Command cmdlet 的 ConnectionURI 或 ApplicationName 参数。

此变量是在本地计算机上设置的,但是它可指定远程计算机上的侦听器。如果远程计算机上不存在指定的应用程序名称,则建立会话的命令将失败。

$PSSessionConfigurationName
---------------------------

指定用于在当前会话中创建 PSSession 的默认会话配置。

此变量是在本地计算机上设置的,但是它可指定位于远程计算机上的会话配置。

$PSSessionConfigurationName 变量的值是一个完全限定的资源 URI。

默认值:

         https://schemas.microsoft.com/PowerShell/microsoft.PowerShell 

指示远程计算机上的 Microsoft.PowerShell 会话配置。

如果只指定配置名称,则将在其前面预置以下架构 URI:

           https://schemas.microsoft.com/PowerShell/

你可以通过使用 New-PSSession、Enter-PSSession 或 Invoke-Command cmdlet 的 ConfigurationName 参数替代特定会话的默认值,并为该会话选择不同的会话配置。

你可以随时更改此变量的值。执行操作时,请记住你选择的会话配置必须存在于远程计算机上。如果不存在,创建使用该会话配置的会话的命令将失败。

当远程用户创建连接到此计算机的会话时,此首选项变量不能确定要使用的本地会话配置。但是,可以使用本地会话配置的权限来确定哪些用户可以使用它们。

$PSSessionOption
----------------

为远程会话中的高级用户选项建立默认值。这些选项的首选项用于替代会话选项的系统默认值。

$PSSessionOption 变量包含一个 PSSessionOption 对象 (System.Management.Automation.Remoting.PSSessionObject)。该对象的每个属性表示一个会话选项。例如,NoCompression 属性在会话期间关闭数据压缩。

默认情况下,$PSSessionOption 变量包含一个 PSSessionOption 对象,该对象具有所有选项的默认值,如下所示。

            MaximumConnectionRedirectionCo For descriptions of these options, see the help topic for the unt : 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 cmdlet 的帮助主题。

若要更改 $PSSessionOption 首选项变量的值,请使用 New-PSSessionOption cmdlet 创建 PSSessionOption 对象,并使用你喜欢的选项值。将输出保存在名为 $PSSessionOption 的变量中。

例如,

            $PSSessionOption = New-PSSessionOption -NoCompression

若要在每个 Windows PowerShell 会话中使用 $PSSessionOption 首选项变量,请将创建 $PSSessionOption 变量的 New-PSSessionOption 命令添加到 Windows PowerShell 配置文件中。

也可为特定远程会话设置自定义选项。你设置的选项优先于系统默认值和 $PSSessionOption 首选项变量的值。

若要设置自定义会话选项,请使用 New-PSSessionOption cmdlet 创建 PSSessionOption 对象。然后,使用 PSSessionOption 对象作为用于创建会话的 cmdlet(例如 New-PSSession、Enter-PSSession 和 Invoke-Command)中的 SessionOption 参数的值。

有关 New-PSSessionOption cmdlet 的详细信息,请参阅 New-PSSessionOption 的帮助主题。有关远程命令和会话的详细信息,请参阅 about_Remote 和 about_PSSessions。有关使用配置文件的详细信息,请参阅 about_Profiles。

$VerbosePreference
------------------

确定 Windows PowerShell 如何响应由脚本、cmdlet 或提供程序生成的详细消息,例如由 Write-Verbose cmdlet 生成的消息。通常,详细消息介绍所执行的用于执行命令的操作。

默认情况下,不显示详细消息,但你可以通过更改 $VerbosePreference 的值来更改此行为。

你可以使用 cmdlet 的 Verbose 通用参数来显示或隐藏特定命令的详细消息。有关详细信息,请键入:“get-help about_commonparameters”。

有效值:

Stop:显示详细消息和一条错误消息,然后停止执行。

Inquire:显示详细消息,然后显示询问你是否继续的提示。

Continue:显示详细消息,然后继续执行。

SilentlyContinue(默认值):不显示详细消息。继续执行。

示例

这些示例显示不同 $VerbosePreference 值的效果,以及如何使用 Verbose 通用参数来替代首选项值。

此示例演示默认值 SilentlyContinue 的效果。

        PS> $VerbosePreference             # Find the current value.
        SilentlyContinue

        PS> Write-Verbose "Verbose message test."              
        PS>                                # Write a verbose message.
                                           # Message is not displayed.

        PS> Write-Verbose "Verbose message test." -verbose     
        VERBOSE: Verbose message test.
                                   # Use the Verbose parameter.

此示例演示值 Continue 的效果。

        PS> $VerbosePreference = "Continue"                    
                                           # Change the value to Continue.
        PS> Write-Verbose "Verbose message test."              
                                           # Write a verbose message.
        VERBOSE: Verbose message test.                         
                                           # Message is displayed.

        PS> Write-Verbose "Verbose message test." -verbose:$false
                                           # Use the Verbose parameter with
                                             a value of $false.
        PS>                                  
                                           # Message is not displayed.

此示例演示值 Stop 的效果。

        PS> $VerbosePreference = "Stop"                        
                                           # Change the value to Stop.
        PS> Write-Verbose "Verbose message test."              
                                           # Write a verbose message.
        VERBOSE: Verbose message test.
        Write-Verbose : Command execution stopped because the shell variable "VerbosePreference"
        is set to Stop.
        At line:1 char:14
        + Write-Verbose  <<<< "Verbose message test."

       PS> Write-Verbose "Verbose message test." -verbose:$false
                                          # Use the Verbose parameter with
                                            a value of $false
       PS>                                  
                                          # Message is not displayed.

此示例演示值 Inquire 的效果。

       PS> $VerbosePreference = "Inquire"                      
                                         # Change the value to Inquire.
       PS> Write-Verbose "Verbose message test."               
       VERBOSE: Verbose message test.
                                         # Write a verbose message.
       Confirm
       Continue with this operation?
       [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): y
       PS>

       PS> Write-Verbose "Verbose message test." -verbose:$false
                                        # Use the Verbose parameter.
       PS>                              
                                        # Message is not displayed.

$WarningPreference
------------------

确定 Windows PowerShell 如何响应由脚本、cmdlet 或提供程序生成的警告消息,例如由 Write-Warning cmdlet 生成的消息。

默认情况下会显示警告消息并继续执行,但你可以通过更改 $WarningPreference 的值来更改此行为。

也可以使用 cmdlet 的 WarningAction 通用参数来确定 Windows PowerShell 如何响应特定命令发出的警告。有关详细信息,请键入:“get-help about_commonparameters”。

有效值:

Stop:显示警告消息和一条错误消息,然后停止执行。

Inquire:显示警告消息,然后提示需要相应权限才可继续。

Continue(默认值):显示警告消息,然后继续执行。

SilentlyContinue:不显示警告消息。继续执行。

示例

这些示例显示不同 $WarningPreference 值的效果,以及如何使用 WarningAction 通用参数来替代首选项值。

此示例演示默认值 Continue 的效果。

            PS> $WarningPreference    # Find the current value.                           
            Continue                  

                                      # Write a warning message.
            PS> Write-Warning "This action can delete data."     
            WARNING: This action can delete data.
                                      
                                      # Use the WarningAction parameter to 
                                      # suppress the warning for this command                                             
            PS> Write-Warning "This action can delete data." -warningaction silentlycontinue     

此示例演示值 SilentlyContinue 的效果。

            PS> $WarningPreference = "SilentlyContinue"           
                                      # Change the value to SilentlyContinue.
 
            PS> Write-Warning "This action can delete data."      
            PS>                        # Write a warning message.

       
            PS> Write-Warning "This action can delete data." -warningaction stop     
                                      # Use the WarningAction parameter to stop
                                      # processing when this command generates a
                                      # warning.         
            WARNING: This action can delete data.
            Write-Warning : Command execution stopped because the shell variable
            "WarningPreference" is set to Stop.
            At line:1 char:14
            + Write-Warning <<<<  "This action can delete data." -warningaction stop
                                 

此示例演示值 Inquire 的效果。

           PS> $WarningPreference = "Inquire"                    
                                      # Change the value to Inquire.
           PS> Write-Warning "This action can delete data."   
                                      # Write a warning message.     
           WARNING: This action can delete data.

           Confirm
           Continue with this operation?
           [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"): y
           PS>

           PS> Write-Warning "This action can delete data." -warningaction silentlycontinue
           PS>                         # Use the WarningAction parameter to change the
                                       # response to a warning for the current command.

此示例演示值 Stop 的效果。

           PS> $WarningPreference = "Stop"                       
                                     # Change the value to Stop.

           PS> Write-Warning "This action can delete data."      
                                     # Write a warning message.
           WARNING: This action can delete data.
           Write-Warning : Command execution stopped because the shell variable 
             "WarningPreference" is set to Stop.
           At line:1 char:14
           + Write-Warning  <<<< "This action can delete data."


           PS> Write-Warning "This action can delete data." -warningaction inquire
           WARNING: This action can delete data.

           Confirm
           Continue with this operation?
           [Y] Yes  [A] Yes to All  [H] Halt Command  [S] Suspend  [?] Help (default is "Y"):                        
                                       # Use the WarningAction parameter to change the
                                       # response to a warning for the current command.

$WhatIfPreference
------------------

确定是否为支持 WhatIf 的每个命令自动启用 WhatIf。启用 WhatIf 后,cmdlet 报告命令预期的效果,但是不执行命令。

有效值:

0(默认值):不会自动启用 WhatIf。若要手动启用,请使用命令的 WhatIf 参数。

1: WhatIf 可在任何支持它的命令上自动启用。用户可以使用值为 False 的 WhatIf 命令 (WhatIf:$false) 来手动禁用。

详细说明

当一个 cmdlet 支持 WhatIf 时,该 cmdlet 将报告命令的预期效果,而不执行命令。例如,Windows PowerShell 报告 Remove-Item 命令将删除哪些内容,而不是响应该命令删除 test.txt 文件。后续的 Get-Childitem 命令确认未删除文件。

              PS> remove-item test.txt
              What if: Performing operation "Remove-Item" on Target "Item: 
                C:\test.txt
              PS> get-childitem test.txt

              Directory: Microsoft.PowerShell.Core\FileSystem::C:


              Mode                LastWriteTime     Length     Name
              ----                -------------     ------     ----
              -a---         7/29/2006   7:15 PM         84     test.txt

示例

这些示例显示不同 $WhatIfPreference 值的效果。它们还演示如何使用 WhatIf cmdlet 参数来替代特定命令的首选项值。

此示例演示默认值 0(未启用)的效果。

             PS> $whatifpreference                     
             0                         # Check the current value.

             PS> get-childitem test.txt | format-list FullName
             FullName : C:\test.txt
                                       # Verify that the file exists.

             PS> remove-item test.txt                  
             PS>                       # Delete the file.

             PS> get-childitem test.txt | format-list -property FullName
                                       # Verify that the file is deleted.

             Get-ChildItem : Cannot find path 'C:\test.txt' because it does not exist.
             At line:1 char:14
             + get-childitem  <<<< test.txt | format-list fullname

此示例演示 $WhatIfPreference 的值为 0 时使用 WhatIf 参数的效果。

             PS> get-childitem test2.txt | format-list -property FullName 
             FullName : C:\test2.txt
                                      # Verify that the file exists.

             PS> remove-item test2.txt -whatif         
             What if: Performing operation "Remove File" on Target "C:\test2.txt".
                                      # Use the WhatIf parameter

             PS> get-childitem test2.txt | format-list -property FullName
             FullName : C:\test2.txt
                                      # Verify that the file was not deleted

此示例演示值 1(启用 WhatIf)的效果。当使用 Remove-item 删除某个 cmdlet 时,Remove-Item 显示它将删除的文件的路径,但不会删除该文件。

             PS> $whatifpreference = 1                 
             PS> $whatifpreference
             1                        # Change the value.
                                      
             PS> remove-item test.txt                  
             What if: Performing operation "Remove File" on Target "C:\test.txt".
                                      # Try to delete a file.

             PS> get-childitem test.txt | format-list FullName
             FullName : C:\test.txt
                                      # Verify that the file exists.

此示例演示 $WhatIfPreference 的值为 1 时如何删除文件。它使用值为 $false 的 WhatIf 参数。

             PS> remove-item test.txt -whatif:$false
                                      # Use the WhatIf parameter with $false.

此示例演示某些 cmdlet 支持 WhatIf 行为,而其他 cmdlet 则不支持。在此示例中,$WhatIfPreference 的值为 1(启用),执行不支持 WhatIf 的 Get-process 命令,但 Stop-Process 命令执行了 WhatIf 行为。可以使用值为 $false 的 WhatIf 参数来替代 Stop-process 命令的 WhatIf 行为。

            PS> $whatifpreference = 1                  
                                     # Change the value to 1.
                                                      
            PS> get-process winword  
                                    # A Get-Process command completes.

            Handles  NPM(K)    PM(K)      WS(K) VM(M)   CPU(s)     Id ProcessName
            -------  ------    -----      ----- -----   ------     -- -----------
                234       8     6324      15060   154     0.36   2312 WINWORD


           PS> stop-process -name winword              
           What if: Performing operation "Stop-Process" on Target "WINWORD (2312)".
                                    # A Stop-Process command uses WhatIf.

           PS> stop-process -name winword  -whatif:$false
           PS>                      # WhatIf:$false overrides the preference.
           
           PS> get-process winword                     
           Get-Process : Cannot find a process with the name 'winword'. Verify the process name
            and call the cmdlet again.
           At line:1 char:12
           + get-process  <<<< winword
                                    # Verify that the process is stopped.

另请参阅

about_Automatic_Variables

about_CommonParameters

about_Environment_Variables

about_Profiles

about_Remote about_Scopes