Powershell查看支持的函数


Powershell已经提供了许多用户能够使用的预定义函数,这些函数可以通过Function:PSDrive虚拟驱动器查看。

PS E:mossfly.com> dir function: | ft -AutoSize

CommandType Name                Definition
----------- ----                ----------
Function    A:                  Set-Location A:
Function    B:                  Set-Location B:
Function    C:                  Set-Location C:
Function    cd..                Set-Location ..
Function    cd                 Set-Location
Function    Clear-Host          $space = New-Object System.Management.Automa...
Function    D:                  Set-Location D:
Function    Disable-PSRemoting  ...
Function    E:                  Set-Location E:
Function    F:                  Set-Location F:
Function    G:                  Set-Location G:
Function    Get-Verb            ...
Function    H:                  Set-Location H:
Function    help                ...
Function    I:                  Set-Location I:
Function    ImportSystemModules ...
Function    J:                  Set-Location J:
Function    K:                  Set-Location K:
Function    L:                  Set-Location L:
Function    M:                  Set-Location M:
Function    mkdir               ...
Function    more                param([string[]]$paths)...
Function    N:                  Set-Location N:
Function    O:                  Set-Location O:
Function    P:                  Set-Location P:
Function    prompt              $(if (test-path variable:/PSDebugContext) { ...
Function    Q:                  Set-Location Q:
Function    R:                  Set-Location R:
Function    S:                  Set-Location S:
Function    T:                  Set-Location T:
Function    TabExpansion        ...
Function    U:                  Set-Location U:
Function    V:                  Set-Location V:
Function    W:                  Set-Location W:
Function    X:                  Set-Location X:
Function    Y:                  Set-Location Y:
Function    Z:                  Set-Location Z:

从这些结果不但能够看出函数的名称,还能通过Definition列查看函数的内容。如果你想深入查看函数的内部定义可以直接访问Function:

PS E:mossfly.com> $function:prompt
$(if (test-path variable:/PSDebugContext) { '[DBG]: ' } else { '' }) + 'PS ' +
$(Get-Location) + $(if ($nestedpromptlevel -ge 1) { '>>' }) + '> '

Powershell中的这些预定义的函数可以做很多重要的工作。

Clear-Host 清除屏幕的缓存
help,man 查看命令的帮助文档
mkdir,md 通过new-Item创建子目录
more 分屏输出管道结果
prompt 返回提示文本
TabExpansion Tab键的自动完成提示
X: 调用Set-Location定位到指定的驱动器根目录

如果你想查看当前Powershell环境中定义了多少个函数可以通过

PS E:mossfly.com> (dir function:).count
37
PS E:mossfly.com>

自定义Prompt

每次成功执行完一条命令,Powershell就会执行Prompt函数,提示用户进行下一步输入。默认设置中,prompt显示“PS” 和当前的工作目录
。再接着是”>”或”>>”,具体情况要看当前Powershell控制台的的层数。当然你可以自定义prompt的,那就得覆盖prompt函数:

PS E:mossfly.com> pwd

Path
----
E:mossfly.com

PS E:mossfly.com> cd ..
PS E:> Function Prompt {"www.mossfly.com"}
www.mossfly.com
www.mossfly.com pwd

Path
----
E:
www.mossfly.com $function:prompt
"www.mossfly.com"
www.mossfly.com

这样的覆盖安全吗,显然安全,对预定义函数的重写,只会在当前控制台会话中有效,当你重新启动控制台时,自然会恢复如初。

在控制台的任何位置输出文本(自定义光标的位置)

因为控制台的内容存放在控制台屏幕的缓存中,因此你可以逐个访问内容的每一行或每一个字符。你甚至可以在控制台的屏幕的任何位置输出你想要输出的信息,接下来的函数会演示这个功能。要完成这个功能,需要使用$Host.UI.Rawui ,光标的位置通过屏幕的横坐标(X)和纵坐标(Y)确定,下面的函数会首先记住当前光标的位置,然后在横坐标上增加60个占位符,然后重置光标的位置至当前位置,最后通过prompt函数回复光标的原始位置。

function prompt
{
	$curPos = $host.ui.rawui.CursorPosition
	$newPos = $curPos
	$newPos.X+=60
	$host.ui.rawui.CursorPosition = $newPos
	Write-Host ("{0:D} {0:T}" -f (Get-Date)) -foregroundcolor Yellow
	$host.ui.rawui.CursorPosition = $curPos
	Write-Host ("PS " + $(get-location) +">") -nonewline -foregroundcolor Green
" "
}

运行结果

PS E:mossfly.com> function prompt
>> {
>>     $curPos = $host.ui.rawui.CursorPosition
>>     $newPos = $curPos
>>     $newPos.X+=60
>>     $host.ui.rawui.CursorPosition = $newPos
>>     Write-Host ("{0:D} {0:T}" -f (Get-Date)) -foregroundcolor Yellow
>>     $host.ui.rawui.CursorPosition = $curPos
>>     Write-Host ("PS " + $(get-location) +">") -nonewline -foregroundcolor Gre
en
>> " "
>> }
>>
PS E:mossfly.com>                                          2012年2月28日 8:54:01

使用窗口标题栏

在Windows控制台的标题栏有一部分空间,可以放置一些有用的信息,比如当前哪个用户登录在控制台,可以通过设置$host.UI.RawUI.WindowTitle来自定义控制台标题栏的文本。
下面的例子就会演示设置标题栏文本,通过.NET方法获取当前用户信息,由于该方法会有几秒钟执行时间,为了效率考虑首先将用户信息保存在全局变量中,然后在Prompt函数中调用。

$global:CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
function prompt
{
$host.ui.rawui.WindowTitle = "Line: " + $host.UI.RawUI.CursorPosition.Y + " " + $CurrentUser.Name + " " + $Host.Name + " " + $Host.Version
Write-Host ("PS " + $(get-location) +">")  -nonewline -foregroundcolor Green
return " "
}

执行以后在标题栏会显示:Line: 72 ComputerNameuser ConsoleHost 2.0

如果你使用管理员权限运行控制台时,Prompt函数还可以给出警告。使用WindowsPrincipal 辨别当前用户是否使用了管理员权限,你不需要了解下面的.NET代码,它会在全局变量中将布尔值赋值给$Admin。

$CurrentUser = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$principal = new-object System.Security.principal.windowsprincipal($CurrentUser)
$global:Admin = $principal.IsInRole( [System.Security.Principal.WindowsBuiltInRole]::Administrator)
Function prompt
{
    # 输出标准的提示信息:
    Write-Host ("PS " + $(get-location)) -nonewline
    # The rest depends on whether you have admin rights or not:
    If ($admin)
    {
        $oldtitle = $host.ui.rawui.WindowTitle
        # 将"Administrator: " 显示在标题栏
        If (!$oldtitle.StartsWith("Administrator: "))
        {
            $host.ui.rawui.WindowTitle ="Administrator: " + $oldtitle
        }
        #  Prompt结尾显示红色的尖括号
        Write-Host ">" -nonewline -foregroundcolor Red
     }
     Else
     {
        Write-Host ">" -nonewline
      }
     return " "
}

没有管理员权限时,标题栏文本:Windows Powershell
有管理员权限时,标题栏文本:Administrator :管理员 : Windows Powershell

Clear-Host:删除屏幕缓存

很可能,你已经注意到了,cls可以删除屏幕的缓存。事实上,cls只是Clear-Host函数的别名,但是却看不到这个函数的内容。

PS E:mossfly.com> $function:Clear-Host
必须在“-”运算符的右侧提供值表达式。
所在位置 行:1 字符: 17
+ $function:Clear- <<<< Host
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordEx
   ception
    + FullyQualifiedErrorId : ExpectedValueExpression

在Powershell中短斜杠是个特殊字符,如果一个函数名中包含了特殊字符就应当把它放在花括号中。

PS E:mossfly.com> ${function:Clear-Host}
$space = New-Object System.Management.Automation.Host.BufferCell
$space.Character = ' '
$space.ForegroundColor = $host.ui.rawui.ForegroundColor
$space.BackgroundColor = $host.ui.rawui.BackgroundColor
$rect = New-Object System.Management.Automation.Host.Rectangle
$rect.Top = $rect.Bottom = $rect.Right = $rect.Left = -1
$origin = New-Object System.Management.Automation.Host.Coordinates
$Host.UI.RawUI.CursorPosition = $origin
$Host.UI.RawUI.SetBufferContents($rect, $space)

盘符名预定义函数C:,D:,E:

这些盘符名称可以作为单独的一个函数,是怎么做到的呢?

PS E:mossfly.com> $function:c:
Set-Location C:
PS E:mossfly.com> $function:d:
Set-Location D:
PS E:mossfly.com> $function:E:
Set-Location E:
PS E:mossfly.com> $function:A:
Set-Location A:
本文链接: https://www.pstips.net/powershell-inspect-available-func.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

关于 Mooser Lee

我是一个Powershell的爱好者,创建了PowerShell中文博客,热衷于Powershell技术的搜集和分享。本站部分内容来源于互联网,不足之处敬请谅解,并欢迎您批评指正。

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注