Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I would think you can pipe the variable to the function

Tags:

powershell

PowerShell 5.1

The following works fine, however, would it work piping it to the method instead of using semicolons?

function Main {
    
    $dev=@{Name='DEV'; DbServer='DEV'}; UpdateSspAppUserPassword @dev
    $uat=@{Name='UAT'; DbServer='UAT'}; UpdateSspAppUserPassword @uat
}

function UpdateSspAppUserPassword ($DbServer) {
    "hello world: $($DbServer)"
}
Clear-Host
Main

Output

hello world: DEV
hello world: UAT
PS C:\WINDOWS\system32> 
like image 285
Rod Avatar asked Oct 20 '25 12:10

Rod


1 Answers

If you're ok using [pscustomobject] instead of hash tables then you can have your parameter take ValueFromPipelineByPropertyName and have your function leverage pipeline processing:

function Main {
    [pscustomobject]@{ Name='DEV'; DbServer='DEV' },
    [pscustomobject]@{ Name='UAT'; DbServer='UAT' } |
        UpdateSspAppUserPassword
}

function UpdateSspAppUserPassword {
    param(
        [Parameter(ValueFromPipelineByPropertyName)]
        [string] $DbServer
    )

    process {
        "hello world: $($DbServer)"
    }
}

Main

Otherwise, using your current implementation, will require assistance from a loop making it less efficient since the function needs to be invoked as many elements are coming from pipeline:

function Main {
    @{ Name='DEV'; DbServer='DEV' }, @{ Name='UAT'; DbServer='UAT' } |
        ForEach-Object { UpdateSspAppUserPassword @_ }
}

function UpdateSspAppUserPassword ($DbServer) {
    "hello world: $($DbServer)"
}

Main
like image 178
Santiago Squarzon Avatar answered Oct 23 '25 03:10

Santiago Squarzon