Accepting Parameters
$srcDir = "C:"
$srcFile = "$SrcDir\ClientGL.xlsx"
$srcTab = "Sheet1"
$outFile = "$SrcDir\ClientGL.txt"
Consider making these parameters that can be passed to the script. You could also make them have defaults that way.
Top of script:
[CmdletBinding()
param(
[Parameter(
Mandatory=$false
)]
[String]
$Path = "C:" ,
[Parameter(
Mandatory=$false
)]
[String]
$srcTab = "Sheet1"
)
$srcFile = "$Path\ClientGL.xlsx"
$outFile = "$Path\ClientGL.txt"
Now you can call the script like so:
.\MyScript.ps1 -Path "C:\Some\Other\Path\" -srcTab "Expenses"
Now you can see why using Join-Path
would save you some headache because you're accepting user input!
Just to break down this param()
block a bit:
[Parameter()]
can take multiple comma separated options; I've shown you Mandatory
. Mandatory means mandatory to be supplied by the caller
not to have a value, so when you use a default value like we are here, you don't want to make the parameter mandatory. Parameters are by default optional, so this was unnecessary; I was just demonstrating it.
The entire [Parameter()]
attribute is also optional, and could be left out.
[String]
is specifying the data type for the parameter. PowerShell will try to coerce input values into this type if possible. Data type is also optional.
$Path
: this is the name of the parameter. It is the only part that's mandatory. I used $Path
instead of $srcDir
because PowerShell has conventions for certain names to represent certain things.
So generally any cmdlet or function that accepts a path will use -Path
. Same for -ComputerName
, -Identity
, -Credential
.
Also note that all of these pieces could have been on a single line. I like to separate them for clarity.
For more on these, have a look at Create a Truly Advanced PowerShell Function and the about_Functions_Advanced and about_Functions_Advanced_Parameters help topics.