1

I'm able to Write-Host a custom variable from PowerShell command line, but predefined variables are not working with same way.

What is proper way to echo a predefined variable.

Write-Host $path works.
Write-Host $PSScriptRoot does not.

Here is my code.

powershell.exe -ExecutionPolicy ByPass -Command "& { $path = """test"""; Write-Host $path; Write-Host $PSScriptRoot; }"

I would like to have parent directory of current script as variable.

Something like this $RootPath = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent.

4
  • 7
    $PSScriptRoot is defined for scripts in files. You're not running a file-based script, so $PSScriptRoot is empty. If you want the current directory, use pwd or [Environment]::CurrentDirectory (depending on whether you want PowerShell's opinion, or the operating system's opinion). Commented Sep 4, 2017 at 15:21
  • @JeroenMostert would you please provide an example for both? Commented Sep 4, 2017 at 15:23
  • Write-Host (Split-Path (pwd) -Parent)? Or set a variable first: $path = pwd. This is a basic case of using a cmdlet's output as input for another cmdlet. Commented Sep 4, 2017 at 15:28
  • @JeroenMostert I was seaching this solution more than 3 hours. I really appreciated. Commented Sep 4, 2017 at 15:43

1 Answer 1

2

If current location is what you want, this has always worked for me.

(Get-Location).path

If you also want to know for other predefined variables, Write host should work.

Get-Variable or simply Variable will display all predefined variables. If you look at $PSScriptroot, you will realize that it is empty. That is why it doesn't seem to be working for you.

Sign up to request clarification or add additional context in comments.

Comments

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.