Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass object[] into a function in PowerShell

Tags:

powershell

Is there a resource on how to pass in a Object[] as a parameter within a PowerShell function?

Both of these functions are cmdlets and they are being exported correctly, but I cannot see the $Return object in my second function.

Is something like the following needed?

ParameterAttribute.ValueFromPipeline Property (System.Management.Automation)

# Within PowerShell code

$Return = My-Function -Param "value" # $Return is of type Object[]
$ModifiedReturn = My-SecondFunction -Input $Return

Where this is my function definition:

function My-SecondFunction
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory=$True)]
        [Object[]]$Input
    )
    begin {}
    process
    {
        Write-Host "test: $Input" # Does not return anything
    }
    end {}
}
like image 911
reZach Avatar asked Jan 27 '17 17:01

reZach


People also ask

How do you pass a variable to a function in PowerShell?

You can pass variables to functions by reference or by value. When you pass a variable by value, you are passing a copy of the data. In the following example, the function changes the value of the variable passed to it. In PowerShell, integers are value types so they are passed by value.

How do you pass multiple parameters in PowerShell?

Refer below PowerShell script for the above problem statement to pass multiple parameters to function in PowerShell. Write-Host $TempFile "file already exists!" Write-Host -f Green $TempFile "file created successfully!" Write-Host -f Green $FolderName "folder created successfully!"

What does $_ do in PowerShell?

The $_ is a variable or also referred to as an operator in PowerShell that is used to retrieve only specific values from the field. It is piped with various cmdlets and used in the “Where” , “Where-Object“, and “ForEach-Object” clauses of the PowerShell.

What is CmdletBinding in PowerShell?

The CmdletBinding attribute is an attribute of functions that makes them operate like compiled cmdlets written in C#. It provides access to the features of cmdlets. PowerShell binds the parameters of functions that have the CmdletBinding attribute in the same way that it binds the parameters of compiled cmdlets.


1 Answers

$Input is the name of an automatic variable. Use a different name.

I recommend $InputObject as that is in common usage so it has a well-understood meaning, but usually that means you are accepting pipeline input as well.

Of course if there's a name that's more descriptive for this parameter, you should use that.

I have submitted this issue on the PowerShell GitHub project suggesting that Set-StrictMode be modified to check for automatic variable assignment.

like image 105
briantist Avatar answered Oct 07 '22 03:10

briantist