À propos des variables automatiquesAbout Automatic Variables
Description courteShort description
Décrit les variables qui stockent des informations d’État pour PowerShell.Describes variables that store state information for PowerShell. Ces variables sont créées et gérées par PowerShell.These variables are created and maintained by PowerShell.
Description longueLong description
Conceptuellement, ces variables sont considérées comme étant en lecture seule.Conceptually, these variables are considered to be read-only. Même s’ils peuvent être écrits dans, pour des raisons de compatibilité descendante, ils ne doivent pas être écrits.Even though they can be written to, for backward compatibility they should not be written to.
Voici une liste des variables automatiques dans PowerShell :Here is a list of the automatic variables in PowerShell:
$$
Contient le dernier jeton de la dernière ligne reçue par la session.Contains the last token in the last line received by the session.
$?$?
Contient l’état d’exécution de la dernière commande.Contains the execution status of the last command. Elle contient la valeur true si la dernière commande a réussi et false si elle a échoué.It contains True if the last command succeeded and False if it failed.
Pour les applets de commande et les fonctions avancées qui sont exécutées à plusieurs étapes dans un pipeline, par exemple dans les process
end
blocs et, l’appel de this.WriteError()
ou, respectivement, $PSCmdlet.WriteError()
à n’importe quel point, est défini $?
sur false , comme c’est le cas this.ThrowTerminatingError()
et $PSCmdlet.ThrowTerminatingError()
.For cmdlets and advanced functions that are run at multiple stages in a pipeline, for example in both process
and end
blocks, calling this.WriteError()
or $PSCmdlet.WriteError()
respectively at any point will set $?
to False , as will this.ThrowTerminatingError()
and $PSCmdlet.ThrowTerminatingError()
.
L' Write-Error
applet de commande affecte toujours la $?
valeur false immédiatement après son exécution, mais elle n’a pas la valeur $?
false pour une fonction qui l’appelle :The Write-Error
cmdlet always sets $?
to False immediately after it is executed, but will not set $?
to False for a function calling it:
function Test-WriteError
{
Write-Error "Bad"
$? # $false
}
Test-WriteError
$? # $true
Dans ce dernier cas, $PSCmdlet.WriteError()
doit être utilisé à la place.For the latter purpose, $PSCmdlet.WriteError()
should be used instead.
Pour les commandes natives (exécutables), a la valeur $?
true lorsque a la valeur $LASTEXITCODE
0, et la valeur false lorsque $LASTEXITCODE
est une autre valeur.For native commands (executables), $?
is set to True when $LASTEXITCODE
is 0, and set to False when $LASTEXITCODE
is any other value.
Notes
Jusqu’à PowerShell 7, contenant une instruction dans les parenthèses, la syntaxe de sous-expression (...)
ou l’expression de tableau est $(...)
@(...)
toujours réinitialisée $?
à true , de sorte que (Write-Error)
affiche la $?
valeur true .Until PowerShell 7, containing a statement within parentheses (...)
, subexpression syntax $(...)
or array expression @(...)
always reset $?
to True , so that (Write-Error)
shows $?
as True .
Cela a été modifié dans PowerShell 7, afin de $?
refléter toujours la réussite réelle de la dernière commande exécutée dans ces expressions.This has been changed in PowerShell 7, so that $?
will always reflect the actual success of the last command run in these expressions.
$^
Contient le premier jeton de la dernière ligne reçue par la session.Contains the first token in the last line received by the session.
$$
Comme pour $PSItem
.Same as $PSItem
. Contient l’objet actuel dans l’objet de pipeline.Contains the current object in the pipeline object. Vous pouvez utiliser cette variable dans les commandes qui exécutent une action sur chaque objet ou sur les objets sélectionnés dans un pipeline.You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.
$args$args
Contient un tableau de valeurs pour les paramètres non déclarés passés à une fonction, à un script ou à un bloc de script.Contains an array of values for undeclared parameters that are passed to a function, script, or script block. Lorsque vous créez une fonction, vous pouvez déclarer les paramètres à l’aide du param
mot clé ou en ajoutant une liste de paramètres séparés par des virgules entre parenthèses après le nom de la fonction.When you create a function, you can declare the parameters by using the param
keyword or by adding a comma-separated list of parameters in parentheses after the function name.
Dans une action d’événement, la $Args
variable contient des objets qui représentent les arguments d’événement de l’événement en cours de traitement.In an event action, the $Args
variable contains objects that represent the event arguments of the event that is being processed. Cette variable est remplie uniquement dans le Action
bloc d’une commande d’inscription d’événement.This variable is populated only within the Action
block of an event registration command.
La valeur de cette variable peut également être trouvée dans la propriété SourceArgs de l’objet PSEventArgs Get-Event
retourné par.The value of this variable can also be found in the SourceArgs property of the PSEventArgs object that Get-Event
returns.
$ConsoleFileName$ConsoleFileName
Contient le chemin d’accès du fichier de console ( .psc1
) qui a été le plus récemment utilisé dans la session.Contains the path of the console file (.psc1
) that was most recently used in the session. Cette variable est remplie lorsque vous démarrez PowerShell à l’aide du paramètre PSConsoleFile ou lorsque vous utilisez l' Export-Console
applet de commande pour exporter des noms de composant logiciel enfichable vers un fichier de console.This variable is populated when you start PowerShell with the PSConsoleFile parameter or when you use the Export-Console
cmdlet to export snap-in names to a console file.
Lorsque vous utilisez l' Export-Console
applet de commande sans paramètres, elle met à jour automatiquement le fichier de console qui a été utilisé le plus récemment dans la session.When you use the Export-Console
cmdlet without parameters, it automatically updates the console file that was most recently used in the session. Vous pouvez utiliser cette variable automatique pour déterminer le fichier qui sera mis à jour.You can use this automatic variable to determine which file will be updated.
$Error$Error
Contient un tableau d’objets d’erreur qui représentent les erreurs les plus récentes.Contains an array of error objects that represent the most recent errors.
L’erreur la plus récente est le premier objet d’erreur dans le tableau $Error[0]
.The most recent error is the first error object in the array $Error[0]
.
Pour éviter qu’une erreur ne soit ajoutée au $Error
tableau, utilisez le paramètre commun ErrorAction avec la valeur ignore .To prevent an error from being added to the $Error
array, use the ErrorAction common parameter with a value of Ignore . Pour plus d’informations, consultez about_CommonParameters.For more information, see about_CommonParameters.
$Event$Event
Contient un objet PSEventArgs qui représente l’événement en cours de traitement.Contains a PSEventArgs object that represents the event that is being processed. Cette variable est remplie uniquement dans le Action
bloc d’une commande d’inscription d’événement, telle que Register-ObjectEvent
.This variable is populated only within the Action
block of an event registration command, such as Register-ObjectEvent
. La valeur de cette variable est le même que celui retourné par l’applet de commande Get-Event
.The value of this variable is the same object that the Get-Event
cmdlet returns. Par conséquent, vous pouvez utiliser les propriétés de la Event
variable, telles que $Event.TimeGenerated
, dans un Action
bloc de script.Therefore, you can use the properties of the Event
variable, such as $Event.TimeGenerated
, in an Action
script block.
$EventArgs$EventArgs
Contient un objet qui représente le premier argument d’événement qui dérive de EventArgs de l’événement en cours de traitement.Contains an object that represents the first event argument that derives from EventArgs of the event that is being processed. Cette variable est remplie uniquement dans le Action
bloc d’une commande d’inscription d’événement.This variable is populated only within the Action
block of an event registration command.
La valeur de cette variable peut également être trouvée dans la propriété SourceEventArgs de l’objet PSEventArgs Get-Event
retourné par.The value of this variable can also be found in the SourceEventArgs property of the PSEventArgs object that Get-Event
returns.
$EventSubscriber$EventSubscriber
Contient un objet PSEventSubscriber qui représente l’abonné aux événements de l’événement en cours de traitement.Contains a PSEventSubscriber object that represents the event subscriber of the event that is being processed. Cette variable est remplie uniquement dans le Action
bloc d’une commande d’inscription d’événement.This variable is populated only within the Action
block of an event registration command. La valeur de cette variable est le même que celui retourné par l’applet de commande Get-EventSubscriber
.The value of this variable is the same object that the Get-EventSubscriber
cmdlet returns.
$ExecutionContext$ExecutionContext
Contient un objet EngineIntrinsics qui représente le contexte d’exécution de l’hôte PowerShell.Contains an EngineIntrinsics object that represents the execution context of the PowerShell host. Vous pouvez utiliser cette variable pour rechercher les objets d’exécution qui sont disponibles pour les applets de commande.You can use this variable to find the execution objects that are available to cmdlets.
$false$false
Contient la valeur false .Contains False . Vous pouvez utiliser cette variable pour représenter la valeur false dans les commandes et les scripts au lieu d’utiliser la chaîne « false ».You can use this variable to represent False in commands and scripts instead of using the string "false". La chaîne peut être interprétée comme true si elle est convertie en une chaîne non vide ou en un entier différent de zéro.The string can be interpreted as True if it's converted to a non-empty string or to a non-zero integer.
$foreach$foreach
Contient l’énumérateur (pas les valeurs résultantes) d’une boucle foreach .Contains the enumerator (not the resulting values) of a ForEach loop. La $ForEach
variable existe uniquement pendant l' ForEach
exécution de la boucle ; elle est supprimée une fois la boucle terminée.The $ForEach
variable exists only while the ForEach
loop is running; it's deleted after the loop is completed.
Les énumérateurs contiennent des propriétés et des méthodes que vous pouvez utiliser pour récupérer des valeurs de boucle et modifier l’itération de boucle actuelle.Enumerators contain properties and methods you can use to retrieve loop values and change the current loop iteration. Pour plus d’informations, consultez utilisation d’énumérateurs.For more information, see Using Enumerators.
$HOME$HOME
Contient le chemin d’accès complet du répertoire de destination de l’utilisateur.Contains the full path of the user's home directory. Cette variable est l’équivalent des "$env:homedrive$env:homepath"
variables d’environnement Windows, en général C:\Users\<UserName>
.This variable is the equivalent of the "$env:homedrive$env:homepath"
Windows environment variables, typically C:\Users\<UserName>
.
$Host$Host
Contient un objet qui représente l’application hôte actuelle pour PowerShell.Contains an object that represents the current host application for PowerShell. Vous pouvez utiliser cette variable pour représenter l’hôte actuel dans les commandes ou pour afficher ou modifier les propriétés de l’hôte, telles que $Host.version
ou $Host.CurrentCulture
, ou $host.ui.rawui.setbackgroundcolor("Red")
.You can use this variable to represent the current host in commands or to display or change the properties of the host, such as $Host.version
or $Host.CurrentCulture
, or $host.ui.rawui.setbackgroundcolor("Red")
.
$input$input
Contient un énumérateur qui énumère toutes les entrées passées à une fonction.Contains an enumerator that enumerates all input that is passed to a function. La $input
variable est disponible uniquement pour les fonctions et les blocs de script (qui sont des fonctions sans nom).The $input
variable is available only to functions and script blocks (which are unnamed functions).
Dans une fonction sans
Begin
bloc,Process
ouEnd
, la$input
variable énumère la collection de toutes les entrées de la fonction.In a function without aBegin
,Process
, orEnd
block, the$input
variable enumerates the collection of all input to the function.Dans le
Begin
bloc, la$input
variable ne contient aucune donnée.In theBegin
block, the$input
variable contains no data.Dans le
Process
bloc, la$input
variable contient l’objet qui se trouve actuellement dans le pipeline.In theProcess
block, the$input
variable contains the object that is currently in the pipeline.Dans le
End
bloc, la$input
variable énumère la collection de toutes les entrées de la fonction.In theEnd
block, the$input
variable enumerates the collection of all input to the function.Notes
Vous ne pouvez pas utiliser la
$input
variable à la fois dans le bloc de processus et dans le bloc de fin dans la même fonction ou le même bloc de script.You cannot use the$input
variable inside both the Process block and the End block in the same function or script block.
Étant donné que $input
est un énumérateur, l’accès à l’une de ses propriétés $input
n’est plus disponible.Since $input
is an enumerator, accessing any of it's properties causes $input
to no longer be available. Vous pouvez stocker $input
dans une autre variable pour réutiliser les $input
Propriétés.You can store $input
in another variable to reuse the $input
properties.
Les énumérateurs contiennent des propriétés et des méthodes que vous pouvez utiliser pour récupérer des valeurs de boucle et modifier l’itération de boucle actuelle.Enumerators contain properties and methods you can use to retrieve loop values and change the current loop iteration. Pour plus d’informations, consultez utilisation d’énumérateurs.For more information, see Using Enumerators.
$IsCoreCLR$IsCoreCLR
Contient $True
si la session active est en cours d’exécution sur le Runtime .net Core (CoreCLR).Contains $True
if the current session is running on the .NET Core Runtime (CoreCLR). Sinon, contient $False
.Otherwise contains $False
.
$IsLinux$IsLinux
Contient $True
si la session active est exécutée sur un système d’exploitation Linux.Contains $True
if the current session is running on a Linux operating system.
Sinon, contient $False
.Otherwise contains $False
.
$IsMacOS$IsMacOS
Contient $True
si la session active est exécutée sur un système d’exploitation MacOS.Contains $True
if the current session is running on a MacOS operating system.
Sinon, contient $False
.Otherwise contains $False
.
$IsWindows$IsWindows
Contient $TRUE
si la session active est exécutée sur un système d’exploitation Windows.Contains $TRUE
if the current session is running on a Windows operating system. Sinon, contient $FALSE
.Otherwise contains $FALSE
.
$LastExitCode$LastExitCode
Contient le code de sortie du dernier programme Windows exécuté.Contains the exit code of the last Windows-based program that was run.
$Matches$Matches
La Matches
variable fonctionne avec les -match
-notmatch
opérateurs et.The Matches
variable works with the -match
and -notmatch
operators.
Lorsque vous envoyez une entrée scalaire à l' -match
opérateur or et que l’une d’elles -notmatch
détecte une correspondance, elle retourne une valeur booléenne et remplit la $Matches
variable automatique avec une table de hachage de toutes les valeurs de chaîne qui ont été mises en correspondance.When you submit scalar input to the -match
or -notmatch
operator, and either one detects a match, they return a Boolean value and populate the $Matches
automatic variable with a hash table of any string values that were matched. La $Matches
table de hachage peut également être remplie avec des captures lorsque vous utilisez des expressions régulières avec l' -match
opérateur.The $Matches
hash table can also be populated with captures when you use regular expressions with the -match
operator.
Pour plus d’informations sur l' -match
opérateur, consultez about_Comparison_Operators.For more information about the -match
operator, see about_Comparison_Operators. Pour plus d’informations sur les expressions régulières, consultez about_regular_expressions.For more information on regular expressions, see about_Regular_Expressions.
$MyInvocation$MyInvocation
Contient des informations sur la commande actuelle, telles que le nom, les paramètres, les valeurs de paramètre et les informations sur la façon dont la commande a été démarrée, appelée ou appelée, comme le nom du script qui a appelé la commande actuelle.Contains information about the current command, such as the name, parameters, parameter values, and information about how the command was started, called, or invoked, such as the name of the script that called the current command.
$MyInvocation
est renseigné uniquement pour les scripts, les fonctions et les blocs de script.$MyInvocation
is populated only for scripts, function, and script blocks. Vous pouvez utiliser les informations de l’objet System. Management. Automation. InvocationInfo qui $MyInvocation
retourne dans le script actuel, comme le chemin d’accès et le nom de fichier du script ( $MyInvocation.MyCommand.Path
) ou le nom d’une fonction ( $MyInvocation.MyCommand.Name
) pour identifier la commande actuelle.You can use the information in the System.Management.Automation.InvocationInfo object that $MyInvocation
returns in the current script, such as the path and file name of the script ($MyInvocation.MyCommand.Path
) or the name of a function ($MyInvocation.MyCommand.Name
) to identify the current command. Cela s’avère particulièrement utile pour rechercher le nom du script actuel.This is particularly useful for finding the name of the current script.
À compter de PowerShell 3,0, MyInvocation
possède les nouvelles propriétés suivantes.Beginning in PowerShell 3.0, MyInvocation
has the following new properties.
PropriétéProperty | DescriptionDescription |
---|---|
PSScriptRootPSScriptRoot | Contient le chemin d’accès complet au script qui a appeléContains the full path to the script that invoked |
commande actuelle.the current command. La valeur de cette propriété estThe value of this property is | |
renseigné uniquement lorsque l’appelant est un script.populated only when the caller is a script. | |
PSCommandPathPSCommandPath | Contient le chemin d’accès complet et le nom de fichier du scriptContains the full path and file name of the script |
qui a appelé la commande actuelle.that invoked the current command. Valeur de ceThe value of this | |
la propriété est remplie uniquement lorsque l’appelant est unproperty is populated only when the caller is a | |
« Hello world! ».script. |
Contrairement aux $PSScriptRoot
$PSCommandPath
variables automatiques et, les propriétés PSScriptRoot et PSCommandPath de la $MyInvocation
variable automatique contiennent des informations sur le demandeur ou le script appelant, et non sur le script en cours.Unlike the $PSScriptRoot
and $PSCommandPath
automatic variables, the PSScriptRoot and PSCommandPath properties of the $MyInvocation
automatic variable contain information about the invoker or calling script, not the current script.
$NestedPromptLevel$NestedPromptLevel
Contient le niveau d’invite actuel.Contains the current prompt level. La valeur 0 indique le niveau d’invite d’origine.A value of 0 indicates the original prompt level. La valeur est incrémentée lorsque vous entrez un niveau imbriqué et décrémenté lorsque vous la quittez.The value is incremented when you enter a nested level and decremented when you exit it.
Par exemple, PowerShell présente une invite de commandes imbriquée lorsque vous utilisez la $Host.EnterNestedPrompt
méthode.For example, PowerShell presents a nested command prompt when you use the $Host.EnterNestedPrompt
method. PowerShell présente également une invite de commandes imbriquée lorsque vous atteignez un point d’arrêt dans le débogueur PowerShell.PowerShell also presents a nested command prompt when you reach a breakpoint in the PowerShell debugger.
Lorsque vous entrez une invite imbriquée, PowerShell suspend la commande active, enregistre le contexte d’exécution et incrémente la valeur de la $NestedPromptLevel
variable.When you enter a nested prompt, PowerShell pauses the current command, saves the execution context, and increments the value of the $NestedPromptLevel
variable. Pour créer des invites de commandes imbriquées supplémentaires (jusqu’à 128 niveaux) ou pour revenir à l’invite de commandes d’origine, exécutez la commande ou tapez exit
.To create additional nested command prompts (up to 128 levels) or to return to the original command prompt, complete the command, or type exit
.
La $NestedPromptLevel
variable vous aide à suivre le niveau d’invite.The $NestedPromptLevel
variable helps you track the prompt level. Vous pouvez créer une autre invite de commandes PowerShell incluant cette valeur afin qu’elle soit toujours visible.You can create an alternative PowerShell command prompt that includes this value so that it's always visible.
$null$null
$null
variable automatique qui contient une valeur null ou vide.$null
is an automatic variable that contains a null or empty value. Vous pouvez utiliser cette variable pour représenter une valeur absente ou non définie dans les commandes et les scripts.You can use this variable to represent an absent or undefined value in commands and scripts.
PowerShell traite $null
comme un objet avec une valeur, autrement dit comme un espace réservé explicite, afin que vous puissiez utiliser $null
pour représenter une valeur vide dans une série de valeurs.PowerShell treats $null
as an object with a value, that is, as an explicit placeholder, so you can use $null
to represent an empty value in a series of values.
Par exemple, lorsque $null
est inclus dans une collection, il est compté comme l’un des objets.For example, when $null
is included in a collection, it's counted as one of the objects.
$a = "one", $null, "three"
$a.count
3
Si vous dirigez la $null
variable vers l’applet de commande ForEach-Object
, elle génère une valeur pour $null
, comme c’est le cas pour les autres objetsIf you pipe the $null
variable to the ForEach-Object
cmdlet, it generates a value for $null
, just as it does for the other objects
"one", $null, "three" | ForEach-Object { "Hello " + $_}
Hello one
Hello
Hello three
Par conséquent, vous ne pouvez pas utiliser $null
pour signifier qu' aucune valeur de paramètre n' est utilisée.As a result, you can't use $null
to mean no parameter value . Une valeur de paramètre de $null
remplace la valeur de paramètre par défaut.A parameter value of $null
overrides the default parameter value.
Toutefois, étant donné que PowerShell traite la $null
variable comme un espace réservé, vous pouvez l’utiliser dans des scripts comme celui qui suit, ce qui ne fonctionnerait $null
pas si a été ignoré.However, because PowerShell treats the $null
variable as a placeholder, you can use it in scripts like the following one, which wouldn't work if $null
were ignored.
$calendar = @($null, $null, "Meeting", $null, $null, "Team Lunch", $null)
$days = "Sunday","Monday","Tuesday","Wednesday","Thursday",
"Friday","Saturday"
$currentDay = 0
foreach($day in $calendar)
{
if($day -ne $null)
{
"Appointment on $($days[$currentDay]): $day"
}
$currentDay++
}
Appointment on Tuesday: Meeting
Appointment on Friday: Team lunch
$PID$PID
Contient l’identificateur de processus (PID) du processus qui héberge la session PowerShell active.Contains the process identifier (PID) of the process that is hosting the current PowerShell session.
$PROFILE$PROFILE
Contient le chemin d’accès complet du profil PowerShell pour l’utilisateur actuel et l’application hôte actuelle.Contains the full path of the PowerShell profile for the current user and the current host application. Vous pouvez utiliser cette variable pour représenter le profil dans les commandes.You can use this variable to represent the profile in commands. Par exemple, vous pouvez l’utiliser dans une commande pour déterminer si un profil a été créé :For example, you can use it in a command to determine whether a profile has been created:
Test-Path $PROFILE
Ou vous pouvez l’utiliser dans une commande pour créer un profil :Or, you can use it in a command to create a profile:
New-Item -ItemType file -Path $PROFILE -Force
Vous pouvez l’utiliser dans une commande pour ouvrir le profil dans notepad.exe :You can use it in a command to open the profile in notepad.exe :
notepad.exe $PROFILE
$PSBoundParameters$PSBoundParameters
Contient un dictionnaire des paramètres qui sont passés à un script ou une fonction et leurs valeurs actuelles.Contains a dictionary of the parameters that are passed to a script or function and their current values. Cette variable a une valeur uniquement dans une portée où les paramètres sont déclarés, comme un script ou une fonction.This variable has a value only in a scope where parameters are declared, such as a script or function. Vous pouvez l’utiliser pour afficher ou modifier les valeurs actuelles des paramètres ou pour passer des valeurs de paramètres à un autre script ou à une autre fonction.You can use it to display or change the current values of parameters or to pass parameter values to another script or function.
Dans cet exemple, la fonction Test2 passe $PSBoundParameters
à la fonction Test1 .In this example, the Test2 function passes the $PSBoundParameters
to the Test1 function. Les $PSBoundParameters
sont affichés dans le format de la clé et de la valeur .The $PSBoundParameters
are displayed in the format of Key and Value .
function Test1 {
param($a, $b)
# Display the parameters in dictionary format.
$PSBoundParameters
}
function Test2 {
param($a, $b)
# Run the Test1 function with $a and $b.
Test1 @PSBoundParameters
}
Test2 -a Power -b Shell
Key Value
--- -----
a Power
b Shell
$PSCmdlet$PSCmdlet
Contient un objet qui représente l’applet de commande ou la fonction avancée en cours d’exécution.Contains an object that represents the cmdlet or advanced function that's being run.
Vous pouvez utiliser les propriétés et les méthodes de l’objet dans votre applet de commande ou code de fonction pour répondre aux conditions d’utilisation.You can use the properties and methods of the object in your cmdlet or function code to respond to the conditions of use. Par exemple, la propriété ParameterSetName contient le nom du jeu de paramètres en cours d’utilisation, et la méthode ShouldProcess ajoute les paramètres WhatIf et Confirm à l’applet de commande de manière dynamique.For example, the ParameterSetName property contains the name of the parameter set that's being used, and the ShouldProcess method adds the WhatIf and Confirm parameters to the cmdlet dynamically.
Pour plus d’informations sur la $PSCmdlet
variable automatique, consultez about_Functions_CmdletBindingAttribute et about_Functions_Advanced.For more information about the $PSCmdlet
automatic variable, see about_Functions_CmdletBindingAttribute and about_Functions_Advanced.
$PSCommandPath$PSCommandPath
Contient le chemin d’accès complet et le nom de fichier du script en cours d’exécution.Contains the full path and file name of the script that's being run. Cette variable est valide dans tous les scripts.This variable is valid in all scripts.
$PSCulture$PSCulture
À compter de PowerShell 7, $PSCulture
reflète la culture de l’instance d’exécution PowerShell actuelle (session).Beginning in PowerShell 7, $PSCulture
reflects the culture of the current PowerShell runspace (session). Si la culture est modifiée dans une instance d’exécution PowerShell, la $PSCulture
valeur de cette instance d’exécution est mise à jour.If the culture is changed in a PowerShell runspace, the $PSCulture
value for that runspace is updated.
La culture détermine le format d’affichage des éléments, tels que les nombres, les devises et les dates, et est stocké dans un objet System. Globalization. CultureInfo .The culture determines the display format of items such as numbers, currency, and dates, and is stored in a System.Globalization.CultureInfo object. Utilisez Get-Culture
pour afficher la culture de l’ordinateur.Use Get-Culture
to display the computer's culture. $PSCulture
contient la valeur de la propriété Name .$PSCulture
contains the Name property's value.
$PSDebugContext$PSDebugContext
Lors du débogage, cette variable contient des informations sur l’environnement de débogage.While debugging, this variable contains information about the debugging environment. Dans le cas contraire, elle contient une valeur null .Otherwise, it contains a null value. Par conséquent, vous pouvez l’utiliser pour indiquer si le débogueur contrôle.As a result, you can use it to indicate whether the debugger has control. Lorsqu’il est rempli, il contient un objet PSDebugContext qui a des points d’arrêt et des propriétés InvocationInfo .When populated, it contains a PsDebugContext object that has Breakpoints and InvocationInfo properties. La propriété InvocationInfo possède plusieurs propriétés utiles, notamment la propriété location .The InvocationInfo property has several useful properties, including the Location property. La propriété location indique le chemin d’accès du script en cours de débogage.The Location property indicates the path of the script that is being debugged.
$PSHOME$PSHOME
Contient le chemin d’accès complet du répertoire d’installation de PowerShell, en général, $env:windir\System32\PowerShell\v1.0
dans les systèmes Windows.Contains the full path of the installation directory for PowerShell, typically, $env:windir\System32\PowerShell\v1.0
in Windows systems. Vous pouvez utiliser cette variable dans les chemins d’accès des fichiers PowerShell.You can use this variable in the paths of PowerShell files. Par exemple, la commande suivante recherche dans les rubriques d’aide conceptuelle le mot variable :For example, the following command searches the conceptual Help topics for the word variable :
Select-String -Pattern Variable -Path $pshome\*.txt
$PSItem$PSItem
Comme pour $_
.Same as $_
. Contient l’objet actuel dans l’objet de pipeline.Contains the current object in the pipeline object. Vous pouvez utiliser cette variable dans les commandes qui exécutent une action sur chaque objet ou sur les objets sélectionnés dans un pipeline.You can use this variable in commands that perform an action on every object or on selected objects in a pipeline.
$PSScriptRoot$PSScriptRoot
Contient le répertoire à partir duquel un script est en cours d’exécution.Contains the directory from which a script is being run.
Dans PowerShell 2,0, cette variable est valide uniquement dans les modules de script ( .psm1
).In PowerShell 2.0, this variable is valid only in script modules (.psm1
).
À compter de PowerShell 3,0, il est valide dans tous les scripts.Beginning in PowerShell 3.0, it's valid in all scripts.
$PSSenderInfo$PSSenderInfo
Contient des informations sur l’utilisateur qui a démarré la session PSSession, y compris l’identité de l’utilisateur et le fuseau horaire de l’ordinateur d’origine.Contains information about the user who started the PSSession, including the user identity and the time zone of the originating computer. Cette variable est disponible uniquement dans sessions PSSession.This variable is available only in PSSessions.
La $PSSenderInfo
variable inclut une propriété configurable par l’utilisateur, ApplicationArguments , qui, par défaut, contient uniquement le $PSVersionTable
de la session d’origine.The $PSSenderInfo
variable includes a user-configurable property, ApplicationArguments , that by default, contains only the $PSVersionTable
from the originating session. Pour ajouter des données à la propriété ApplicationArguments , utilisez le paramètre ApplicationArguments de l’applet de commande New-PSSessionOption
.To add data to the ApplicationArguments property, use the ApplicationArguments parameter of the New-PSSessionOption
cmdlet.
$PSUICulture$PSUICulture
Contient le nom de la culture de l’interface utilisateur qui est actuellement utilisée dans le système d’exploitation.Contains the name of the user interface (UI) culture that's currently in use in the operating system. La culture d'interface utilisateur détermine les chaînes de texte utilisées pour les éléments d'interface utilisateur, tels que les menus et les messages.The UI culture determines which text strings are used for user interface elements, such as menus and messages. Il s’agit de la valeur de la propriété System.Globalization.CultureInfo.CurrentUICulture.Name du système.This is the value of the System.Globalization.CultureInfo.CurrentUICulture.Name property of the system. Pour obtenir l’objet System. Globalization. CultureInfo du système, utilisez l' Get-UICulture
applet de commande.To get the System.Globalization.CultureInfo object for the system, use the Get-UICulture
cmdlet.
$PSVersionTable$PSVersionTable
Contient une table de hachage en lecture seule qui affiche des détails sur la version de PowerShell en cours d’exécution dans la session active.Contains a read-only hash table that displays details about the version of PowerShell that is running in the current session. Le tableau comprend les éléments suivants :The table includes the following items:
PropriétéProperty | DescriptionDescription |
---|---|
PSVersionPSVersion | Numéro de version de PowerShellThe PowerShell version number |
PSEditionPSEdition | Cette propriété a la valeur « Desktop » pourThis property has the value of 'Desktop' for |
PowerShell 4 et versions antérieures, ainsi que PowerShellPowerShell 4 and below as well as PowerShell | |
5,1 sur les éditions Windows complètes.5.1 on full-featured Windows editions. | |
Cette propriété a la valeur « Core » pourThis property has the value of 'Core' for | |
PowerShell 6 et versions ultérieures, ainsi que PowerShellPowerShell 6 and above as well as PowerShell | |
PowerShell 5,1 sur les éditions à encombrement réduitPowerShell 5.1 on reduced-footprint editions | |
comme Windows nano Server ou Windows IoT.like Windows Nano Server or Windows IoT. | |
GitCommitIdGitCommitId | ID de validation des fichiers sources, dans GitHub,The commit Id of the source files, in GitHub, |
SEOS | Description du système d’exploitation quiDescription of the operating system that |
PowerShell est en cours d’exécution sur.PowerShell is running on. | |
PlateformePlatform | Plateforme exécutée par le système d’exploitationPlatform that the operating system is running |
Activé.on. La valeur sur Linux et macOS est UNIX .The value on Linux and macOS is Unix . | |
Localisez $IsMacOs et $IsLinux .See $IsMacOs and $IsLinux . |
|
PSCompatibleVersionsPSCompatibleVersions | Versions de PowerShell compatiblesVersions of PowerShell that are compatible |
avec la version actuellewith the current version | |
PSRemotingProtocolVersionPSRemotingProtocolVersion | Version de PowerShell à distanceThe version of the PowerShell remote |
Protocole de gestion.management protocol. | |
SerializationVersionSerializationVersion | Version de la méthode de sérialisationThe version of the serialization method |
WSManStackVersionWSManStackVersion | Numéro de version de la pile de WS-ManagementThe version number of the WS-Management stack |
$PWD$PWD
Contient un objet de chemin d’accès qui représente le chemin d’accès complet du répertoire actif.Contains a path object that represents the full path of the current directory.
$Sender$Sender
Contient l’objet qui a généré cet événement.Contains the object that generated this event. Cette variable est remplie uniquement dans le bloc d’action d’une commande d’inscription d’événement.This variable is populated only within the Action block of an event registration command. La valeur de cette variable peut également se trouver dans la propriété sender de l’objet PSEventArgs qui Get-Event
retourne.The value of this variable can also be found in the Sender property of the PSEventArgs object that Get-Event
returns.
$ShellId$ShellId
Contient l’identificateur de l’interpréteur de commandes actuel.Contains the identifier of the current shell.
$StackTrace$StackTrace
Contient une trace de la pile de l’erreur la plus récente.Contains a stack trace for the most recent error.
$switch$switch
Contient l’énumérateur qui ne correspond pas aux valeurs résultantes d’une Switch
instruction.Contains the enumerator not the resulting values of a Switch
statement. La $switch
variable existe uniquement lorsque l' Switch
instruction est en cours d’exécution ; elle est supprimée à la fin de l’exécution de l' switch
instruction.The $switch
variable exists only while the Switch
statement is running; it's deleted when the switch
statement completes execution. Pour plus d’informations, consultez about_Switch.For more information, see about_Switch.
Les énumérateurs contiennent des propriétés et des méthodes que vous pouvez utiliser pour récupérer des valeurs de boucle et modifier l’itération de boucle actuelle.Enumerators contain properties and methods you can use to retrieve loop values and change the current loop iteration. Pour plus d’informations, consultez utilisation d’énumérateurs.For more information, see Using Enumerators.
$this$this
Dans un bloc de script qui définit une propriété de script ou une méthode de script, la $this
variable fait référence à l’objet qui est étendu.In a script block that defines a script property or script method, the $this
variable refers to the object that is being extended.
Dans une classe personnalisée, la $this
variable fait référence à l’objet de classe lui-même autorisant l’accès aux propriétés et méthodes définies dans la classe.In a custom class, the $this
variable refers to the class object itself allowing access to properties and methods defined in the class.
$true$true
Contient la valeur true .Contains True . Vous pouvez utiliser cette variable pour représenter la valeur true dans les commandes et les scripts.You can use this variable to represent True in commands and scripts.
Utilisation d’énumérateursUsing Enumerators
Les $input
$foreach
variables, et $switch
sont tous des énumérateurs utilisés pour itérer au sein des valeurs traitées par leur bloc de code conteneur.The $input
, $foreach
, and $switch
variables are all enumerators used to iterate through the values processed by their containing code block.
Un énumérateur contient des propriétés et des méthodes que vous pouvez utiliser pour avancer ou réinitialiser une itération, ou pour récupérer des valeurs d’itération.An enumerator contains properties and methods you can use to advance or reset iteration, or retrieve iteration values. La manipulation directe d’énumérateurs n’est pas considérée comme meilleure pratique.Directly manipulating enumerators isn't considered best practice.
Dans les boucles, les mots clés de contrôle de workflow break et continue doivent être préférés.Within loops, flow control keywords break and continue should be preferred.
Dans les fonctions qui acceptent l’entrée de pipeline, il est recommandé d’utiliser des paramètres avec les attributs ValueFromPipeline ou ValueFromPipelineByPropertyName .Within functions that accept pipeline input, it's best practice to use Parameters with the ValueFromPipeline or ValueFromPipelineByPropertyName attributes.
Pour plus d’informations, consultez about_Functions_Advanced_Parameters.For more information, see about_Functions_Advanced_Parameters.
MoveNextMoveNext
La méthode MoveNext avance l’énumérateur à l’élément suivant de la collection.The MoveNext method advances the enumerator to the next element of the collection. MoveNext retourne true si l’énumérateur a été avancé avec succès, false si l’énumérateur a dépassé la fin de la collection.MoveNext returns True if the enumerator was successfully advanced, False if the enumerator has passed the end of the collection.
Notes
La valeur booléenne retournée par mon MoveNext est envoyée au flux de sortie.The Boolean value returned my MoveNext is sent to the output stream.
Vous pouvez supprimer la sortie en la cast ou en la [void]
canalisant vers out-NULL.You can suppress the output by typecasting it to [void]
or piping it to Out-Null.
$input.MoveNext() | Out-Null
[void]$input.MoveNext()
RéinitialiserReset
La méthode Reset affecte à l’énumérateur sa position initiale, qui précède le premier élément de la collection.The Reset method sets the enumerator to its initial position, which is before the first element in the collection.
ActuelCurrent
La propriété actuelle obtient l’élément dans la collection, ou le pipeline, à la position actuelle de l’énumérateur.The Current property gets the element in the collection, or pipeline, at the current position of the enumerator.
La propriété actuelle continue à retourner la même propriété jusqu’à ce que MoveNext soit appelé.The Current property continues to return the same property until MoveNext is called.
ExemplesExamples
Exemple 1 : utilisation de la variable $inputExample 1: Using the $input variable
Dans l’exemple suivant, l’accès à la $input
variable efface la variable jusqu’à la prochaine exécution du bloc de processus.In the following example, accessing the $input
variable clears the variable until the next time the process block executes. L’utilisation de la méthode Reset réinitialise la $input
variable à la valeur de pipeline actuelle.Using the Reset method resets the $input
variable to the current pipeline value.
function Test
{
begin
{
$i = 0
}
process
{
"Iteration: $i"
$i++
"`tInput: $input"
"`tAccess Again: $input"
$input.Reset()
"`tAfter Reset: $input"
}
}
"one","two" | Test
Iteration: 0
Input: one
Access Again:
After Reset: one
Iteration: 1
Input: two
Access Again:
After Reset: two
Le bloc de processus avance automatiquement la $input
variable même si vous n’y accédez pas.The process block automatically advances the $input
variable even if you don't access it.
$skip = $true
function Skip
{
begin
{
$i = 0
}
process
{
"Iteration: $i"
$i++
if ($skip)
{
"`tSkipping"
$skip = $false
}
else
{
"`tInput: $input"
}
}
}
"one","two" | Skip
Iteration: 0
Skipping
Iteration: 1
Input: two
Exemple 2 : utilisation de $input en dehors du bloc ProcessExample 2: Using $input outside the process block
En dehors du bloc de processus $input
, la variable représente toutes les valeurs redirigées dans la fonction.Outside of the process block the $input
variable represents all the values piped into the function.
- L’accès à la
$input
variable efface toutes les valeurs.Accessing the$input
variable clears all values. - La méthode Reset réinitialise l’ensemble de la collection.The Reset method resets the entire collection.
- La propriété actuelle n’est jamais remplie.The Current property is never populated.
- La méthode MoveNext retourne la valeur false, car la collection ne peut pas être avancée.The MoveNext method returns false because the collection can't be advanced.
- L’appel de MoveNext efface la
$input
variable.Calling MoveNext clears out the$input
variable.
- L’appel de MoveNext efface la
Function All
{
"All Values: $input"
"Access Again: $input"
$input.Reset()
"After Reset: $input"
$input.MoveNext() | Out-Null
"After MoveNext: $input"
}
"one","two","three" | All
All Values: one two three
Access Again:
After Reset: one two three
After MoveNext:
Exemple 3 : utilisation de l' $input. Propriété actuelleExample 3: Using the $input.Current property
À l’aide de la propriété Current , la valeur de pipeline actuelle est accessible plusieurs fois sans utiliser la méthode Reset .By using the Current property, the current pipeline value can be accessed multiple times without using the Reset method. Le bloc Process n’appelle pas automatiquement la méthode MoveNext .The process block doesn't automatically call the MoveNext method.
La propriété actuelle ne sera jamais remplie, sauf si vous appelez explicitement MoveNext .The Current property will never be populated unless you explicitly call MoveNext . La propriété actuelle est accessible plusieurs fois dans le bloc de processus sans effacer sa valeur.The Current property can be accessed multiple times inside the process block without clearing its value.
function Current
{
begin
{
$i = 0
}
process
{
"Iteration: $i"
$i++
"`tBefore MoveNext: $($input.Current)"
$input.MoveNext() | Out-Null
"`tAfter MoveNext: $($input.Current)"
"`tAccess Again: $($input.Current)"
}
}
"one","two" | Current
Iteration: 0
Before MoveNext:
After MoveNext: one
Access Again: one
Iteration: 1
Before MoveNext:
After MoveNext: two
Access Again: two
Exemple 4 : utilisation de la variable $foreachExample 4: Using the $foreach variable
Contrairement $input
à la variable, la $foreach
variable représente toujours tous les éléments de la collection lorsque vous y accédez directement.Unlike the $input
variable, the $foreach
variable always represents all items in the collection when accessed directly. Utilisez la propriété Current pour accéder à l’élément de collection actuel, et les méthodes Reset et MoveNext pour modifier sa valeur.Use the Current property to access the current collection element, and the Reset and MoveNext methods to change its value.
Notes
Chaque itération de la foreach
boucle appellera automatiquement la méthode MoveNext .Each iteration of the foreach
loop will automatically call the MoveNext method.
La boucle suivante s’exécute deux fois seulement.The following loop only executes twice. Dans la deuxième itération, la collection est déplacée vers le troisième élément avant la fin de l’itération.In the second iteration, the collection is moved to the third element before the iteration is complete. Après la deuxième itération, il n’y a plus aucune valeur à itérer, et la boucle se termine.After the second iteration, there are now no more values to iterate, and the loop terminates.
La propriété MoveNext n’affecte pas la variable choisie pour itérer au sein de la collection ( $Num
).The MoveNext property doesn't affect the variable chosen to iterate through the collection ($Num
).
$i = 0
foreach ($num in ("one","two","three"))
{
"Iteration: $i"
$i++
"`tNum: $num"
"`tCurrent: $($foreach.Current)"
if ($foreach.Current -eq "two")
{
"Before MoveNext (Current): $($foreach.Current)"
$foreach.MoveNext() | Out-Null
"After MoveNext (Current): $($foreach.Current)"
"Num has not changed: $num"
}
}
Iteration: 0
Num: one
Current: one
Iteration: 1
Num: two
Current: two
Before MoveNext (Current): two
After MoveNext (Current): three
Num has not changed: two
L’utilisation de la méthode Reset réinitialise l’élément actuel dans la collection.Using the Reset method resets the current element in the collection. L’exemple suivant effectue une boucle à deux reprises sur les deux premiers éléments, car la méthode de réinitialisation est appelée.The following example loops through the first two elements twice because the Reset method is called. Après les deux premières boucles, l' if
instruction échoue et la boucle itère les trois éléments normalement.After the first two loops, the if
statement fails and the loop iterates through all three elements normally.
Important
Cela peut entraîner une boucle infinie.This could result in an infinite loop.
$stopLoop = 0
foreach ($num in ("one","two", "three"))
{
("`t" * $stopLoop) + "Current: $($foreach.Current)"
if ($num -eq "two" -and $stopLoop -lt 2)
{
$foreach.Reset() | Out-Null
("`t" * $stopLoop) + "Reset Loop: $stopLoop"
$stopLoop++
}
}
Current: one
Current: two
Reset Loop: 0
Current: one
Current: two
Reset Loop: 1
Current: one
Current: two
Current: three
Exemple 5 : utilisation de la variable $switchExample 5: Using the $switch variable
La $switch
variable a exactement les mêmes règles que la $foreach
variable.The $switch
variable has the exact same rules as the $foreach
variable.
L’exemple suivant illustre tous les concepts de l’énumérateur.The following example demonstrates all the enumerator concepts.
Notes
Notez que le cas NotEvaluated n’est jamais exécuté, même s’il n’y a pas d' break
instruction après la méthode MoveNext .Note how the NotEvaluated case is never executed, even though there's no break
statement after the MoveNext method.
$values = "Start", "MoveNext", "NotEvaluated", "Reset", "End"
$stopInfinite = $false
switch ($values)
{
"MoveNext" {
"`tMoveNext"
$switch.MoveNext() | Out-Null
"`tAfter MoveNext: $($switch.Current)"
}
# This case is never evaluated.
"NotEvaluated" {
"`tAfterMoveNext: $($switch.Current)"
}
"Reset" {
if (!$stopInfinite)
{
"`tReset"
$switch.Reset()
$stopInfinite = $true
}
}
default {
"Default (Current): $($switch.Current)"
}
}
Default (Current): Start
MoveNext
After MoveNext: NotEvaluated
Reset
Default (Current): Start
MoveNext
After MoveNext: NotEvaluated
Default (Current): End
Voir aussiSee also
about_Functionsabout_Functions
about_Functions_Advancedabout_Functions_Advanced
about_Functions_Advanced_Methodsabout_Functions_Advanced_Methods
about_Functions_Advanced_Parametersabout_Functions_Advanced_Parameters
about_Functions_OutputTypeAttributeabout_Functions_OutputTypeAttribute
about_Functions_CmdletBindingAttributeabout_Functions_CmdletBindingAttribute
about_Hash_Tablesabout_Hash_Tables
about_Preference_Variablesabout_Preference_Variables