0

Using PowerShell 2, I can correctly use the $$ variable

PS > $PSVersionTable.PSVersion.Major
2

PS > Convert-Path 'Program Files'
C:\Program Files

PS > Convert-Path $$
C:\Program Files

However with PowerShell 4 the same command produces an error

PS > $PSVersionTable.PSVersion.Major
4

PS > Convert-Path 'Program Files'
C:\Program Files

PS > Convert-Path $$
Convert-Path : Cannot find path 'C:\'Program Files'' because it does not exist.

How can I use this example with PowerShell 4?

about_Automatic_Variables

Zombo
  • 1
  • 62
  • 391
  • 407

2 Answers2

1

One way is:

Convert-Path 'Program Files'

Convert-Path ($$ -replace "`'", '')

edit after comment:

 Convert-Path ($$ -replace "^`'|`'$", '')

to replace only single quote at the start and at the end of the $$

CB.
  • 58,865
  • 9
  • 159
  • 159
1

You could use Invoke-Expression to expand the string.

PS > Convert-Path 'Program Files'
C:\Program Files

PS > Convert-Path (Invoke-Expression $$)
C:\Program Files

Using aliases:

PS > cvpa (iex $$)
C:\Program Files

You could even use this to create an automatic variable of your own. Here, I use 4 since it's on the same key as $.

Put this in your Profile:

$Global:4 = 0
$null = Set-PSBreakpoint -Variable 4 -Action {
        $global:4 = Invoke-Expression $$} -Mode Read

Then you can run:

PS > Convert-Path 'Program Files'
C:\Program Files

PS > Convert-Path $4
C:\Program Files
Rynant
  • 23,153
  • 5
  • 57
  • 71