Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify and restore PowerShell prompt from a module

I'm writing a PowerShell module for interacting with a remote service. When connecting to the remote service (via a function in the module), I want to prepend the username to the prompt. Upon disconnecting, I want to remove the username.

I thought I could accomplish this by copying the global prompt function, then restoring it upon disconnect:

# Doesn't work
function Connect {
    Copy-Item function:prompt function:prompt_old
    function global:prompt { "[Username] $(prompt_old)" }
}
function Disconnect {
    Copy-Item function:prompt_old function:prompt -Force
}

However, Copy-Item doesn't make a copy in the global scope. Thus, prompt throws a CommandNotFoundException and the disconnect function can't replace prompt with prompt_old.

Is there a way I can modify, then restore, the PowerShell prompt from module functions?

like image 991
Stephen Jennings Avatar asked Sep 06 '25 03:09

Stephen Jennings


1 Answers

You can store the function in a variable while you work.

Backup using:

$global:prompt_old = get-content function:\prompt

Then you can modify the prompt, and recover it later using:

set-content function:\prompt $global:prompt_old
like image 105
Frode F. Avatar answered Sep 07 '25 19:09

Frode F.