Newb Alert: Passing array as function param

This topic contains 5 replies, has 2 voices, and was last updated by  Toby Williams 4 years, 10 months ago.

  • Author
  • #8350

    Toby Williams


    I am trying to build a list of computer names and OS architecture and am super stuck.

    For far I have;

    function get-architecture {
    param ($Computername)

    Get-WmiObject -ComputerName $computername -Class Win32_Processor -erroraction stop  |
    select @{Name='ComputerName';Expression={$computername}},@{Name='Architecture';Expression={$_.AddressWidth}} | ft -AutoSize


    $Computers = @("Desktop175", "Slowvostro", "Desktop190")

    get-architecture -computername $Computers

    This gives me;

    ComputerName                         Architecture
    ------------                         ------------
    {Desktop175, Slowvostro, Desktop190}           64
    {Desktop175, Slowvostro, Desktop190}           32
    {Desktop175, Slowvostro, Desktop190}           64

    This is almost right but I want it to display 1 computer name on each line.

    Where am I going wrong?




  • #8354

    Toby Williams

    I forgot to mention (but you can most likely tell), I am just starting to learn about functions and creating custom objects. =D

  • #8360


    Your issue is with the assignment of your Expression in select object to the $computerName parameter (which contains all 3 computer names).

    The easiest solution is to replace your Expression={$computerName} assignment with Expression={$_.__SERVER}. That will set the computer name to the __SERVER property of the WMI objects that are passed in from the previous stage in the pipeline.

  • #8365

    Toby Williams

    Many thanks. I should know better to check all the properties first before asking for help!

    May I ask how you would achieve the same results if there were no property which specified the machine name?

  • #8366


    Sure. I would do it like this:

    $(foreach ($item in $ComputerName) {
        Get-WmiObject -ComputerName $item -Class Win32_Processor -erroraction stop  |
        select @{Name='ComputerName';Expression={$item}},@{Name='Architecture';Expression={$_.AddressWidth}}
    }) | ft -AutoSize

    Actually, that's not entirely true. I wouldn't use format-table in the output. That's actually an anti-pattern in PowerShell. You should return the objects, and let the caller do the formatting. If you want to specify a default format, even for custom objects, there are ways to do that (See the *-FormatData and *-TypeData cmdlets and the cooresponding *.ps1xml files in $PSHome as examples). Make sure you give your custom object a custom type name though because formatting and type extensions are keyed off of the type name.

  • #8367

    Toby Williams

    OK, thanks again for the help.

You must be logged in to reply to this topic.