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

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

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 $$

2 Comments

Try and see, I cannot test it now
If the path was ProgramFiles' this will fail.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.