Blog Post

#PowershellBasics: Run a file and pass it a parameter.

,

I realized in my last #PowershellBasics post that I was talking about running a file and passing in an optional parameter but I didn’t describe how to do it. I decided that it was a distinct enough task that I’d make it it’s own post, so here we go.

Quick point. This is a basics post. I’m sure there are lots of ways to do this. This is the beginnings of my journey with Powershell and this is the only way I know to do it right now. If you have other methods for this feel free to mention them in the comments. Links to other posts are of course welcome too.

First of all we take the following code and save it to a file. I used Powershell ISE but it would be just as easy to use notepad or something like it. I named my file C:PoshScriptsRead-Host w Param.ps1

param
(
    $ShouldI? = (Read-Host -Prompt 'Well should I?')
)
If ($ShouldI? -eq 'Y') {
    Write-Host 'I did some stuff.'
 } Else {
    Write-Host 'I didn''t do anything.'
}

Close the file, or if you are running this in ISE you can just open a new tab. Now run this.

& "C:PoshScriptsRead-Host w Param.ps1"

Well should I?: N

I didn’t do anything.

Because I didn’t pass in a parameter the program used the Read-Host to prompt for the information. But if I pass a parameter:

& "C:PoshScriptsRead-Host w Param.ps1" "Y"

I did some stuff.

This time there was no prompt because the parameter was passed in.

Quick side notes:

  • The quotes around the file name were required because of the spaces in the name.
  • When calling the file there is no comma between the file name or between parameters if there are multiple parameters.

Original post (opens in new tab)
View comments in original post (opens in new tab)

Rate

3 (1)

You rated this post out of 5. Change rating

Share

Share

Rate

3 (1)

You rated this post out of 5. Change rating