Powershell Functions do not return single element arrays

Written by Tao Yang

I came across an interesting problem today that a function I wrote to return all SCCM primary sites worked at work but did not work at home. the difference between 2 SCCM environments is that I only have 1 single SCCM site in my home environment comparing to large multi-tier SCCM infrastructure at work. after some investigation I found out this common issue with Powershell when comes to returning arrays from a function.

For example:

image

The first function foo should returns a single element arraylist, and the variable it returned has the same type as the type of the only element in the arraylist.

The second function boo should returns a two-element arraylist but the type of returned variable has changed from .NET arraylist to normal powershell array.

So how should I get Powershell to return the same variable type in a function when it’s some sort of array?

In the return statement inside of the function, add a comma (“,”) in front of variable:

.NET ArrayList:

image

 

Normal Powershell arrays:

image

More readings about this here and here

6 comments on “Powershell Functions do not return single element arrays

  1. Pingback: Powershell Functions do not return single element arrays « MS Tech BLOG

  2. Super Post… I was going mad over this until i stumbled upon your blog.
    Thanks a ton.

  3. What is really missing in this port is what everyone is looking for. How to get more than one thing out of a function. Well I am going to share what everyone wants to know who has searched and found this hoping it will answer the question.

    function My-Function([string]$IfYouWant)
    {
    [hashtable]$Return = @{}

    $Return.Success = $False
    $Return.date = get-date
    $Return.Computer = Get-Host

    Return $Return
    }
    #End Function

    $GetItOut = My-Function
    Write-host “The Process was $($GetItOut.Success) on the date $($GetItOut.date) on the host $($GetItOut.Computer)”

    #You could then do
    $var1 = $GetItOut.Success
    $Var2 =$GetItOut.date
    $Var3 = $GetItOut.Computer

    If ($var1 –like “True”){write-host “Its True, Its True”}

    Enjoy
    Peter S
    Australia

    • This may be a touch simpler:

      function xxx {
      return $false, (get-date), (get-host)
      }

      $flg, $dt, $h = xxx

      $flg
      $dt
      $h

  4. Pingback: SharePoint 2013 – Перенос элементов списка с SharePoint 2010 на примере записей Блога « ИТ Блог Алексея Максимова

  5. Pingback: Label Printing

Leave a Reply