Krisz
Krisz

Reputation: 743

Is it possible to overwrite the Prompt function from a function in PowerShell?

I'm trying to define a single command to set a custom prompt on the PowerShell console. You can overwrite the default prompt with the following script:

function Prompt {
    "PS " + "[$(Get-Date)] " + $(Get-Location) + ">"
}

So I would like to call above script with a function, e.g.: Set-CustomPrompt.

I've already seen a solution on StackOverflow where the script was executed from an external ps1 file, but I am looking for a solution where the definition is in the same file.

Upvotes: 3

Views: 1017

Answers (3)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200363

Have your Set-CustomPrompt function define the Prompt function in the global scope (see also):

function Set-CustomPrompt {
    function global:Prompt {
        "PS [$(Get-Date)] $(Get-Location)>"
    }
}

Upvotes: 4

Richard
Richard

Reputation: 109100

The prompt function needs to be an global scope. But it can call another function.

So define with a level of abstraction with a global variable holding the function name:

function Set-CustomPrompt {
   ....
   $myCustomPropmtFunctionName = ...
}

function prompt {
    &$myCustomPropmtFunctionName;
}

Upvotes: 0

nilleb
nilleb

Reputation: 1012

Just defining the prompt function in your code doesn't work for you? (see: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_prompts?view=powershell-5.1)

Upvotes: -1

Related Questions