I have found the following behaviour that I do not understand. I have some functions in my $profile (specifically, that change my prompt, so function prmopt { }) with settings that change my prompt and when I start a console, if I dotsource the function ( . PromptCustom ), it takes full effect and the new prompt takes over. However, I don't want my $profile to be too big so I moved my five or so different prompts into a Module, but when I try to dotsource any of them, nothing happens. They just output what the prompt might look like but do not take over as the default prompt.
The objective is to be able to have multiple functions that switch between prompts as required (i.e. not a single prompt that applies to every console, for which I would just put function prompt in my $profile). When I move functions that follow the below template to a Module, they all break and so I was wondering if that was a scoping issue, and how to achieve the goal of having mutltiple prompt functions in a Module that I can switch between instead of being forced to keep them in my $profile? (Edit: updating this question as @mklement0 pointed out, since really it's about the required objective i.e. having prompts that I can switch between).
Here is one of my prompt functions that dotsources and takes over as the default prompt perfectly if this function is defined in my $profile but does nothing if it is put into a Module:
function PromptShortenPath {
# https://stackoverflow.com/questions/1338453/custom-powershell-prompts
function shorten-path([string] $path) {
$loc = $path.Replace($HOME, '~')
# remove prefix for UNC paths
$loc = $loc -replace '^[^:]+::', ''
# make path shorter like tabs in Vim,
# handle paths starting with \\ and . correctly
return ($loc -replace '\\(\.?)([^\\])[^\\]*(?=\\)','\$1$2')
}
function prompt {
# our theme
$cdelim = [ConsoleColor]::DarkCyan
$chost = [ConsoleColor]::Green
$cloc = [ConsoleColor]::Cyan
write-host "$([char]0x0A7) " -n -f $cloc
write-host ([net.dns]::GetHostName()) -n -f $chost
write-host ' {' -n -f $cdelim
write-host (shorten-path (pwd).Path) -n -f $cloc
write-host '}' -n -f $cdelim
return ' '
}
if ($MyInvocation.InvocationName -eq "PromptShortenPath") {
"`nWarning: Must dotsource '$($MyInvocation.MyCommand)' or it will not be applied to this session.`n`n . $($MyInvocation.MyCommand)`n"
} else {
. prompt
}
}