Set-Variable
Use Set-Variable to create or change a variable, with control over its scope and options.
Documentation: Microsoft Learn — Set-Variable
Syntax
See the command anatomy
Read the command and its supplied arguments. This example requires real PowerShell or its module; this diagram does not execute it.
Set-Variable [-Name] <String[]> [[-Value] <object>] [-Description <String>] [-Option <ScopedItemOptions>] [-Force] [-Scope <String>] [-PassThru] [<CommonParameters>]- Stage 1Set-Variable
-Name -Value -Description -Option -Force -Scope -PassThru
Try it
PowerShell example · browser support is limited.
Execution scope: The full example below requires PowerShell outside this browser. You can edit this runner to use the supported practice commands; unsupported syntax returns an explanation.
Follow the objects
Run the command to inspect each stage.
Examples
Set-Variable -Name retryCount
Show reference output
Sample output · fictional data, shaped like the real thing
Name Value ---- ----- retryCount 3
Set-Variable -Name maxSize
Show reference output
Sample output · fictional data, shaped like the real thing
Name Value Options ---- ----- ------- maxSize 100 ReadOnly
Set-Variable -Name logPath
Show reference output
Sample output · fictional data, shaped like the real thing
Name Description ---- ----------- logPath where this script writes
Parameters
Parameter definitions:
-Name-Value-Description-Option-Force-Scope-PassThru
Practical use and troubleshooting
Practical scenario: Use Set-Variable when you need to create or change a variable, with control over its scope and options. Start with one identified target and inspect the returned values before extending the operation to a list. Keep the identity in your report so you can trace each result back to the object or path that produced it.
Common error and fix: A read-only or constant variable can reject assignment. Inspect its Options first and use a new variable name when the existing binding is not intended to change. In an unattended script, capture this failure with its original error record and record which target failed. An empty result and an unsuccessful query must remain distinguishable in the final report.
See also: Get-Variable. Get-Variable reads variable metadata or values; Set-Variable assigns or changes a variable. Choose the scope deliberately when a function and its caller use the same variable name. Read the linked command before substituting it; similar names do not imply identical inputs or output.
Recap
Set-Variable Use Set-Variable to create or change a variable, with control over its scope and options.
Next: Get-Variable