Write-Host "assoc.Id) - assoc.Name) - assoc.Owner)"

See the Windows PowerShell Language Specification Version 3.0, p25, sub-expressions expansion.

Answer from David Brabant on Stack Overflow
Discussions

How to pass the string from variable instead using it as parameter
Hello. How do I make line 2 work so that it extracts the string from $a and uses it in the command instead of trying to find a user with identity $a? $a = “-filter *” get-aduser $a And how is this called? I could not search for help because I do not know how it is called. Thank you Honza More on forums.powershell.org
🌐 forums.powershell.org
5
0
March 28, 2023
powershell - Setting a (string) variable equal to another (string) variable including modifications - Stack Overflow
I'm trying to get better at reusable PowerShell (v5.1, but v-agnostic) scripting at scale with libraries, and I have a very simple task I'll use for illustration. Coming from C# the pseudocode to c... More on stackoverflow.com
🌐 stackoverflow.com
How to set a variable in cmd which is a string from powershell command result? - Stack Overflow
I want to store the result of powershell command in cmd variable as String : powershell -com "(ls | select -Last 1).FullName". How to do this? More on stackoverflow.com
🌐 stackoverflow.com
Using Variable inside a string
Put your variable in $() to resolve it correctly in this instance. Example: $Variable = 20 $GrouptoAdd = "SG_VPN-$($Variable)_User" More on reddit.com
🌐 r/PowerShell
10
5
October 10, 2022
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.utility › set-variable
Set-Variable (Microsoft.PowerShell.Utility) - PowerShell | Microsoft Learn
These commands set the value of the $desc variable to A description, and then gets the value of the variable. Set-Variable -Name "desc" -Value "A description" Get-Variable -Name "desc" ... This example creates a global, read-only variable that contains all processes on the system, and then it displays all properties of the variable.
🌐
PowerShell Forums
forums.powershell.org › powershell help
How to pass the string from variable instead using it as parameter - PowerShell Help - PowerShell Forums
March 28, 2023 - Hello. How do I make line 2 work so that it extracts the string from $a and uses it in the command instead of trying to find a user with identity $a? $a = “-filter *” get-aduser $a And how is this called? I could not…
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:\> 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'

selhost is offline!'
ExecutionContext.InvokeCommand.ExpandString(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.

🌐
EDUCBA
educba.com › home › data science › data science tutorials › powershell tutorial › string in powershell
String in PowerShell | How to declare a string in powershell with operation?
June 28, 2023 - Here you are converting a variable to a string. The below method is generally used in function and advanced functions while declaring parameters. ... To check which operations PowerShell can perform on a string, you must pipeline the Get-Member command and check for the methods.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
🌐
Netwrix
blog.netwrix.com › 2018 › 10 › 04 › powershell-variables-and-arrays
How to Use PowerShell Variables
August 26, 2025 - After this command, whenever you type $Greeting, PowerShell will substitute the value you assigned to that variable, as shown below. The double quotes (“ ”) in the previous example indicate that the value is a string.
🌐
EDUCBA
educba.com › home › data science › data science tutorials › powershell tutorial › powershell variable in string
PowerShell Variable in String | Examples of PowerShell Variable in String
March 13, 2023 - Similarly, for the other data types, the string can convert any variable to the string. ... $a = 10.2 Write-Output "Representing float $a to string" $b = "Hello World" Write-Output "Representing String $b to string" ... Single-quote and Double-Quote in the PowerShell are the same, but expanding the variable makes a huge difference because single-quote string can’t expand the variable.
Address   Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
Find elsewhere
🌐
Red Gate Software
red-gate.com › home › working with powershell strings
Working with PowerShell strings | Simple Talk
November 24, 2021 - For example, when you start writing in PowerShell, you may notice that you can use single quotes or double quotes to designate a string. Save the above as SimpleStrings_demo.ps1. And as usual, examples are available at Github. When you run the above, you will see the following output: The first line is echoed as is because you haven’t told PowerShell to do anything special. Then you have created two variables and assigned strings to them.
🌐
Powershellbyexample
powershellbyexample.dev › post › strings
Strings | PowerShell By Example
Or maybe you have a CSV file and want to replace the delimiter from a comma to a semi-colon. You can either use the .Replace() method or the -replace operator. # Setup the query $query = "SELECT * FROM [_SCHEMANAME_].[_TABLENAME_] WHERE id = ...
Top answer
1 of 2
3

In PowerShell any output can be assigned to a variable. If it isn't assigned or otherwise consumed it will output to the host, usually the console.

Your example derived from pseudo code might be something like:

Copy$SomeOtherVar = $SomeVar -replace "one", "two"

The same would be true if you invoked a .Net method on the string:

Copy$SomeOtherVar = $SomeVar.Replace( "one", "two" )

Also important is assigning the output of a command which can be a cmdlet, function or even a command line executable.

Note: that calling functions & cmdlets is a little different in PowerShell. Don't specify arguments parenthetically. Separate parameters and arguments with spaces and/or use the named parameters.

Copy$SomeOtherVar = Get-SomeData $SomeVar

$SomeOtherVar = Ping $SomeVar

The summary answer to your question is anything PowerShell outputs can be assigned to a variable. So, literally anything you do to $SomeVar that generates output even if the output is null can be assigned to $SomeOtherVar

Responding to Comment / Additional Example:

Copy$SomeVar = 'foo'
$SomeOtherVar = $SomeVar -replace 'foo', 'bar'
$SomeOtherVar

Output: bar

2 of 2
1

So I find this post somewhat confusing and amusing. Steven's answer is a good one but seems to not have gotten through somehow so I will try to just throw some code out there and hope something sticks. If not, at least I tried right?

Copyfunction Append-BarToString {
    param(
        [string]$InputString
    )
    # explicit return keyword not needed.  
    # Any output inside function not assigned  
    # to a variable or to $null will be sent out
    $InputString + "Bar" 
}

# function can also be written without param block 
# more like C# like this, though it is unconventional
function Append-BarToString ([string]$InputString)
{
    # $InputString + "Bar"
    # or 
    "${InputString}Bar"
}

$someVar = 'foo'
$someOtherVar = Append-BarToString $someVar


$someOtherVar
# or
Write-Host $someOtherVar

# output
# fooBar
# fooBar
🌐
SS64
ss64.com › ps › set-variable.html
Set-Variable - PowerShell cmdlet
PowerShell · How-to · Set the value of a variable. Syntax Set-Variable [-Name] String[] [-value] Object] [-Include string[]] [-Exclude string[]] [-option option] [-scope string] [-force] [-passThru] [-whatIf] [-Description string] [-Visibility { Public | Private} ] [-confirm] [CommonParameters] Key -Name String The name of the variable(s), may be piped.
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › scripting › learn › deep-dives › everything-about-string-substitutions
Everything you wanted to know about variable substitution in strings - PowerShell | Microsoft Learn
There's a long history of using concatenation to build formatted strings. $name = 'Kevin Marquette' $message = 'Hello, ' + $name · Concatenation works out OK when there are only a few values to add. But this can get complicated quickly. ... This simple example is already getting harder to read. PowerShell has another option that is easier. You can specify your variables directly in the strings.
🌐
PowerShell Test-Path
powershellfaqs.com › convert-variables-to-strings-in-powershell
How to Convert Variables to Strings in PowerShell?
July 8, 2024 - The ToString() method is used to convert a variable to a string in PowerShell.
🌐
Super User
superuser.com › questions › 1351802 › how-can-i-store-a-powershell-variables-value-as-a-string-while-creating-ise-sub
How can I store a Powershell variable's value as a string while creating ISE submenus - Super User
At line:2 char:2 + Import-Module -Name $folder + ~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ResourceUnavailable: (_Connect-Office365Service:String) [Import-Module], FileNotFoundException + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand · The "_Connect-Office365Service" value is the last value or folder processed by the foreach statement. I want the unique and corresponding value of $folder for each folder name found to be part of the submenu item created.
🌐
Broadcom Community
community.broadcom.com › vmware-cloud-foundation › discussion › create-variable-inside-here-string-powershell
Create variable inside here-string - powershell | PowerCLI
Hi Team,I am trying to workout the below example - unable to define variable inside the here-string and useit(variable $a). something basic am missing, could yo
🌐
ShellGeek
shellgeek.com › home › powershell › convert powershell variable to string
Convert PowerShell Variable to String - ShellGeek
April 14, 2024 - In PowerShell, you can convert the variable to a string using the ToString() method or the -f format operator. You can convert integer, bool,
🌐
Adam the Automator
adamtheautomator.com › powershell-variable-in-strings
Place PowerShell Variables in Strings: Quick Tips
October 1, 2023 - When you need to show a PowerShell variable in a string, you typically just add the variable along with some other text inside of a string with double-quotes as shown below ... Putting a variable inside of a double-quoted string is called variable ...
🌐
PDQ
pdq.com › powershell › set-variable
Set-Variable - PowerShell Command | PDQ
Skip to content · PowerShell Commands ... [-Visibility {Public | Private}] [-WhatIf] [<CommonParameters>] The Set-Variable cmdlet assigns a value to a specified variable or changes the current value....
Top answer
1 of 3
3

CMD does not have a straightforward way of assigning command output to a variable. If the command produces just a single line you could use a for loop

for /f "delims=" %a in ('some_command /to /run') do @set "var=%a"

However, if the command produces multiple lines that will capture only the last line. A better approach would be redirecting the output of the command to a file and then reading that file into a variable:

set "tempfile=C:\temp\out.txt"
>"%tempfile%" some_command /to /run
set /p var=<"%tempfile%"
del /q "%tempfile%"

If you literally need only the last file in a directory you don't need to run PowerShell, though. That much CMD can do by itself:

for /f "delims=" %f in ('dir /a-d /b') do @set "var=%~ff"

Beware that you need to double the % characters when running this from a batch file.

2 of 3
1

A FOR loop can provide the path to the file. If the default directory sorting order is not the result needed, specify additional command line switches on the DIR command.

FOR /F "delims=" %F IN ('DIR /B') DO (SET "THE_FILE=%~fF")
ECHO THE_FILE is "%THE_FILE%"

In a .bat file script, double the percent characters on FOR loop variables.

FOR /F "delims=" %%F IN ('DIR /B') DO (SET "THE_FILE=%%~fF")
ECHO THE_FILE is "%THE_FILE%"

The .bat file scripts can also run PowerShell scripts. It is best practice to not use aliases such as ls in scripts.

FOR /F "delims=" %%F IN ('powershell -NoLogo -NoProfile -Command ^
    "(Get-ChildItem -File | Select-Object -Last 1).FullName"') DO (SET "THE_FILE=%%~fF")
ECHO THE_FILE is "%THE_FILE%"