PowerShell Advanced Function get current ParameterSetName - powershell

In C# you can get the current ParameterSetName in the ProcessRecord override of a PowerShell Cmdlet with code like this:
switch (ParameterSetName)
{
case FromUriParamSetName:
loadFromUri();
break;
case FromFileParamSetName:
loadFromFile();
break;
}
I'm trying to figure out how I can get the value for ParameterSetName in a script cmdlet (Advanced Function).

Use $PsCmdlet.ParameterSetName:
switch ($PsCmdlet.ParameterSetName) {
"FromFile_ParamSet" {
}
"FromUri_ParamSet" {
}
}

As a way to expand this awesome answer:
switch ($PsCmdlet.ParameterSetName) {
"FromFile_ParamSet" {
}
"FromUri_ParamSet" {
}
"__AllParameterSets" {
}
}
The __AllparameterSets is the default option in PS

Related

PowerShell - how to determine programmatically whether StrictMode is set?

I know that I can override in a script or function the StrictMode setting inherited from a higher scope. But how can I find out in a script or function what the inherited setting is?
Perhaps a small function can help:
function Get-StrictMode {
# returns the currently set StrictMode version 1, 2, 3
# or 0 if StrictMode is off.
try { $xyz = #(1); $null = ($null -eq $xyz[2])}
catch { return 3 }
try { "Not-a-Date".Year }
catch { return 2 }
try { $null = ($undefined -gt 1) }
catch { return 1 }
return 0
}
Get-StrictMode

Access a field from a function call without an intermediate variable

Say I have the following powershell code:
function GetImageInfo()
{
[OutputType([ImageInfo])]
[ImageInfo] $imageInfo = [ImageInfo]::new()
$imageInfo.Owner = "Me"
$imageInfo.PrimaryTechnology = "jpeg"
$imageInfo.OperatingSystem = "Windows"
$imageInfo.OperatingSystemVersion = "10"
return $imageInfo
}
class ImageInfo
{
[string] $Owner
[string] $PrimaryTechnology
[string] $OperatingSystem
[string] $OperatingSystemVersion
[string[]] $OptionalQualifiers
}
I now want to call GetImageInfo and put the value of Owner in a variable.
I can do it like this:
$info = GetImageInfo
$owner = $imageInfo.Owner
But I was surprised that this does not work:
# Throws an error
$owner = GetImageInfo.Owner
For what I am doing now the shorter option would be nice.
Is there a way to get a field directly from a method call in PowerShell?
You need to wrap function call in the parenthesis. This allows you to let output from a command participate in an expression:
$owner = (GetImageInfo).Owner

How to run script and catch its return value

I have this simple function that return some value based on the passed argument:
function GetParam($fileName)
{
if($fileName.ToLower().Contains("yes"))
{
return 1
}
elseif($fileName.ToLower().Contains("no"))
{
return 2
}
else
{
return -1
}
}
I want to call this script from another script and get its return value, in order to decide what to do next.
How can I do that ?
You have to dot source the script where the GetParam function is defined to expose it to the other script:
getparam.ps1
function GetParam($fileName)
{
if($fileName.ToLower().Contains("yes"))
{
return 1
}
elseif($fileName.ToLower().Contains("no"))
{
return 2
}
else
{
return -1
}
}
other.ps1
. .\getparam.ps1 # load the function into the current scope.
$returnValue = GetParam -fileName "yourFilename"
Note: Consider using approved Verbs and change your function name to Get-Param. Also you can omit the return keyword.

Get all parameters passed to a function in PowerShell

I have a function as following. It generates a string as per the parameters passed.
function createSentenceAccordingly {
Param([Parameter(mandatory = $false)] [String] $name,
[Parameter(mandatory = $false)] [String] $address,
[Parameter(mandatory = $false)] [String] $zipcode,
[Parameter(mandatory = $false)] [String] $city,
[Parameter(mandatory = $false)] [String] $state)
$stringRequired = "Hi,"
if($name){
$stringRequired += "$name, "
}
if($address){
$stringRequired += "You live at $address, "
}
if($zipcode){
$stringRequired += "in the zipcode:$zipcode, "
}
if($name){
$stringRequired += "in the city:$city, "
}
if($name){
$stringRequired += "in the state: $state."
}
return $stringRequired
}
So, basically the function returns something depending upon the parameters passed. I wanted to avoid the if loops as much as possible and access all the parameters at once.
Can I access all the parameters in an array or a hashmap ? As I should be using named parameters, $args cannot be used here. If I could access all the parameters at once (may be in an array like $args or a hashamp), my plan is to use that to create the returnstring dynamically.
In the future, the parameters for the function will increase a lot and I donot want to keep on writing if loops for each additional parameter.
Thanks in advance, :)
The $PSBoundParameters variable is a hashtable that contains only the parameters explicitly passed to the function.
A better way for what you want might be to use parameter sets so that you can name specific combinations of parameters (don't forget to make the appropriate parameters mandatory within those sets).
Then you can do something like:
switch ($PsCmdlet.ParameterSetName) {
'NameOnly' {
# Do Stuff
}
'NameAndZip' {
# Do Stuff
}
# etc.
}

How do I exit from a try-catch block in PowerShell?

I want to exit from inside a try block:
function myfunc
{
try {
# Some things
if(condition) { 'I want to go to the end of the function' }
# Some other things
}
catch {
'Whoop!'
}
# Other statements here
return $whatever
}
I tested with a break, but this doesn't work. It breaks the upper loop if any calling code is inside a loop.
An extra scriptblock around try/catch and the return in it may do this:
function myfunc($condition)
{
# Extra script block, use `return` to exit from it
.{
try {
'some things'
if($condition) { return }
'some other things'
}
catch {
'Whoop!'
}
}
'End of try/catch'
}
# It gets 'some other things' done
myfunc
# It skips 'some other things'
myfunc $true
The canonical way to do what you want is to negate the condition and put the "other things" into the "then" block.
function myfunc {
try {
# some things
if (-not condition) {
# some other things
}
} catch {
'Whoop!'
}
# other statements here
return $whatever
}
You can do like this:
function myfunc
{
try {
# Some things
if(condition)
{
goto(catch)
}
# Some other things
}
catch {
'Whoop!'
}
# Other statements here
return $whatever
}