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

Leave a comment

February 17, 2020 by Kenneth Fisher

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:\PoshScripts\Read-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:\PoshScripts\Read-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:\PoshScripts\Read-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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Enter your email address to follow this blog and receive notifications of new posts by email.

Join 3,106 other followers

Follow me on Twitter

ToadWorld Pro of the Month November 2013
%d bloggers like this: