4

Is it possible to somehow configure PowerShell to add a new line after executing a command? IronPython and other console programs which I use doesn't always finish it's output with a \n and because of that the PowerShell prompt will appear at the middle of the line.

This is what I get:

PS D:\Test> ipy test.py
Traceback (most recent call last):
  File "test.py", line 1, in <module>
RuntimeError: *** ERROR ***PS D:\Test\bin>  <---------- MIDDLE OF LINE PROMPT

This is what I would like:

PS D:\Test> ipy test.py
Traceback (most recent call last):
  File "test.py", line 1, in <module>
RuntimeError: *** ERROR ***
PS D:\Test\bin>                            <---------- NEW LINE PROMPT
Meh
  • 373
  • 2
  • 7
  • 10

2 Answers2

6

You can create custom prompt function like this:

Set-Content function:\prompt { 
  if($Host.UI.RawUI.CursorPosition.X -eq 0) {'PS>'} else{"`nPS>"}
}

How to test it:

write-host 'this is test' -nonewline
stej
  • 196
  • 3
0

I've cobbled together a few examples. This is in my Profile script. You can edit your Profile script by entering notepad $Profile or better yet, code $Profile if you've got VSCode installed.

function  prompt {
    # Put a blank line between us and the last output
    # Two, if the output failed to put us on a new line
    $spacing = if($Host.UI.RawUI.CursorPosition.X -eq 0){"`n"}else{"`n`n"};

    # Determine if PS is running in Admin mode
    $identity = [Security.Principal.WindowsIdentity]::GetCurrent();
    $principal = [Security.Principal.WindowsPrincipal] $identity;
    $adminRole = [Security.Principal.WindowsBuiltInRole]::Administrator;
    $adminStr = $(if($principal.IsInRole($adminRole)) { '[ADMIN]: ' });

    # Determine if we're in Debug context
    $dbgStr = $(if (Test-Path variable:\PSDebugContext) { '[DBG]: ' });

    # Determine history/line number for current prompt
    # The at sign creates an array in case only one history item exists.
    $history = @(Get-History);
    if($history.Count -gt 0) {
        $lastItem = $history[$history.Count - 1];
        $lastId = $lastItem.Id;
    };
    $nextId = $lastId + 1;

    # Determine the current location
    $currentLocation = $($executionContext.SessionState.Path.CurrentLocation);

    # Generate nested indicator
    $nest = $('>' * ($NestedPromptLevel + 1));

    # String it all together and output
    "$spacing$adminStr$dbgStr" + "PS: $nextId $currentLocation$nest "
    # .Link
    # https://go.microsoft.com/fwlink/?LinkID=225750
    # .ExternalHelp System.Management.Automation.dll-help.xml
}

Here's an example:

PowerShell 7.3.2

[ADMIN]: PS: 1 C:\Users\tbemr> $pi = 'three'

[ADMIN]: PS: 2 C:\Users\tbemr> Write-Host "2$pi" -NoNewline
2three

[ADMIN]: PS: 3 C:\Users\tbemr> @(Get-History)[0]

  Id     Duration CommandLine
  --     -------- -----------
   1        0.001 $pi = 'three'


[ADMIN]: PS: 4 C:\Users\tbemr>