powershell – Powershell Test Script Error: ‘The term ‘=’ is not recognized’

linuxpowershellscripting

powershell users!
If I run powershell as shell and type commands one by one – weverything's good.
But if I put commands into .ps1 file and try to execte it I receive weird error:

The term '=' is not recognized as the name of a cmdlet, function, script file, or operable program

test script I run:

echo "$pw = 2" > ./test.ps1
echo '$pw' >> ./test.ps1
pwsh ./test.ps1

I use pwsh on linux (installed from https://packages.microsoft.com/rhel/7/prod/) if it matters.

tried to use "$pw=2` – same result.

Yes, I know about long form of setting and getting variable:

echo "set-variable -name 'pw' -value '2'" > ./test.ps1
echo "get-variable -name 'pw'" >> ./test.ps1
pwsh ./test.ps1

It works. But I want more complicated scripts where get-variable can be hardly used.

Please help – what am I doing wrong?

Best Answer

You need to escape the $ dollar sign indicating a variable name.

# command                       # result
Set-StrictMode -Off             # uninitialized variables are assumed to have a value of 0 (zero) or $null
echo "$pw = 2"                  #  = 2
Set-StrictMode -Version Latest  # Selects the latest (most strict) version available
echo "$pw = 2"                  # throws an error: The variable '$pw' cannot be retrieved because it has not been set.
echo '$pw = 2'                  # $pw = 2       (used single quotes)
echo "`$pw = 2"                 # $pw = 2       (used backtick escape character)

Edit the above example was tested in Windows Powershell. However, it works with the same results in WSL Ubuntu shell omitting all the Set-StrictMode stuff and using the \ backslash escape character as follows:

# command                       # result
echo "$pw = 2"                  #  = 2
echo '$pw = 2'                  # $pw = 2       (used single quotes)
echo "\$pw = 2"                 # $pw = 2       (used backslash escape character)

Reference: