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

[玩转系统] 及时的 PowerShell 提示

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

及时的 PowerShell 提示


[玩转系统] 及时的 PowerShell 提示

因此,我认为将时钟作为 PowerShell 提示符的一部分可能会很方便。 PowerShell 有一个名为 Prompt 的内置函数,但您可以将其替换为您自己的版本。该功能只会在您的 PowerShell 会话期间持续有效,因此如果您不喜欢它,请退出并重新启动 PowerShell。

Function Prompt {

#get current cursor position
$Coordinate = $host.ui.RawUI.CursorPosition
$running = $True
#set a variable to determine if the user is typing something
$Typing = $False

While ($Running) {
 #set the cursor position
  $host.ui.rawui.CursorPosition=$Coordinate
 $p = "[{0}] PS {1}>" -f (Get-Date -DisplayHint time),(Get-Location).Path
 Write-Host $p -NoNewline
 Start-Sleep -milliseconds 250

 if (-Not $Typing) {
 #see if a key has been pushed
    if ($host.ui.RawUi.KeyAvailable) {
        #user is typing
        $Typing = $True
        $running = $False
        #function needs to return something
        return " "
    } #if key available
 } #if not typing  
} #while

} #end function

这在很大程度上是显示 PS 和您当前位置的基本功能。该提示功能在PowerShell ISE中将无法正常工作。神奇之处在于始终将光标设置到 PowerShell shell 控制台中的相同坐标。我使用与其他函数中使用的相同类型的 While 循环,只是这次我等待用户按下任意键,这将指示开始键入命令。一旦检测到这一点,循环就会停止,提示中的时间也不再刷新。

您确实需要现场观看,但这里有一个屏幕截图示例。

[玩转系统] 及时的 PowerShell 提示

然后我认为让时钟脱颖而出可能会有所帮助,所以我添加了一点颜色。

Function Prompt {

<#
this version writes the clock in a different color

#>
#get current cursor position
$Coordinate = $host.ui.RawUI.CursorPosition
#variable for looping
$running = $True
#set a variable to determine if the user is typing something
$Typing = $False

While ($Running) {
 #set the cursor position
  $host.ui.rawui.CursorPosition=$Coordinate
 $d = "[{0}]" -f (Get-Date -DisplayHint time)
 $p = " PS {0}>" -f (Get-Location).Path
 Write-Host $d -NoNewline -ForegroundColor Yellow
 Write-Host $p -NoNewline
 Start-Sleep -milliseconds 250

 if (-Not $Typing) {

 #see if a key has been pushed
    if ($host.ui.RawUi.KeyAvailable) {
        #user is typing
        $Typing = $True
        $running = $False
        #function needs to return something
        return " "
    } #if key available
 } #if not typing  
} #while

} #end function

[玩转系统] 及时的 PowerShell 提示

我发现这些提示的唯一问题是,如果您需要在控制台窗口中滚动,则需要按空格键或键入一些内容,以便时钟停止刷新。否则,当 PowerShell 尝试写入控制台时,您会滚动。

您可以使用倒计时器代替时钟。或者也许是某种性能计数器。但对于提示,您需要确保可以在几百毫秒内获取并显示信息,否则提示会感觉缓慢且无响应。

享受并让我知道这将带您走向何方。

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

取消回复欢迎 发表评论:

关灯