powershellcommand-line-interface

How get Powershell v7.5 to expand $env from command line like v5.1


Passing an environment variable from command line works differently in Powershell v7.5 compared to v5.1. Is there some overall setting for PS 7.5 to provide compatibility? Or an explanation of why so I can develop a good work-around?

Sample test.ps1

"args[0]"
$args[0]

Running with ps 5.1

powershell test.ps1 $env:temp
args[0]
D:\MyTemp

With pwsh 7.5

pwsh test.ps1 $env:temp
args[0]
$env:temp

Quoting the value on the command line doesn't change. Assigning $args[0] to another variable does not expand it. But, an inline assignment works fine like $val = "$env:temp"


Solution

  • The main difference between pwsh and powershell in the context of your question, is that the former defaults to -File (-f) while the latter defaults to -Command (-c) which seem to be resolve the issue when calling the script from cmd.

    Worth noting, if the script isn't discoverable via $env:PATH, the CLI call will require .\ preceding the script name or the absolute path to the script, so that it is invoked as opposed to being interpreted as command name.

    In summary, from powershell, no changes:

    powershell test.ps1 $env:TEMP
    

    But from pwsh, add -c or -command and the issue should be resolved:

    pwsh -c test.ps1 $env:TEMP
    

    As to why it works with -c, essentially it's like calling your script from PowerShell itself, allowing the expansion of $env:TEMP before being passed as argument of the script. Another way of seeing it would be like in this example:

    & {
        'args[0]'
        $args[0]
    } $env:TEMP