Search code examples
powershellwindows-terminal

Load a .PS1 file into current session without simulating user input?


I have this file called Local_Paths.txt . Its just a text file full of paths:

C:\Temp\README.md
C:\Temp\README.md
C:\Temp\object_lifetime_management.md
C:\Temp\object_reference.md
...
...
...

The paths are being logged there, in real time as I interact with folders and files, in file manager and other tools.

The purpose of this Local_Paths.txt is for a module I made in powershell. For example I can quicly call up Terminal and pipe the 5 most recent .Md files into this module.

I have the file loaded into a variable in my $Profile:

cls
$LocalPaths = Get-Content "C:\Users\...\Documents\Local_Paths.txt"

On the rare case I have to boot up Powershell, this works fine. The problem I have is that I always have a Powershell session minimised on the taskbar.

So I am constantly either . $Profile my entire profile, which is quite a heavy file. or just declaring a $LocalPaths = Get-Content "C:\Users\...\Documents\Local_Paths.txt".

This proccess just kills the purpose of my module (Less hand wringling, more automation)

I am wondering is there a way to inject powershell code into the current session through a .Ps1 script or even through the wt command?

so that when I press the hotkey to focus Powershell this script to load the txt file gets executed first.

I did go through the Windows Terminal page for the Actions command. This is still user simulation though.


I have taken the liberty to cross post this question on other forums as well. Any help or just pointing me in the right direction would appreciated.


Solution

  • If I understand correctly, you want the value of $LocalPaths to always reflect the latest content of your Local_Paths.txt file.

    Since you need some identifier to refer to this content, you could use a function instead, which reads the file on every invocation, and you can place that in your $PROFILE file:

    # Note: I'm using a name that follows PowerShell's naming convention here,
    #       but you're free to choose your own, possibly shorter name.
    #       The use of @args means that you can pass arguments through
    #       to the Get-Content call, such as -Tail 5
    function Get-LocalPaths { 
      Get-Content -LiteralPath 'C:\Users\...\Documents\Local_Paths.txt' @args
    }
    

    If reading the file every time the function is called is too costly, you could implement a caching mechanism that only reloads the file if its .LastWriteTime property has changed.