如何让 PowerShell 执行命令后添加新行?

如何让 PowerShell 执行命令后添加新行?

是否可以以某种方式配置 PowerShell 以在执行命令后添加新行?我使用的 IronPython 和其他控制台程序并不总是以 \n 结束其输出,因此 PowerShell 提示符将出现在行的中间。

这是我得到的:

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

这就是我想要的:

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

答案1

您可以prompt像这样创建自定义函数:

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

如何测试:

write-host 'this is test' -nonewline

答案2

我拼凑了一些示例。这些都在我的 Profile 脚本中。您可以通过输入notepad $Profile或更好的方式(code $Profile如果您已安装 VSCode)来编辑您的 Profile 脚本。

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
}

以下是一个例子:

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>

相关内容