lit
lit

Reputation: 16236

PSScriptRoot variable has a value but cannot be used

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

Upvotes: 1

Views: 621

Answers (1)

Bacon Bits
Bacon Bits

Reputation: 32145

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

Upvotes: 3

Related Questions