Reputation: 13234
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?
Upvotes: 4
Views: 482
Reputation: 54911
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
Upvotes: 8