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?

  • Did you enter the script in bash or pwsh? Remember variables inside double quotes are expanded. So echo '$pw = 2' > ./test.ps1 should do. In pwsh the echo is superfluous. – LotPings Feb 22 '19 at 17:08

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)


  • :wall: I know about double quotes normally - but there I forgot about it totally. Thanks! – Drey Feb 24 '19 at 14:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.