You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
$PSScriptRoot is not populated when running a code block (via F8) #633
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.
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?
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.
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?
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.
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.
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.
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.
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.
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.
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.
@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.
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!
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.
Activity
daviwil commentedon Mar 30, 2017
Thanks for reminding me! I need to get that fixed.
glennsarti commentedon Mar 30, 2017
Glad I wasn't going insane (more than usual)
rkeithhill commentedon Mar 30, 2017
One could argue that since
F8simply runs the selected code inglobalscope, that it is expected that$PSScriptRootwould not be defined. This is howF8works in ISE i.e.$PSScriptRootis not defined.glennsarti commentedon Mar 30, 2017
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$PSScriptRootshould 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?
rkeithhill commentedon Mar 30, 2017
Dot sourcing will evaluate
$PSScriptRootand when the file is executed without dot sourcing, it obviously works as well.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-PSCallStackand 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 sourcethe script rather than execute script directly in the global session. Then, at least$PSScriptRootand$PSCommandPathwould be defined correctly.glennsarti commentedon Mar 30, 2017
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.
rkeithhill commentedon Mar 30, 2017
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
$PSScriptRootand replace it with the full path of the script's parent dir?daviwil commentedon Mar 30, 2017
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?
dragonwolf83 commentedon Mar 30, 2017
ISE has the following property to get the Current File in the Editor:
$psise.CurrentFileI 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.
simonsabin commentedon Nov 13, 2017
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.
SeeminglyScience commentedon Jan 17, 2018
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
PSScriptRootvariable manually because it's replaced by the engine in every single scope.That said, the engine creates the variable based on the
ScriptExtentfor the command. With theParserAPI, you can parse specific input and specify a file source. Here's a proof of concept editor command preservesMyInvocation,PSScriptExtent, and position info for breakpoints.daviwil commentedon Jan 17, 2018
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.
91 remaining items
JustinGrote commentedon Jan 25, 2022
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.
simonsabin commentedon Jan 25, 2022
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.
JustinGrote commentedon Jan 25, 2022
Simon Sabin (@simonsabin)
{ "type": "PowerShell", "request": "launch", "name": "PS: 📄 with args", "script": "${file}", "args": [ "${command:SpecifyScriptArgs}" ], "cwd": "${file}" },simonsabin commentedon Jan 26, 2022
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
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.
walterg32 commentedon Mar 17, 2023
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!
JustinGrote commentedon Mar 22, 2023
What would the parent folder of
Remove-Item $PSScriptRoot -recurse -forcebe 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.