1

The PSScriptRoot variable appears to have a value, but it cannot be used. My apologies if this turns out to be silly. What's going on?

PS C:\> Get-ChildItem Variable:PSScriptRoot

Name                           Value
----                           -----
PSScriptRoot                   C:\Windows\System32\WindowsPowerShell\v1.0

PS C:\> $PSScriptRoot

PS C:\> $PSScriptRoot.Length
0
PS C:\> $PSScriptRoot.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

PS C:\> $PSScriptRoot | Format-List * -Force

Length : 0

PS C:\> $null -eq $PSScriptRoot
False
PS C:\> "===$PSScriptRoot==="
======
PS C:\> $PSVersionTable.PSVersion.ToString()
5.1.17763.1490
1
  • 2
    $PSScriptRoot will only work if the script is saved and you're executing the whole script (not a portion of the code). Hopefully it makes sense. Commented Apr 23, 2021 at 14:46

1 Answer 1

3

$PSScriptRoot is an automatic variable. Outside of a script it generally has a value of '' (empty string). Inside of a script it contains the path of the folder that contains the script file it's executing. You can set it, but it's likely to be immediately overwritten by the interpreter.

PS C:\> Set-Location $env:TEMP
PS C:\Users\userid\AppData\Local\Temp> Set-Content -Path .\Test.ps1 -Value 'Write-Host $PSScriptRoot'
PS C:\Users\userid\AppData\Local\Temp> .\Test.ps1
C:\Users\userid\AppData\Local\Temp
PS C:\Users\userid\AppData\Local\Temp> $PSScriptRoot

PS C:\Users\userid\AppData\Local\Temp> cd\
PS C:\> C:\Users\userid\AppData\Local\Temp\Test.ps1
C:\Users\userid\AppData\Local\Temp
PS C:\> 
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.