MattV
MattV

Reputation: 1383

Call Powershell Function with Parameter Object

Is is possible to create an object like so

    $Data = new-object PSObject
    $Data | Add-member NoteProperty -Name "SiteName" -Value "Web Title"
    $Data | Add-member NoteProperty -Name "SiteURL" -Value "https://www.test.url"

And then somehow call a function like

Do-CustomFunction $Data

Which would unpack the object and use its attributes as named parameters, to emulate the behavior of:

Do-CustomFunction -SiteName "Web Title" -SiteURL "https://www.test.url"

Upvotes: 3

Views: 8450

Answers (3)

Theo
Theo

Reputation: 61028

As commented, you could use ParameterSets to combine the option of either sending separate strings or an object containing the values:

function Do-CustomFunction {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'ByParams')]
        [string]$SiteName, 
        [Parameter(Mandatory = $true, Position = 1, ParameterSetName = 'ByParams')]
        [string]$SiteUrl,

        [Parameter(Mandatory = $true, Position = 0, ParameterSetName = 'ByObject')]
        [object]$SiteObject
    )
    if ($PSCmdlet.ParameterSetName -eq 'ByObject') {
        $SiteName = $SiteObject.siteName
        $SiteUrl  = $SiteObject.siteUrl
    }

    Write-Host "SiteName: $SiteName  SiteUrl: $SiteUrl"
}

Using

Do-CustomFunction -SiteName 'SiteName' -SiteUrl 'SiteURL'

or

$Data = new-object PSObject
$Data | Add-member NoteProperty -Name "SiteName" -Value "Web Title"
$Data | Add-member NoteProperty -Name "SiteURL" -Value "https://www.test.url"

Do-CustomFunction -SiteObject $Data

will both do nicely.

Upvotes: 2

hcm
hcm

Reputation: 1010

You are looking for about_splatting: link

Example:

function mytest{
    param($path1,$path2)
    write-host $path1 $path2
}

$commands = @{
    path1 = "C:\temp\test.txt"
    path2 = "C:\temp\test2.txt"
}

mytest @commands

Notice referencing the hashtable with an @ when calling the function.

Upvotes: 10

JimShapedCoding
JimShapedCoding

Reputation: 917

If you want to use SiteName as $SiteName , you can do this with Set-Variable.

However, if you put this in function block, it does not set the variable properly for future use in the script execution. After a lot of attempts, this is the best result i've reached, hope this is what you looking for.


$Data = new-object PSObject
$Data | Add-member NoteProperty -Name "SiteName" -Value "Web Title"
$Data | Add-member NoteProperty -Name "SiteURL" -Value "httpss://www.test.url"


foreach ($att in $Data.psobject.Properties)
{
    Set-Variable -Name $att.Name -Value $att.Value
}

#CONSOLE:
$SiteName
#OUTPUT: Web Title
$SiteURL
#OUTPUT: https://www.test.url

Upvotes: 1

Related Questions