Search code examples
powershellprofile

Enter-PSSession equivalent of $profile script


On my local PC and locally on the servers I admin, I regularly use the $profile script to set/output basic information. For instance running Set-Location to set the current path to the folder containing the scripts, and perhaps some Write-Host entries to show a basic cheat sheet for the most commonly used scripts and their expected parameters.

Does anyone know of a way to do something similar to that when using Enter-PSSession to connect interactively with a remote server?

As far as I can see there are no $profile files available with remote sessions, so I can't just add the commands in there (and the $profile used interactively on the local server doesn't get called when you remote into that same server).

Locally I've added functions to my local profile to make connecting to specific servers quicker, for example :

function foo{
   $host.ui.RawUI.WindowTitle = "Foo"
   Enter-PSSession -computername foo.local.mydomain.com -authentication credssp -credential mydomain\adminuser
}

and that works fine for connecting me (eg I type foo, then enter my password, and I'm in), but I still get dumped into C:\Users\adminuser\Documents.

I've tried adding things like the Set-Location command to the function after the connection, but that gets run in the local context (where the folder doesn't exist) and THEN it connects to the server. I even tried piping the commands to Enter-PSSession, but perhaps unsuprisingly that didn't work either.

Obviously things like Invoke-Command would allow me to specify commands to run once connected, but that wouldn't (as far as I can work out) leave me with an interactive session which is the primary aim.


Solution

  • You can't really automate unattended execution of anything that happens after Enter-PSSession connects your host to the remote session - but you can execute all the code you want in the remote session before calling Enter-PSSession:

    function DumpMeInto {
      param([string]$Path)
    
      # Create remote session (you'll be prompted for credentials at this point)
      $session = New-PSSession -ComputerName foo.local.mydomain.com -Authentication credssp -Credential mydomain\adminuser
    
      # Run Set-Location in remote runspace
      Invoke-Command -Session $session -ScriptBlock { Set-Location $args[0] } -ArgumentList $Path
    
      # ... and then enter the session 
      Enter-PSSession -Session $session
    }
    

    Now you can do DumpMeInto C:\temp and it should drop you into a remote session on foo.local.mydomain.com with it's working directory set to c:\temp