Registry Mirror
Skip to content

$PSScriptRoot is not populated when running a code block (via F8) #633

Open

Description

System Details

  • Operating system name and version: Windows 10
  • VS Code version: 1.10.2
  • PowerShell extension version:
  • Output from $PSVersionTable:
PS C:\Source\neo4j-quick-demo> $pseditor.EditorServicesVersion

Major  Minor  Build  Revision
-----  -----  -----  --------
0      11     0      0


PS C:\Source\neo4j-quick-demo>
PS C:\Source\neo4j-quick-demo> code --list-extensions --show-versions
PS C:\Source\neo4j-quick-demo>
PS C:\Source\neo4j-quick-demo> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.14393.953
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.14393.953
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1

Issue Description

$PSScriptRoot is not populated when running a code block (via F8)

I am trying load DLLs that are in the same directory as the PowerShell script and use $PSScriptRoot to get the location for them.

When running the code in PowerShell it's fine, but using VSCode, when running the code snippet via F8, the variable is not populated.

Repro

  • Open VSCode and create a PowerShell (.ps1) file
  • Add the following command Write-Host "$PSScriptRoot\abc"
  • Select the newly created line and Press F8 to execute the PowerShell in the integrated terminal

Expected result:
<full working path>\abc

e.g. If the script I was editing was in C:\Source I would expect the result to be C:\Source\abc

Actual result:
\abc

Activity

  1. daviwil commented on Mar 30, 2017

    @daviwil
    Contributor

    Thanks for reminding me! I need to get that fixed.

  2. glennsarti commented on Mar 30, 2017

    @glennsarti
    ContributorAuthor

    Glad I wasn't going insane (more than usual)

  3. rkeithhill commented on Mar 30, 2017

    @rkeithhill
    Contributor

    One could argue that since F8 simply runs the selected code in global scope, that it is expected that $PSScriptRoot would not be defined. This is how F8 works in ISE i.e.$PSScriptRoot is not defined.

  4. glennsarti commented on Mar 30, 2017

    @glennsarti
    ContributorAuthor

    True, although if the code is being run from a file that exists, and it's a ps1, in my mind there's an expectation that $PSScriptRoot should be discoverable. If I use the PS Debugging (F5) it exists.

    I feel I do understand the technicalities here, and yes I can see your argument.

    The bigger question in my mind is should the user know the difference? If so, how would VS Code convey that to the user, instead of errors and null values?

  5. rkeithhill commented on Mar 30, 2017

    @rkeithhill
    Contributor

    If I use the PS Debugging (F5) it exists.

    Dot sourcing will evaluate $PSScriptRoot and when the file is executed without dot sourcing, it obviously works as well.

    The bigger question in my mind is should the user know the difference?

    IMO yes, because running script with F8 i.e. in the global session is subtly different than executing the script file or even dot sourcing it. $PSScriptRoot is just on example. Other differences are $PSCommandPath, $MyInvocation , Get-PSCallStack and likely others I haven't thought of. Also, the integrated console global session is "global" to all scripts you are editing. So these values would have to change for the lines of script that are being executed by F8. Which is likely doable except that have you tried to set $PSScriptRoot? It doesn't want to let you set it. :-) Anyway, if you don't appreciate these subtleties, you can get yourself into trouble thinking you have F8'd yourself to a working script when it won't work when invoked normally. All that said, the common stumbling block is likely to be $PSScriptRoot. If this variable can be set in the global scope and setting it doesn't interfere with proper script operation later, it is probably worth setting.

    Finally, maybe the F8 feature could be made smart and if you have selected all the text in a script, it would dot source the script rather than execute script directly in the global session. Then, at least $PSScriptRoot and $PSCommandPath would be defined correctly.

  6. glennsarti commented on Mar 30, 2017

    @glennsarti
    ContributorAuthor

    I'd be happy if it wasn't supported, but somehow I was warned that "Stuff may not do what you expect" if it saw those tokens in the text.

  7. rkeithhill commented on Mar 30, 2017

    @rkeithhill
    Contributor

    warned that "Stuff may not do what you expect" if it saw those tokens in the text.

    We should probably do that if we detect $PSCommandPath, $MyInvocation or Get-PSCallStack in the text. I think those are corner-case enough to not try to "fix up" in the global session.

    Now that I think about it, perhaps the F8 mechanism could do the evaluation of $PSScriptRoot and replace it with the full path of the script's parent dir?

  8. daviwil commented on Mar 30, 2017

    @daviwil
    Contributor

    Yeah, F8 could just insert the script's parent dir into the session as $PSScriptRoot right before running the snippet. I believe people used to complain that the ISE did not do this. Might be nice to make it work.

    However, I've been considering using VS Code's built in Run Selection in Terminal command instead of my own custom F8 implementation. This would mean that I wouldn't be able to do the $PSScriptRoot injection. However, I don't have a good reason to do that other than just removing "unnecessary" code. If the $PSScriptRoot injection is important enough (which it might be for interactive dev workflow) then I can still keep the current F8.

    Thoughts?

  9. dragonwolf83 commented on Mar 30, 2017

    @dragonwolf83

    ISE has the following property to get the Current File in the Editor:

    $psise.CurrentFile

    I don't know if you have ported it yet, but that makes it easy to inject into $PSScriptRoot when F8 is run. It always stays up-to-date with new editor tabs and even has path to where Untitled.ps1 would be saved.

    This is one of the most annoying things in ISE. It requires special handling and thinking when developing because you need $PSScriptRoot in production and $psise.CurrentFile in testing specific code blocks.

    A couple reasons for using F8 is because previous code in script is either dangerous to run multiple times (deleting files) or has performance impacts (large RESTful call or Get-ChildItem -Recurse). So I run a snippet and then test various things on that snippet and would like one "truth" of where the script is located.

  10. simonsabin commented on Nov 13, 2017

    @simonsabin

    Hit this today, Really don't want to have to comment lots of code out to run that file. One might argue I need to factor my code correctly, but rightly or wrongly I expect people to be in this situation and want to F8 a script that tries to run files in relative folders.

  11. SeeminglyScience commented on Jan 17, 2018

    @SeeminglyScience
    Collaborator

    Fixing this is a little bit more difficult than it may appear. The big problem with this one is that it's basically impossible to set the PSScriptRoot variable manually because it's replaced by the engine in every single scope.

    That said, the engine creates the variable based on the ScriptExtent for the command. With the Parser API, you can parse specific input and specify a file source. Here's a proof of concept editor command preserves MyInvocation, PSScriptExtent, and position info for breakpoints.

    Register-EditorCommand -Name TestingF8 -DisplayName 'Run selected text and preserve extent' -ScriptBlock {
        [System.Diagnostics.DebuggerHidden()]
        [System.Diagnostics.DebuggerStepThrough()]
        [CmdletBinding()]
        param()
        end {
            function __PSES__GetScriptBlockToInvoke {
                $context = $psEditor.GetEditorContext()
                $extent = $context.SelectedRange | ConvertTo-ScriptExtent
    
                $newScript = [System.Text.StringBuilder]::new().
                    Append([char]' ', $extent.StartOffset - $extent.StartLineNumber - $extent.StartColumnNumber).
                    Append([char]"`n", $extent.StartLineNumber - 1).
                    Append([char]' ', $extent.StartColumnNumber - 1).
                    Append($extent.Text).
                    ToString()
    
                try {
                    $errors = $null
                    return [System.Management.Automation.Language.Parser]::ParseInput(
                        <# input:    #> $newScript,
                        <# fileName: #> $Context.CurrentFile.Path,
                        <# tokens:   #> [ref] $null,
                        <# errors:   #> [ref] $errors).
                        GetScriptBlock()
                } catch [System.Management.Automation.PSInvalidOperationException] {
                    $exception = New-Object System.Management.Automation.ParseException($errors)
                    $PSCmdlet.ThrowTerminatingError(
                        (New-Object System.Management.Automation.ErrorRecord(
                            <# exception:     #> $exception,
                            <# errorId:       #> 'RunSelectionParseError',
                            <# errorCategory: #> 'ParserError',
                            <# targetObject:  #> $newScript)))
                }
            }
    
            try {
                return . (__PSES__GetScriptBlockToInvoke)
            } catch {
                if ($PSItem -is [System.Management.Automation.ErrorRecord]) {
                    $PSCmdlet.ThrowTerminatingError($PSItem)
                    return
                }
    
                $PSCmdlet.ThrowTerminatingError(
                    (New-Object System.Management.Automation.ErrorRecord(
                        <# exception:     #> $PSItem,
                        <# errorId:       #> 'RunSelectionRuntimeException',
                        <# errorCategory: #> 'NotSpecified',
                        <# targetObject:  #> $null)))
            }
        }
    }
  12. daviwil commented on Jan 17, 2018

    @daviwil
    Contributor

    Very clever solution! If we tried that, one thing we'd want to do is send the EditorContext along with the run selection request so that it doesn't have to be fetched from within PowerShell, saving another round trip. If the editor sends the EditorContext with the request we can take this approach, otherwise go with the original approach.

  13. 91 remaining items

  14. ghost added
    Needs: Maintainer Attention
    on Jan 25, 2022
  15. JustinGrote commented on Jan 25, 2022

    @JustinGrote
    Collaborator

    This issue can be used for tracking the enhancement. I've flagged it as Up for Grabs which means we will entertain PR attempts, right now with the pipeline rework the focus is on getting that to the point it can be promoted to stable so that we can have a regular stable release cadence again, so I wouldn't expect this anytime soon unless someone contributes it.

  16. simonsabin commented on Jan 25, 2022

    @simonsabin

    I was wondering if this could be solved by the debug capability rather than built in F8. i.e. being able to specify something in launch.json
    I however couldn't find a way to have a script run, the script property of launch.json only seems to take a file.

  17. ghost added
    Needs: Maintainer Attention
    on Jan 25, 2022
  18. JustinGrote commented on Jan 25, 2022

    @JustinGrote
    Collaborator

    Simon Sabin (@simonsabin)

            {
                "type": "PowerShell",
                "request": "launch",
                "name": "PS: 📄 with args",
                "script": "${file}",
                "args": [
                    "${command:SpecifyScriptArgs}"
                ],
                "cwd": "${file}"
            },
  19. simonsabin commented on Jan 26, 2022

    @simonsabin

    Thanks @JustinGrote.my point was that "script" only takes a filepath. one can't pass a chunk of text.
    I was looking for a cheap workaround

       {
                "name": "PowerShell F8 Session",
                "type": "PowerShell",
                "request": "launch",
                "script": "${workspaceFolder}/.vscode/run.ps1",
                "args": [
                    "-file","${file}",
                    "{${selectedText}}"
                ]
            },
    

    where run.ps1 is a script that can run the selected text. However you can't override psscriptroot.

    It looks like Patrick Meinecke (@SeeminglyScience) solution would be a much better one.

  20. ghost added
    Needs: Maintainer Attention
    on Jan 26, 2022
  21. walterg32 commented on Mar 17, 2023

    @walterg32

    @RandyInMarin for Powershell at least, there are several variables like $PSScriptRoot that are only present in the context of a script, not within an interactive session.

    https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.2#myinvocation image

    When you do F8, you are basically "cut pasting" into the terminal, so the current behavior is exactly what happens outside of vscode at a normal terminal.

    Like I said, an opt-in setting to populate these to ease development would make sense, if someone wants to attempt a PR I'm sure we could massage it to get accepted, but it definitely wouldn't be the default.

    I had my "AHA" moment when I read this comment. Totally makes sense now why my $PSScriptRoot wasn't working. I was selectively running code segments. Thanks for the solution!

  22. JustinGrote commented on Mar 22, 2023

    @JustinGrote
    Collaborator

    Even if it's not run as a script, the script still has a parent folder.

    What would the parent folder of Remove-Item $PSScriptRoot -recurse -force be if run as a selection? Your current working directory? That sounds dangerous, that's why it only populates if it is in the context of the script.

    When you use Run Selection, it's the same as copying and pasting the code to the command line. Testing of scripts proper including $PSScriptRoot you really should be using Pester, run as file (default F5) or dot sourcing the script to test it. Running fragments out of a script and expecting PSScriptRoot to work in my opinion is the same as running a block of code without the variable above it and expecting the variable to be magically autopopulated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Area-Extension TerminalIssue-EnhancementUp for Grabs

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions