Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell Function Name as "main" Strange Effect

Tags:

powershell

Check out this code:

main

function main
{
    cls
    Write-Host "hi"
}

If you run it for the first time, the windows Mouse Properties window will load.

Run it again and it will display "hi".

Why is this?

I understand that main.cpl is the Mouse Properties window. But why is it that it opens only the first time, then the 2nd time Powershell realises that you actually want to call the "main" function.

Shouldn't Powershell detect this and ask you to write main.cpl instead if you want the mouse properties window?

like image 554
David Klempfner Avatar asked Feb 26 '14 10:02

David Klempfner


People also ask

What is Backtick in PowerShell?

The backtick ` is used as the escape character in Powershell. That is, escaping quotes, tabs and whatnot. Unlike in many other environments, Powershell's newline is `n , not \n . This has the benefit of simplifying paths, since those use backslash in Windows.

What is $Global in PowerShell?

Global: The scope that is in effect when PowerShell starts or when you create a new session or runspace. Variables and functions that are present when PowerShell starts have been created in the global scope, such as automatic variables and preference variables.

What does the caret symbol do in PowerShell?

The ^ is reserved as the escape character in the cmd shell environment.

What does @{} mean in PowerShell?

The Splatting Operator To create an array, we create a variable and assign the array. Arrays are noted by the "@" symbol.


1 Answers

Because at the time main is called the first time, there is no function main, so PowerShell is looking for another thing called main to execute. The second time it knows about the main function and that gets precedence above main.cpl.

The solution is simple. Declare the main function before you call it the first time.

function main
{
    cls
    Write-Host "hi"
}

main

I do not have an answer why PowerShell decides to execute main.cpl when you type main, but the same goes for main.exe if you have it in $env:path.

like image 194
Lars Truijens Avatar answered Oct 07 '22 01:10

Lars Truijens