Hi,
I have a powershell script which is a function and takes parameters. From with the powershell command shell, how do I execute a function? It seems like it works differently for different users.
Hi,
I have a powershell script which is a function and takes parameters. From with the powershell command shell, how do I execute a function? It seems like it works differently for different users.
Take a look at this post, maybe it is the right for you. http://stackoverflow.com/questions/1293907/how-to-pass-command-line-arguments-to-a-powershell-ps1-file
Anyway, the built-in $args variable is an array that holds all the command line arguments.
Is your script, simply a script or does it contain a function? If it is a script and takes parameters it will look something like this:
-- top of file foo.ps1 --
param($param1, $param2)
<script here>
You invoke that just like a cmdlet excecpt that if you are running from the current dir you have to specify the path to the script like so:
.\foo.ps1 a b
Also note that you pass arguments to scripts (and functions) space separated just like you do with cmdlets.
You mentioned function, so if you script looks like this you have a couple of options:
-- top of file foo.ps1 --
function foo ($param1, $param2) {
<script here>
}
If you run foo.ps1 like above, nothing will happen other than you will define a function called foo in a temporary scope and that scope will go away when the script exits. You could add a line to the bottom of the script that actually calls the foo function. But perhaps you are intending on using this script more as a reusable function library. In that case you probably want to load
the functions into the current scope. You can do that with the dot source operator .
like so:
C:\PS> . .\foo.ps1
C:\PS> foo a b
Now function foo will be defined at the global level. Note that you could do the same thing within another script which will load that function into the script's scope.