$PSScriptRoot defaulting to C:\ drive

Welcome Forums General PowerShell Q&A $PSScriptRoot defaulting to C:\ drive

This topic contains 5 replies, has 3 voices, and was last updated by

 
Participant
4 years, 5 months ago.

  • Author
    Posts
  • #20755

    Participant
    Topics: 2
    Replies: 2
    Points: 0
    Rank: Member

    I'm having an issue where my script will randomly start registering $PSScriptroot as the C:\ drive on my computer. It will work many times as intended, and sometime later seemingly at random it errors out with "cannot find the specified file."

    I am opening the script from C:\Scripts\GETSDC\
    and it returns:

    Get-Content : Cannot find path 'C:\Targets.txt' because it does not exist.
    

    The command that's throwing the error first in my script is get-content:

    $Targets = Get-Content $PSScriptRoot\Targets.txt
    

    Any help would be appreciated. Thanks!

  • #20760

    Member
    Topics: 9
    Replies: 2322
    Points: 0
    Rank: Member

    Are you running your script from PowerShell -Version 2.0 when this happens? $PSScriptRoot wasn't added until PowerShell v3.

  • #20761

    Participant
    Topics: 2
    Replies: 90
    Points: 470
    Rank: Contributor

    I've yet to see $PSScriptRoot not return the proper directory. At minimum, you could test with the $MyInvocation automatic variable and see if you end up with the same error or not.

    Get-Content "$(Split-Path $MyInvocation.InvocationName)\Targets.txt"
  • #20769

    Participant
    Topics: 2
    Replies: 2
    Points: 0
    Rank: Member

    This is where I'm running my script from. Note the target file.

    This is the error it's giving me and note that I'm running version 4.

    Edit: images weren't working, attached them to the post.
    Edit2: Please note that I'm running a script selection, and getting the same error when I run my whole script. I'm not just trying to use $PSScriptroot without a script.

  • #20773

    Member
    Topics: 9
    Replies: 2322
    Points: 0
    Rank: Member

    You can't use $PSScriptRoot at the command line. That variable is only set when you're executing a ps1 or psm1 file.

    • #20780

      Participant
      Topics: 2
      Replies: 2
      Points: 0
      Rank: Member

      Edit2: Please note that I'm running a script selection, and getting the same error when I run my whole script. I'm not just trying to use $PSScriptroot without a script.

      I added in this edit when I replied, you must not have read this line.

The topic ‘$PSScriptRoot defaulting to C:\ drive’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort