Setting variables in PowerShell itself is trivial, merely assign (= operator) to the variable:

$VarName = 42

But likely the question is looking for a way to set Environment variables which the (VSTS) application can 'see' and 'use' when it is called from PowerShell.

To assign to any session Environment variable prefix the name with "ENV" so it looks like this:

$Env:VarName = 4201

This will remain for the current PowerShell session or life of the console -- other sessions in other windows or run later will not see or be affected by such settings.

If you wish to have a persistent Environment variable then you must set that in the registry, either for the User (HKey_Local_User) or Computer (Hkey_Local_Machine).

These will get the environment settings from the registry (maybe be different that currently set in your process):

[Environment]::GetEnvironmentVariable('path',[EnvironmentVariableTarget]::Machine)
[Environment]::GetEnvironmentVariable('path',[EnvironmentVariableTarget]::User)

And the Set commands are similar but include the new value (e.g., variable 'Tools' is set to 'C:\':

[Environment]::SetEnvironmentVariable('Tools', 'C:\', [EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable('Tools', 'C:\', [EnvironmentVariableTarget]::User)

There is also a "location" enumeration for "Process" (instead of User or Machine) but it is simpler to set this using the PowerShell $Env:VariableName shown above.

    [Environment]::SetEnvironmentVariable('Tools', 'C:\', [EnvironmentVariableTarget]::Process)
Answer from HerbM on Stack Overflow
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.utility › set-variable
Set-Variable (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Learn
The Set-Variable cmdlet assigns a value to a specified variable or changes the current value. If the variable does not exist, the cmdlet creates it.
Top answer
1 of 5
8

Setting variables in PowerShell itself is trivial, merely assign (= operator) to the variable:

$VarName = 42

But likely the question is looking for a way to set Environment variables which the (VSTS) application can 'see' and 'use' when it is called from PowerShell.

To assign to any session Environment variable prefix the name with "ENV" so it looks like this:

$Env:VarName = 4201

This will remain for the current PowerShell session or life of the console -- other sessions in other windows or run later will not see or be affected by such settings.

If you wish to have a persistent Environment variable then you must set that in the registry, either for the User (HKey_Local_User) or Computer (Hkey_Local_Machine).

These will get the environment settings from the registry (maybe be different that currently set in your process):

[Environment]::GetEnvironmentVariable('path',[EnvironmentVariableTarget]::Machine)
[Environment]::GetEnvironmentVariable('path',[EnvironmentVariableTarget]::User)

And the Set commands are similar but include the new value (e.g., variable 'Tools' is set to 'C:\':

[Environment]::SetEnvironmentVariable('Tools', 'C:\', [EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable('Tools', 'C:\', [EnvironmentVariableTarget]::User)

There is also a "location" enumeration for "Process" (instead of User or Machine) but it is simpler to set this using the PowerShell $Env:VariableName shown above.

    [Environment]::SetEnvironmentVariable('Tools', 'C:\', [EnvironmentVariableTarget]::Process)
2 of 5
7

You need to use Write-Host with a special string format:

Write-Host "##vso[task.setvariable variable=YourVSTSVariableName]$yourPowershellVariable"

Discussions

Setting local variables in Powershell/CMD
in cmd c:\>set var1 = 777 reference it c:\>echo %var1% In PowerShell PS c:\> $var1 = 777 reference it PS c:\> Write-Host $var1 More on reddit.com
🌐 r/sysadmin
6
0
February 16, 2022
azure devops - How do you set a variables in powershell - Stack Overflow
I am trying to set variables in a PowerShell so I can use them in custom conditions in a release definitions, so i can prevent phases from running is a VSTS variable is set to false or 0 More on stackoverflow.com
🌐 stackoverflow.com
In Powershell, how to set variable values within a function and have that value available in the parent scope? - Stack Overflow
I am trying to set the values for some variables using a function. My code is below: $BackupFile = $null $TaskSequenceID = $null $OSDComputerName = $null $capturedWimPath = $null Function Set-OsT... More on stackoverflow.com
🌐 stackoverflow.com
I want to define a variable but not call it right away
Declare your variables? To create a new variable, use an assignment statement to assign a value to the variable. You don't have to declare the variable before using it. That said, you should declare your variables in as narrow scope as possible. So if the variable is ONLY used in a function, it should be declared at the top of that function. More on reddit.com
🌐 r/PowerShell
6
8
March 18, 2021
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_variables
about_Variables - PowerShell | Microsoft Learn
For example, to get the $PSCulture automatic variable, use the following command. ... You can prefix a provider path with the dollar ($) sign, and access the content of any provider that implements the IContentCmdletProvider interface. The following built-in PowerShell providers support this notation: ... PowerShell includes a set of cmdlets that are designed to manage variables.
🌐
SharePoint Diary
sharepointdiary.com › sharepoint diary › powershell › powershell tutorials › set variables in powershell: a quick guide
Set Variables in PowerShell: A Quick Guide - SharePoint Diary
October 9, 2025 - The Set-Variable cmdlet is a built-in PowerShell command that allows you to create new variables, change the value of existing ones, and control the scope and visibility of variables.
🌐
Netwrix
netwrix.com › en › resources › blog › powershell-variables-and-arrays
How to Use PowerShell Variables
August 26, 2025 - PowerShell variables have a Description property that you can set using the Set-Variable cmdlet with the Description parameter:
🌐
PDQ
pdq.com › powershell › set-variable
Set-Variable - PowerShell Command | PDQ
This command creates a global, read-only variable that contains all processes on the system, and then it displays all properties of the variable. The command uses the Set-Variable cmdlet to create the variable. It uses the PassThru parameter to create an object representing the new variable, ...
Find elsewhere
🌐
Ironman Software
blog.ironmansoftware.com › daily-powershell › assign-powershell-variables
Assign Variables in PowerShell
November 22, 2021 - You can also use curly braces and the $ prefix to reference variables with characters such as spaces. Set-Variable -Name 'This is a variable with spaces' -Value 123 ${This is a variable with spaces} = 123
🌐
Reddit
reddit.com › r/sysadmin › setting local variables in powershell/cmd
r/sysadmin on Reddit: Setting local variables in Powershell/CMD
February 16, 2022 -

Trying to get a quick script that would determine if a specific system process is running.

I am running into an issue where I cannot set a local variable.

C:\WINDOWS\system32>var1 = 777

'var1' is not recognized as an internal or external command, operable program or batch file.

This seems to be an issue with more than one of our endpoints. Is there a way to fix this issue using the terminal?

Top answer
1 of 4
9

Setting variables in PowerShell itself is trivial, merely assign (= operator) to the variable:

$VarName = 42

But likely the question is looking for a way to set Environment variables which the (VSTS) application can 'see' and 'use' when it is called from PowerShell.

To assign to any session Environment variable prefix the name with "ENV" so it looks like this:

$Env:VarName = 4201

This will remain for the current PowerShell session or life of the console -- other sessions in other windows or run later will not see or be affected by such settings.

If you wish to have a persistent Environment variable then you must set that in the registry, either for the User (HKey_Local_User) or Computer (Hkey_Local_Machine).

These will get the environment settings from the registry (maybe be different that currently set in your process):

[Environment]::GetEnvironmentVariable('path',[EnvironmentVariableTarget]::Machine)
[Environment]::GetEnvironmentVariable('path',[EnvironmentVariableTarget]::User)

And the Set commands are similar but include the new value (e.g., variable 'Tools' is set to 'C:\':

[Environment]::SetEnvironmentVariable('Tools', 'C:\', [EnvironmentVariableTarget]::Machine)
[Environment]::SetEnvironmentVariable('Tools', 'C:\', [EnvironmentVariableTarget]::User)

There is also a "location" enumeration for "Process" (instead of User or Machine) but it is simpler to set this using the PowerShell $Env:VariableName shown above.

    [Environment]::SetEnvironmentVariable('Tools', 'C:\', [EnvironmentVariableTarget]::Process)
2 of 4
7

You need to use Write-Host with a special string format:

Write-Host "##vso[task.setvariable variable=YourVSTSVariableName]$yourPowershellVariable"

Top answer
1 of 6
10

When defining variables in PowerShell, single quotes (') mean you want the literal version of the string. Use double-quotes (") if you want to allow variable expansion:

PS C:\> $a = "hello"
PS C:\> $a
hello
PS C:\> $b = "$a world!"
PS C:\> $b
hello world!

More info:

  • Single Quotes vs. Double Quotes in PowerShell: What's the Difference?
  • Referencing Variables and Variable Values

Edit after comments:

For your example where you're pulling the line from a file, that's a little trickier since it's pulling the line as a literal string.

The easiest way (IMO) would be to use the Replace method; something like:

$selHost = (get-content c:\scripts\hosts.txt)[0]
$a = ((get-content c:\scripts\config.txt)[1]).replace('$selhost', $selHost)
2 of 6
2

When you read a string that contains a variable name out of a file and into a variable, you are going to need something other than double quotes to cause string expansion. There is a tool that's relevant here. It's called ExpandString. Take a look at this sample code:

$selhost = 'spr-it-minion'

$b = '$selhost is offline!'
$c = $ExecutionContext.InvokeCommand.ExpandString($b)

$c

What's going on here is that first I have given $selhost and $b literal values, similar to the ones you would read out of the files you are using. Of course, $b isn't right, because the reference to $selhost isn't resolved, as outlined in the accepted answer. But $c gets the value produced by expanding $selhost, which you can use in your output.

I'll leave applying this to your case as a coding exercise.

🌐
LazyAdmin
lazyadmin.nl › home › how to use powershell variables
How to use PowerShell Variables — LazyAdmin
January 18, 2024 - It’s also possible to create a variable in PowerShell without specifying any value, even not $null. For this, you will have to use the cmdlet Set-Variable, which creates the variable with the value $null for you.
🌐
GitHub
github.com › MicrosoftDocs › PowerShell-Docs › blob › main › reference › 7.5 › Microsoft.PowerShell.Utility › Set-Variable.md
PowerShell-Docs/reference/7.5/Microsoft.PowerShell.Utility/Set-Variable.md at main · MicrosoftDocs/PowerShell-Docs
This example creates a global, read-only variable that contains all processes on the system, and then it displays all properties of the variable. Set-Variable -Name "processes" -Value (Get-Process) -Option Constant -Scope Global -Description "All processes" -PassThru | Format-List -Property *
Author   MicrosoftDocs
🌐
Petri
petri.com › home › powershell set environment variable – a step-by-step guide
PowerShell Set Environment Variable - A Step-By-Step Guide | Petri
May 5, 2025 - One of the easiest ways to add or append an environment variable using PowerShell is to use $Env to set an environment variable using the assignment operator (=) and to append or create a new environment variable using the (+=) operator.
🌐
Codecademy
codecademy.com › docs › powershell › variables
PowerShell | Variables | Codecademy
June 8, 2023 - Variables in PowerShell are referenced using a dollar sign $ followed by a valid variable name.
Top answer
1 of 3
24

The variables are created in your function's local-scope. Those variables are deleted when your function is done.

Global: 
    The scope that is in effect when Windows PowerShell
    starts. Variables and functions that are present when
    Windows PowerShell starts have been created in the
    global scope. This includes automatic variables and
    preference variables. This also includes the variables, aliases,
    and functions that are in your Windows PowerShell
    profiles.

Local:  
    The current scope. The local scope can be the global 
    scope or any other scope. 

Script: 
    The scope that is created while a script file runs. Only
    the commands in the script run in the script scope. To
    the commands in a script, the script scope is the local
    scope.

Source: about_Scopes

If you need the variables to be available for the script, then write them to the script scope.

$BackupFile = $null
$TaskSequenceID = $null
$OSDComputerName = $null
$capturedWimPath = $null

Function Set-OsToBuild 
{
  switch ($OsToBuild)
  {
    "Win7x64"
        { 
            $script:BackupFile = "Win7x64-SP1.wim"
            $script:TaskSequenceID = "WIN7X64BC"
            $script:OSDComputerName = "Ref-Win7x64"
            $script:capturedWimPath = "$($PathToMdtShare)\Captures\$BackupFile"
        }
  }
}

If you would like to keep the values for whole sessions (until you close the powershell-process), then you should use the global scope.

$global:BackupFile = $null
$global:TaskSequenceID = $null
$global:OSDComputerName = $null
$global:capturedWimPath = $null

Function Set-OsToBuild 
{
  switch ($OsToBuild)
  {
    "Win7x64"
        { 
            $global:BackupFile = "Win7x64-SP1.wim"
            $global:TaskSequenceID = "WIN7X64BC"
            $global:OSDComputerName = "Ref-Win7x64"
            $global:capturedWimPath = "$($PathToMdtShare)\Captures\$BackupFile"
        }
  }
}
2 of 3
7

The powershell about_scope help document is what you want to read for this.

Specifically this section:

Windows PowerShell Scopes

Scopes in Windows PowerShell have both names and numbers. The named
scopes specify an absolute scope. The numbers are relative and reflect
the relationship between scopes.


Global: 
    The scope that is in effect when Windows PowerShell
    starts. Variables and functions that are present when
    Windows PowerShell starts have been created in the
    global scope. This includes automatic variables and
    preference variables. This also includes the variables, aliases,
    and functions that are in your Windows PowerShell
    profiles. 

Local:  
    The current scope. The local scope can be the global 
    scope or any other scope. 

Script: 
    The scope that is created while a script file runs. Only
    the commands in the script run in the script scope. To
    the commands in a script, the script scope is the local
    scope.

Private:
    Items in private scope cannot be seen outside of the current
    scope. You can use private scope to create a private version
    of an item with the same name in another scope.        


Numbered Scopes:
    You can refer to scopes by name or by a number that
    describes the relative position of one scope to another.
    Scope 0 represents the current, or local, scope. Scope 1
    indicates the immediate parent scope. Scope 2 indicates the
    parent of the parent scope, and so on. Numbered scopes
    are useful if you have created many recursive
    scopes.

So depending on your exact needs you could use any one of the following I believe.

  1. $global:BackupFile = "Win7x64-SP1.wim"
  2. $script:BackupFile = "Win7x64-SP1.wim"
  3. $1:BackupFile = "Win7x64-SP1.wim"
🌐
Reddit
reddit.com › r/powershell › i want to define a variable but not call it right away
r/PowerShell on Reddit: I want to define a variable but not call it right away
March 18, 2021 -

Hopefully this isnt a silly question.

Basically I'm trying to write this script to search the directory for a folder, move it to an archive, create a new folder based on deployment number, and copy over files from various locations. The problem I'm running into is I've defined my variables at the start and it looks like theyre being called when theyre being set. Is it bad practice to set variables like that at the start? I can shift the order around but I wanted to check on this.

[CmdletBinding()]
param
(
	$deploymentNumber = ""
)

#Variables defined

$deploymentNumber = Read-Host "Enter Deployment Number"
$f = New-Item -path ".\z_PRE_Deployment_$($deploymentNumber)" -ItemType Directory -Force
$oldBackup = Test-path '.\z_PRE_Deployment*'
$copy1 = copy-item -path "C:\Users\michael\Documents\PA Flow Backups\*" -destination $f.FullName -recurse

#Check in folder for previous backups and move them to an archive folder before proceeding

if (Test-path '.\z_PRE_Deployment*') {
#	write-verbose "Searching for previous deployment folder..."
#       gci '.\z_PRE_Deployment*' | Move-Item -destination '.\z_Archive'
#	write-verbose "Moving previous deployment folder to archive..." 
"true"
} else {
#	write-verbose "Previous deployment backup not found..."
#	write-verbose "Creating new folder for deployment $deploymentNumber..."
"false"
}

#       $f 
#	write-verbose "Creating new folder for deployment '$deploymentNumber'..."
#	write-verbose "Folder created successfully..."
#       write-verbose "Copying backup files..."
#       $copy1
🌐
Broadcom
knowledge.broadcom.com › external › article › 188030 › setting-a-variable-in-a-powershell-scrip.html
Setting a variable in a PowerShell script and passing the value to the next job.
October 11, 2023 - /*USEVAR - job retrieves the value and passes it as an argument into the /* script DATA_OBJECT DATA1 SETVAR MYVAR='DUMMY' ENDJOB NT_JOB SETVAR RUN ANY AGENT MYAGENT CMDNAME C:\WINDOWS\SYSTEM32\WINDOWSPOWERSHELL\V1.0\POWERSHELL.EXE ARGS C:\Users\Administrator\Documents\Scripts\ESPMGR.ps1 - "%ESPAPPL..%ESPAPGEN" EXITCODE 5 FAILURE RELEASE USEVAR ENDJOB NT_JOB USEVAR VALUE = WOBDATA('DATA1','MYVAR') RUN ANY AGENT MYAGENT CMDNAME C:\WINDOWS\SYSTEM32\WINDOWSPOWERSHELL\V1.0\POWERSHELL.EXE ARGS /C C:\Users\Administrator\Documents\Scripts\test_args.ps1 - %VALUE ENDJOB *********************************