3

I know how to return hashtables, arrays etc from Powershell to c# through PSObjects. In order to use that, I need to return an object from the Powershell script - not just list the output.

But how can I get from a list in Powershell to something structured I can return from the Powershell script?

Think about this simple scenario (for example purposes):

Get-ChildItem C:\Test

And I get something like this output:

PS C:\test> Get-ChildItem

Directory: C:\test

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
-a---        03.06.2013     14:59          6 test1.txt
-a---        03.06.2013     14:59          5 test2.txt

Now I want to take the Name and Length property of each file and return it from the powershell script as some sort of object, I can process with C#.

An example of something I could handle from C# would be this:

$a = New-Object psobject -Property @{
   Name = "test1.txt"
   Age = 6
}

$b = New-Object psobject -Property @{
    Name = "test2.txt"
    Age = 5
}

$myarray = @()

$myarray += $a
$myarray += $b

Return $myarray

How do I get from Get-ChildItem (or something similar that gives a list) to an array of objects or something similar?

Please note that this is not about Get-ChildItem specifically, it is just used as an example of something that outputs a list.

1 Answer 1

8

Something like that should do it:

$arr = Get-ChildItem | Select-Object Name,Length
return $arr

If for some reason it doesn't work, try nesting the array in a one array element (using the comma operator)

return ,$arr
Sign up to request clarification or add additional context in comments.

2 Comments

I like wheels. So...$arr = (Get-ChileItem | % {[PSCustomObject]@{Name=$_.Name;Lenght=$_.Length}})
You're taking the longer route but it is a valid route :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.