5

Considering the PowerShell code example here:

powershell code

It has [CmdletBinding()] on top of the .ps1 scipt file.

Please note that [CmdletBinding()] is on top of the file, not the function.

How do I call this file from commandline and assign values to the parameters?

What is the name of this technique, so I can search and learn more about the concept?

Uuuuuumm
  • 608
  • 5
  • 21
Allan Xu
  • 7,998
  • 11
  • 51
  • 122
  • 4
    `help about_Functions_CmdletBindingAttribute` ? – Bill_Stewart Aug 06 '20 at 19:39
  • 3
    That just means you can call the file name like a function. ex: `file.ps1 -param1 "Hello World"` – Uuuuuumm Aug 06 '20 at 19:39
  • 2
    Does this answer your question? [What is \[cmdletbinding()\] and how does it work?](https://stackoverflow.com/questions/14671051/what-is-cmdletbinding-and-how-does-it-work) – JosefZ Aug 06 '20 at 19:53
  • 1
    Think of a file as a large function with a file extension, you can assign parameters to a file with `param` just like you can with a function, with that you can also use `[cmdletbinding()]` on files just like you can in functions. – Nico Nekoru Aug 06 '20 at 22:00
  • @NekoMusume, thanks. Please add your answer so I can mark is as answer. – Allan Xu Aug 06 '20 at 23:04
  • @JosefZ, not it doesn't. consider my comment "Please note that [CmdletBinding()] is on top of the file, not the function.". Neko answered my question. – Allan Xu Aug 06 '20 at 23:06

1 Answers1

8

Think of a file as a large function with a file extension, you can assign parameters to a file with param just like you can with a function, with that you can also use [CmdletBinding()] on files just like you can in functions. For example, if I have a file that has multiple switches and can take arguments I could do something like

[CmdletBinding()]
param([switch]$a,
      [string]$b)
if ($a) {return Write-Host $b -ForegroundColor red}
return Write-Host $b

Would be the same as doing

function MyName {
    [CmdletBinding()]
    param([switch]$a
        [string]$b)
    if ($a) {return Write-Host $b -ForegroundColor red}
    return Write-Host $b
}

and you could call them with

#file
.\MyName.ps1 -a -b Test

or

#function
MyName -a -b Test

and they will have the same output., a red Test

Unlike batch files (.bat) you cannot directly call a ps1 script just with its name, so just using MyName -a -b Test without the function being defined will result in an error.

InteXX
  • 6,135
  • 6
  • 43
  • 80
Nico Nekoru
  • 2,840
  • 2
  • 17
  • 38