当前位置:网站首页 > 更多 > 玩电脑 > 正文

[玩转系统] 周五乐趣:让您的 PowerShell 提示符焕然一新

作者:精品下载站 日期:2024-12-14 07:52:53 浏览:16 分类:玩电脑

周五乐趣:让您的 PowerShell 提示符焕然一新


我已经有一段时间没有写周五有趣的帖子了。通常这些帖子没有太多实用价值,但希望能说明一个概念或技术。虽然我今天拥有的东西是你可以立即使用的。我有一个 PowerShell 提示函数版本,它会根据底层 PSProvider 对您的位置进行颜色编码。该函数可以在 Windows PowerShell 上运行,并且在 Windows 下运行的 PowerShell Core 上运行得很好。但 Linux 上的 PowerShell Core 处理提示功能的方式似乎有点不同,所以我不建议使用它。这就是一切的运作方式。

PowerShell 有一个内置函数,称为提示。但您可以按照您喜欢的任何方式重新定义此函数。一年来我分享了许多提示功能。这就是我今天正在尝试的。

[玩转系统] 周五乐趣:让您的 PowerShell 提示符焕然一新

提示将改变您所在位置的颜色。我还要插入当前时间。这是我正在使用的代码。

#this won't display properly on Linux
Function prompt {
    # .Description
    # This custom version of the PowerShell prompt will present a colorized location value based on the current provider. It will also display the PS prefix in red if the current user is running as administrator.    
    # .Link
    # https://go.microsoft.com/fwlink/?LinkID=225750
    # .ExternalHelp System.Management.Automation.dll-help.xml
 
    $user = [Security.Principal.WindowsIdentity]::GetCurrent()
    if ( (New-Object Security.Principal.WindowsPrincipal $user).IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)) {
        $adminfg = "Red"
    }
    else {
        $adminfg = $host.ui.rawui.ForegroundColor
    }

    Switch ((get-location).provider.name) {
        "FileSystem" { $fg = "green"}
        "Registry" { $fg = "magenta"}
        "wsman" { $fg = "cyan"}
        "Environment" { $fg = "yellow"}
        "Certificate" { $fg = "darkcyan"}
        "Function" { $fg = "gray"}
        "alias" { $fg = "darkgray"}
        "variable" { $fg = "darkgreen"}
        Default { $fg = $host.ui.rawui.ForegroundColor}
    } 

    Write-Host "[$((Get-Date).timeofday.tostring().substring(0,8))] " -NoNewline
    Write-Host "PS " -nonewline -ForegroundColor $adminfg
    Write-Host "$($executionContext.SessionState.Path.CurrentLocation)" -foregroundcolor $fg -nonewline
    Write-Output "$('>' * ($nestedPromptLevel + 1)) "  
}

主要部分是一个 Switch 语句,它根据当前位置的底层 PS 提供程序分配一个颜色变量。然后,我使用 Write-Host 构建提示,以不同的颜色显示不同的部分。提示函数需要返回一些内容,因此最后一行使用 Write-Output 来提供 >。您可能还注意到函数开头的一些代码。如果当前用户正在提升的会话中运行,那么我想以红色显示提示的 PS 部分以提供视觉提醒。

[玩转系统] 周五乐趣:让您的 PowerShell 提示符焕然一新

要使用此提示,我可以将该函数放入配置文件脚本中,也可以将其放入单独的文件中并随时点源它。

我希望你能尝试一下,至少体验一下。最坏的情况是,重新启动 PowerShell 会话,您就会恢复正常。周末愉快。

您需要 登录账户 后才能发表评论

取消回复欢迎 发表评论:

关灯