正如你们所知,我可以在 Power Shell 窗口中使用 clear 或 cls。
但是我发现clear(5)或cls(5)有效,也可以清除屏幕(任何数字都有效,包括负数)。但是如果我尝试像clear(abc)或clear(“abc”)这样的东西,它会抛出错误
abc:术语“abc”未被识别为 cmdlet、函数、脚本文件或可执行程序的名称。 检查名称的拼写,或者如果包含路径,请验证路径是否正确,然后重试。
为什么它接受一个数字,如果这个数字没有做任何事情(不是要清除的行数或任何东西),为什么会抛出非数字错误?
最佳答案
构建于 Santiago Squarzon的评论:Clear-Host
命令是一个函数。您可以通过运行看到这一点:
Get-Command Clear-Host -OutVariable cmd
输出
CommandType Name
----------- ----
Function Clear-Host
由于函数是用PowerShell编写的,您还可以查看内容(定义):
$cmd.Definition
输出(Windows PowerShell 5.1)
$RawUI = $Host.UI.RawUI
$RawUI.CursorPosition = @{X=0;Y=0}
$RawUI.SetBufferContents(
@{Top = -1; Bottom = -1; Right = -1; Left = -1},
@{Character = ' '; ForegroundColor = $rawui.ForegroundColor; BackgroundColor = $rawui.BackgroundColor})
# .Link
# https://go.microsoft.com/fwlink/?LinkID=225747
# .ExternalHelp System.Management.Automation.dll-help.xml
输出(PowerShell 7.1.3,在 Linux 上)
[Console]::Write((
& (Get-Command -CommandType Application clear | Select-Object -First 1).Definition
))
# .Link
# https://go.microsoft.com/fwlink/?LinkID=2096480
# .ExternalHelp System.Management.Automation.dll-help.xml
您可以查看about_Functions_Advanced
阅读有关此内容的更多信息,但如果没有[CmdletBinding()]
,它不是一个“高级”函数,因此它不会以相同的方式验证其参数。
相反,该函数可以访问 $args
中的未命名参数,但正如您在定义中看到的那样,它不能。
Get-Help Clear-Host
将向您显示它不需要任何参数:
NAME
Clear-Host
SYNOPSIS
SYNTAX
Clear-Host [<CommonParameters>]
DESCRIPTION
RELATED LINKS
https://go.microsoft.com/fwlink/?LinkID=225747
REMARKS
To see the examples, type: "get-help Clear-Host -examples".
For more information, type: "get-help Clear-Host -detailed".
For technical information, type: "get-help Clear-Host -full".
For online help, type: "get-help Clear-Host -online"
即使是命名参数的非高级函数也会让它们显示在帮助输出中:
function Test-Thing($one, $two) {}
Get-Help Test-Thing
输出
NAME
Test-Thing
SYNTAX
Test-Thing [[-one] <Object>] [[-two] <Object>]
ALIASES
None
REMARKS
None
关于windows - 为什么 power shell clear(或 cls)命令接受数字作为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72194824/