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

[玩转系统] 周五乐趣:在 PowerShell 提示符中走捷径

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

周五乐趣:在 PowerShell 提示符中走捷径


为了开始新的一年,我想走捷径,回收 PowerShell 提示符中一些浪费的空间。我知道我在课堂和会议期间遇到了这个问题。或许你也遇到过。您位于 PowerShell 控制台中,最终进入了一个深层目录结构,因此您的提示符和控制台现在如下所示:

[玩转系统] 周五乐趣:在 PowerShell 提示符中走捷径

正如您所看到的,我的提示中没有太多剩余空间。通常,如果我待在一个位置(例如进行演示),我会创建一个名称较短的 PSDrive。我使用 PSScriptTools 模块中的 New-PSDriveHere 命令。但另一种选择是截断提示。因此,您在这里看到的长路径可能不是 C:\Users...\HelpDesk。我修改了默认的 PowerShell 提示函数来做到这一点。

ShortLocation-Prompt.ps1:


Function prompt {

    $location = $executionContext.SessionState.Path.CurrentLocation.path
    #what is the maximum length of the path before you begin truncating?
    $len = 33

    if ($location.length -gt $len) {

        #split on the path delimiter which might be different on non-Windows platforms
        $dsc = [system.io.path]::DirectorySeparatorChar
        #escape the separator character to treat it as a literal
        #filter out any blank entries which might happen if the path ends with the delimiter
        $split = $location -split "$($dsc)" | Where-Object { $_ -match "\S+" }
        #reconstruct a shorted path
        $here = "{0}$dsc{1}...$dsc{2}" -f $split[0], $split[1], $split[-1]

    }
    else {
        #length is ok so use the current location
        $here = $location
    }

    "PS $here$('>' * ($nestedPromptLevel + 1)) "
    # .Link
    # https://go.microsoft.com/fwlink/?LinkID=225750
    # .ExternalHelp System.Management.Automation.dll-help.xml

}

该函数被设计为跨平台工作,并且设计非常简单。如果当前位置的长度大于某个值,我的默认是33,则在目录分隔符上分割路径。这应该是\或 /。然后使用分割数组的前 2 个元素和最后一个元素构造一条缩短的路径。在两者之间,我插入了一个椭圆(...),尽管您可以使用任何您想要的东西。

看看当我加载新的提示函数时会发生什么:

[玩转系统] 周五乐趣:在 PowerShell 提示符中走捷径

现在我的提示位置会动态更新。

[玩转系统] 周五乐趣:在 PowerShell 提示符中走捷径

而且它还可以跨平台工作。

[玩转系统] 周五乐趣:在 PowerShell 提示符中走捷径

在 PowerShell 配置文件脚本中获取提示函数,一切就都准备好了。如果您遇到任何问题,请告诉我您的想法。享受并度过一个愉快的周末。

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

取消回复欢迎 发表评论:

关灯