Home > Software design >  Why power shell clear (or cls) command accepts a number as parameter?
Why power shell clear (or cls) command accepts a number as parameter?

Time:05-12

From a Power Shell window, I can use the clear or cls as you all know.

But messing around I found that clear(5) or cls(5) works, also clear the screen (any number works, including negative numbers). But if I try something like clear(abc) or clear("abc") it throws error

abc: The term 'abc' is not recognized as a name of a cmdlet, function, script file, or executable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

Why it accepts a number, if the number doesn't do anything (is not the number of lines to clear or anything), and why throws error with non-numerical?

CodePudding user response:

Building on Santiago Squarzon's comment: the Clear-Host command is a function. You can see this by running:

Get-Command Clear-Host -OutVariable cmd
Output
CommandType     Name
-----------     ----
Function        Clear-Host

Since functions are written in PowerShell, you can also view the contents (definition):

$cmd.Definition
Output (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
Output (PowerShell 7.1.3, on 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

You can view about_Functions_Advanced to read more about this, but without [CmdletBinding()], it's not an "advanced" function and so it won't be validating its arguments in the same way.

Instead the function can access its unnamed arguments in $args but as you can see in the definition, it does not.

Get-Help Clear-Host will show you that it is not expecting any parameters:

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"

Even a non-advanced function that names parameters will have them show up in help output:

function Test-Thing($one, $two) {}
Get-Help Test-Thing
Output
NAME
    Test-Thing

SYNTAX
    Test-Thing [[-one] <Object>] [[-two] <Object>]


ALIASES
    None


REMARKS
    None
  • Related