Reputation: 9328
Considering the PowerShell code example here:
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?
Upvotes: 6
Views: 4898
Reputation: 3112
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.
Upvotes: 8