Use Alias only for parameters in function - function

How can i use alias only when i call my cmdlet function ?
This is my code
Function Deploy-Citrix {
[cmdletBinding(SupportsShouldProcess=$True)]
Param(
[Parameter(Mandatory=$true)]
[Alias("component")]
[ValidateNotNullOrEmpty()]
[string]$componentparam,
[Parameter(Mandatory=$true)]
[Alias("ip")]
[ValidateNotNullOrEmpty()]
[string]$ipaddressparam,
)
In this case for the second parameter for example, i can use the alias -ip but i can also use -ipaddressparam.
Deploy-citrix -componentparam "toto" -ipaddressparam "172.22.0.100"
Deploy-citrix -component "toto" -ip "172.22.0.100"
I can use both, but i want to disable the first one, i want to have alias only.
I know i can rename my variable, but i don't want to touch them in the whole script.
How can i achieve that?
I'm using Powershell V4.0
Thanks

If your goal is disallow the long form, you have no choice but to rename the parameter and remove the alias.
To minimize changes to your script, you can create a variable inside the function, e.g.
Function Deploy-Citrix {
[cmdletBinding(SupportsShouldProcess=$True)]
Param(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]$ip)
$ipaddressparam = $ip
...

Related

passing a parameter in a function, the second parameter is always null [duplicate]

If I have a function which accepts more than one string parameter, the first parameter seems to get all the data assigned to it, and remaining parameters are passed in as empty.
A quick test script:
Function Test([string]$arg1, [string]$arg2)
{
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
Test("ABC", "DEF")
The output generated is
$arg1 value: ABC DEF
$arg2 value:
The correct output should be:
$arg1 value: ABC
$arg2 value: DEF
This seems to be consistent between v1 and v2 on multiple machines, so obviously, I'm doing something wrong. Can anyone point out exactly what?
Parameters in calls to functions in PowerShell (all versions) are space-separated, not comma separated. Also, the parentheses are entirely unneccessary and will cause a parse error in PowerShell 2.0 (or later) if Set-StrictMode -Version 2 or higher is active. Parenthesised arguments are used in .NET methods only.
function foo($a, $b, $c) {
"a: $a; b: $b; c: $c"
}
ps> foo 1 2 3
a: 1; b: 2; c: 3
The correct answer has already been provided, but this issue seems prevalent enough to warrant some additional details for those wanting to understand the subtleties.
I would have added this just as a comment, but I wanted to include an illustration--I tore this off my quick reference chart on PowerShell functions. This assumes function f's signature is f($a, $b, $c):
Thus, one can call a function with space-separated positional parameters or order-independent named parameters. The other pitfalls reveal that you need to be cognizant of commas, parentheses, and white space.
For further reading, see my article Down the Rabbit Hole: A Study in PowerShell Pipelines, Functions, and Parameters. The article contains a link to the quick reference/wall chart as well.
There are some good answers here, but I wanted to point out a couple of other things. Function parameters are actually a place where PowerShell shines. For example, you can have either named or positional parameters in advanced functions like so:
function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string] $Name,
[Parameter(Mandatory=$true, Position=1)]
[int] $Id
)
}
Then you could either call it by specifying the parameter name, or you could just use positional parameters, since you explicitly defined them. So either of these would work:
Get-Something -Id 34 -Name "Blah"
Get-Something "Blah" 34
The first example works even though Name is provided second, because we explicitly used the parameter name. The second example works based on position though, so Name would need to be first. When possible, I always try to define positions so both options are available.
PowerShell also has the ability to define parameter sets. It uses this in place of method overloading, and again is quite useful:
function Get-Something
{
[CmdletBinding(DefaultParameterSetName='Name')]
Param
(
[Parameter(Mandatory=$true, Position=0, ParameterSetName='Name')]
[string] $Name,
[Parameter(Mandatory=$true, Position=0, ParameterSetName='Id')]
[int] $Id
)
}
Now the function will either take a name, or an id, but not both. You can use them positionally, or by name. Since they are a different type, PowerShell will figure it out. So all of these would work:
Get-Something "some name"
Get-Something 23
Get-Something -Name "some name"
Get-Something -Id 23
You can also assign additional parameters to the various parameter sets. (That was a pretty basic example obviously.) Inside of the function, you can determine which parameter set was used with the $PsCmdlet.ParameterSetName property. For example:
if($PsCmdlet.ParameterSetName -eq "Name")
{
Write-Host "Doing something with name here"
}
Then, on a related side note, there is also parameter validation in PowerShell. This is one of my favorite PowerShell features, and it makes the code inside your functions very clean. There are numerous validations you can use. A couple of examples are:
function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[ValidatePattern('^Some.*')]
[string] $Name,
[Parameter(Mandatory=$true, Position=1)]
[ValidateRange(10,100)]
[int] $Id
)
}
In the first example, ValidatePattern accepts a regular expression that assures the supplied parameter matches what you're expecting. If it doesn't, an intuitive exception is thrown, telling you exactly what is wrong. So in that example, 'Something' would work fine, but 'Summer' wouldn't pass validation.
ValidateRange ensures that the parameter value is in between the range you expect for an integer. So 10 or 99 would work, but 101 would throw an exception.
Another useful one is ValidateSet, which allows you to explicitly define an array of acceptable values. If something else is entered, an exception will be thrown. There are others as well, but probably the most useful one is ValidateScript. This takes a script block that must evaluate to $true, so the sky is the limit. For example:
function Get-Something
{
Param
(
[Parameter(Mandatory=$true, Position=0)]
[ValidateScript({ Test-Path $_ -PathType 'Leaf' })]
[ValidateScript({ (Get-Item $_ | select -Expand Extension) -eq ".csv" })]
[string] $Path
)
}
In this example, we are assured not only that $Path exists, but that it is a file, (as opposed to a directory) and has a .csv extension. ($_ refers to the parameter, when inside your scriptblock.) You can also pass in much larger, multi-line script blocks if that level is required, or use multiple scriptblocks like I did here. It's extremely useful and makes for nice clean functions and intuitive exceptions.
You call PowerShell functions without the parentheses and without using the comma as a separator. Try using:
test "ABC" "DEF"
In PowerShell the comma (,) is an array operator, e.g.
$a = "one", "two", "three"
It sets $a to an array with three values.
Function Test([string]$arg1, [string]$arg2)
{
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
Test "ABC" "DEF"
If you're a C# / Java / C++ / Ruby / Python / Pick-A-Language-From-This-Century developer and you want to call your function with commas, because that's what you've always done, then you need something like this:
$myModule = New-Module -ascustomobject {
function test($arg1, $arg2) {
echo "arg1 = $arg1, and arg2 = $arg2"
}
}
Now call:
$myModule.test("ABC", "DEF")
and you'll see
arg1 = ABC, and arg2 = DEF
Because this is a frequent viewed question, I want to mention that a PowerShell function should use approved verbs (Verb-Noun as the function name).
The verb part of the name identifies the action that the cmdlet performs. The noun part of the name identifies the entity on which the action is performed. This rule simplifies the usage of your cmdlets for advanced PowerShell users.
Also, you can specify things like whether the parameter is mandatory and the position of the parameter:
function Test-Script
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true, Position=0)]
[string]$arg1,
[Parameter(Mandatory=$true, Position=1)]
[string]$arg2
)
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
To pass the parameter to the function you can either use the position:
Test-Script "Hello" "World"
Or you specify the parameter name:
Test-Script -arg1 "Hello" -arg2 "World"
You don't use parentheses like you do when you call a function within C#.
I would recommend to always pass the parameter names when using more than one parameter, since this is more readable.
If you don't know (or care) how many arguments you will be passing to the function, you could also use a very simple approach like;
Code:
function FunctionName()
{
Write-Host $args
}
That would print out all arguments. For example:
FunctionName a b c 1 2 3
Output
a b c 1 2 3
I find this particularly useful when creating functions that use external commands that could have many different (and optional) parameters, but relies on said command to provide feedback on syntax errors, etc.
Here is a another real-world example (creating a function to the tracert command, which I hate having to remember the truncated name);
Code:
Function traceroute
{
Start-Process -FilePath "$env:systemroot\system32\tracert.exe" -ArgumentList $args -NoNewWindow
}
If you try:
PS > Test("ABC", "GHI") ("DEF")
you get:
$arg1 value: ABC GHI
$arg2 value: DEF
So you see that the parentheses separates the parameters
If you try:
PS > $var = "C"
PS > Test ("AB" + $var) "DEF"
you get:
$arg1 value: ABC
$arg2 value: DEF
Now you could find some immediate usefulness of the parentheses - a space will not become a separator for the next parameter - instead you have an eval function.
I don't see it mentioned here, but splatting your arguments is a useful alternative and becomes especially useful if you are building out the arguments to a command dynamically (as opposed to using Invoke-Expression). You can splat with arrays for positional arguments and hashtables for named arguments. Here are some examples:
Note: You can use positional splats with external commands arguments with relative ease, but named splats are less useful with external commands. They work, but the program must accept arguments in the -Key:Value format as each parameter relates to the hashtable key/value pairs. One example of such software is the choco command from the Chocolatey package manager for Windows.
Splat With Arrays (Positional Arguments)
Test-Connection with Positional Arguments
Test-Connection www.google.com localhost
With Array Splatting
$argumentArray = 'www.google.com', 'localhost'
Test-Connection #argumentArray
Note that when splatting, we reference the splatted variable with an # instead of a $. It is the same when using a Hashtable to splat as well.
Splat With Hashtable (Named Arguments)
Test-Connection with Named Arguments
Test-Connection -ComputerName www.google.com -Source localhost
With Hashtable Splatting
$argumentHash = #{
ComputerName = 'www.google.com'
Source = 'localhost'
}
Test-Connection #argumentHash
Splat Positional and Named Arguments Simultaneously
Test-Connection With Both Positional and Named Arguments
Test-Connection www.google.com localhost -Count 1
Splatting Array and Hashtables Together
$argumentHash = #{
Count = 1
}
$argumentArray = 'www.google.com', 'localhost'
Test-Connection #argumentHash #argumentArray
Function Test([string]$arg1, [string]$arg2)
{
Write-Host "`$arg1 value: $arg1"
Write-Host "`$arg2 value: $arg2"
}
Test("ABC") ("DEF")
I don't know what you're doing with the function, but have a look at using the 'param' keyword. It's quite a bit more powerful for passing parameters into a function, and makes it more user friendly. Below is a link to an overly complex article from Microsoft about it. It isn't as complicated as the article makes it sound.
Param Usage
Also, here is an example from a question on this site:
Check it out.
I stated the following earlier:
The common problem is using the singular form $arg, which is incorrect. It should always be plural as $args.
The problem is not that. In fact, $arg can be anything else. The problem was the use of the comma and the parentheses.
I run the following code that worked and the output follows:
Code:
Function Test([string]$var1, [string]$var2)
{
Write-Host "`$var1 value: $var1"
Write-Host "`$var2 value: $var2"
}
Test "ABC" "DEF"
Output:
$var1 value: ABC
$var2 value: DEF
Function Test {
Param([string]$arg1, [string]$arg2)
Write-Host $arg1
Write-Host $arg2
}
This is a proper params declaration.
See about_Functions_Advanced_Parameters.
And it indeed works.
You can pass parameters in a function like this also:
function FunctionName()
{
Param ([string]$ParamName);
# Operations
}

Mandatory parameter for inner function

I'm stuck trying to figure out the best method for calling a function from a function and making parameters mandatory for both functions. I've got the below so far, and things work because I know what cmdline params to specify.
I did find this post but I'm not sure how to use that with a function that calls a function.
Edit: added shorter code. In the code, How would you make the ParamSet parameter [string]$killserver mandatory for both the parent function main and the child function KillSwitch so that if the function is run main -nukejobs Powershell prompts for the variable $killserver
Edit 2: worked out the prompting for the mandatory param serverlist and datelist but it appears now the child function doesn't write to host "receive input from $serverlist and $datelist"
Edit 3: corrected the Switch ($PSCmdlet.ParameterSetName){ value for RunMulti and now things look good.
Function Main{
[CmdletBinding(SupportsShouldProcess=$true,DefaultParameterSetName="ViewOnly")]
Param(
[Parameter(Mandatory=$false,ParameterSetName="KillSwitch")]
[Switch]$NukeJobs,
[Parameter(Mandatory=$true,ParameterSetName="KillSwitch",
HelpMessage="Enter ServerName to remove the scheduled reboot for, Check using main -viewonly")]
[String]$killserver,
[Parameter(Mandatory=$false,ParameterSetName="RunMulti")]
[switch]$RunMultiple,
[Parameter(Mandatory=$true,ParameterSetName="RunMulti")]
[String]$serverlist,
[Parameter(Mandatory=$true,ParameterSetName="RunMulti")]
[String]$datelist
)
Switch ($PSCmdlet.ParameterSetName) {
"KillSwitch" {
KillSwitch -server $killserver
} # end killswitch
"RunMulti" {
RunMulti -serverlist $serverlist -datelist $datelist
} # end run multi
} # end switch block
} # end main function
Function KillSwitch{
Param(
[Parameter(Mandatory=$true)]
[String]$server
)
"Removing previous scheduled reboot for $server"
} # end killswitch function
Function RunMulti {
Param(
[Parameter(Mandatory=$true,
HelpMessage="Text file with server names to reboot, one per line!")]
[string]$serverlist,
[Parameter(Mandatory=$true,
HelpMessage="Text file with date/times, one per line!")]
[String]$datelist
)
"receive input from $serverlist and $datelist"
}
I found the mandatory parameters needed separate:
[Parameter(Mandatory=$true,ParameterSetName="RunOnce")] blocks.
For example, this won't work, even if Mandatory=$true
My guess is because it only applies to [switch]
[Parameter(Mandatory=$false,ParameterSetName="RunOnce",
HelpMessage="Enter ServerName to schedule reboot for.")]
[switch]$RunOnce,
[string]$server,
[string]$date,
But this will work, causing Powershell to prompt for $server and $date when the RunOnce switch is given.
[Parameter(Mandatory=$false,ParameterSetName="RunOnce",
HelpMessage="Enter ServerName to schedule reboot for.")]
[switch]$RunOnce,
[Parameter(Mandatory=$true,ParameterSetName="RunOnce")]
[string]$server,
[Parameter(Mandatory=$true,ParameterSetName="RunOnce")]
[string]$date,

Correct Way To Request Parameters In Powershell

I'm trying to figure out the correct way to request parameters in a PowerShell script without using a function. With the following sample script I get an error if I don't include the Param within the function.
#Add SharePoint PowerShell SnapIn if not already added
if ((Get-PSSnapin "Microsoft.SharePoint.PowerShell" -ErrorAction SilentlyContinue) -eq $null) {
Add-PSSnapin "Microsoft.SharePoint.PowerShell"
}
function SomeFunctionName
{
Param(
[Parameter(Mandatory=$true)]
[string]$CollectionUrl,
[Parameter(Mandatory=$true)]
[string]$SourceList,
[Parameter(Mandatory=$true)]
[string]$DestList,
[Parameter(Mandatory=$true)]
[string]$ExpireDays
) # END PARAMS
#DO SOMETHING WITH THE PARAMETERS
}
If I remove the "function" and surrounding brackets just try to request parameters directly in the script I get the following error:
Missing closing ')' in expression.
You need to put the param(...) block at the top of the script before the If/Add-PSSnapin. You can have comments before the param but no other script.

Wrap existing powershell script as function?

I have a script like this:
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
$Message
)
Write-Host "Hello, $Message!"
But I want to provide a method that allows users to dot source the script. Initially, I was just thinking I would wrap the whole script in a function to allow dot sourcing:
function Hello
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
$Message
)
Write-Host "Hello, $Message!"
}
The problem with this is that if I did this, it would break the script for some people who are using it the old way. Is it possible to return an object with the same functionality as the script, or is there a way to dot source the script as it is (the first example above)?
I would suggest using splatting with $PSBoundParameters:
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
$Message
)
function Hello
{
[CmdletBinding()]
param(
[Parameter(Mandatory=$true)]
$Message
)
Write-Host "Hello, $Message!"
}
Hello #PSBoundParameters
Alternatively: instead of dot-sourcing just create function from existing script:
$code = Get-Content .\HelloScript.ps1
New-Item -Path function:\Hello -Value ([scriptblock]::Create($code))
At the end of function Hello you must trigger it to simulate old behaviour. So if the script used to take an argument from command line, lets say c:\scripts\hello.ps1 bob, you can do it as so:
function Hello
{
...
}
if($args.Count -eq 0){
Hello $null
}
else{
Hello $args
}
$args will be an empty array if you were to run c:\scripts\newhello.ps1 without an argument, rather than $null as previously when no value was passed. Therefore we check $args.Count before triggering the function with correct parameter.
I know this is incredibly old but I just ran into it while doing something similar. I have a Foo.ps1 script that needs to work as a script but that I would also like available as one function exported from a module. It seems (I just started playing with it) as if putting the following (in Foo.psm1) function Foo { . "$PSScriptRoot\Foo.ps1" } works like a charm. Avoids having to write out all the arguments in two places.

Powershell: Functions with switches that include arguments

So I'm trying to write a script that uses switch parameters and I also need arguments to go along with them. So for instance,
Function Foo ($X, $Z, [switch]$Y, $Yarg, [switch]$K, $Karg){
if($Y){
$Yup = $Yarg
}
if($K){
$Y = $Karg
}Else{$Y = 42}
$X + $Z / $Yup
}
Essentialy I want to ask if the switch is there, then if it's there I want it to use the $Yarg variable, currently when I do that I get an error saying the switch can only be a boolean value. Then the rest of the code fails. Any ideas?
My assumption is that Y and K are mutually exclusive parameter sets, and X and Z are common to both, and mandatory. If neither -Y nor -K are specified, the default will be -Y. I'm using the alternate parameter declaration syntax here for clarity:
function Foo(
[cmdletbinding(defaultparametersetname="setY")]
param(
[parameter(mandatory=$true)]
$X,
[parameter(mandatory=$true)]
$Y
[parameter(parametersetname="setY")]
[switch]$Y,
[parameter(parametersetname="setY", mandatory=$true)]
$YArg,
[parameter(parametersetname="setK")]
[switch]$K,
[parameter(parametersetname="setK", mandatory=$true)]
$KArg,
)
# do work
)
I'm hoping the syntax should be obvious.
So what I am intending on doing is making a function where you enter variables like so
foo x z -y yarg -k karg
Primarily wanting the -y yarg type variable entry.
For me to be able to do this I thought I needed to use a switch, but really I just needed unmandatory parameters.
function Foo(
[cmdletbinding(defaultparametersetname="setY")]
param(
[parameter(mandatory=$true, position=0)]
$X,
[parameter(mandatory=$true, position=1)]
$Z
[parameter(mandatory=$false)]
$Y,
[parameter(mandatory=$false)]
$K
)
# do work
)
That seemed easier, and it works!