0

我正在尝试将一组自定义对象传递给函数以进一步处理这些对象。

这是我创建自定义对象数组的函数:

Function GetNetworkAdapterList
{
    # Get a list of available Adapters
    $hnet = New-Object -ComObject HNetCfg.HNetShare
    $netAdapters = @()
    foreach ($i in $hnet.EnumEveryConnection)
    {   
        $netconprop = $hnet.NetConnectionProps($i)
        $inetconf = $hnet.INetSharingConfigurationForINetConnection($i)

        $netAdapters += New-Object PsObject -Property @{
                Index = $index
                Guid = $netconprop.Guid
                Name = $netconprop.Name
                DeviceName = $netconprop.DeviceName
                Status = $netconprop.Status
                MediaType = $netconprop.MediaType
                Characteristics = $netconprop.Characteristics
                SharingEnabled = $inetconf.SharingEnabled
                SharingConnectionType = $inetconf.SharingConnectionType
                InternetFirewallEnabled = $inetconf.InternetFirewallEnabled
                SharingConfigurationObject = $inetconf
                }
        $index++
    }   
    return $netAdapters
}

然后在我的主代码中,我像这样调用上面的函数:

$netAdapterList = GetNetworkAdapterList

$netAdapterList 返回预期的数据,我可以执行以下操作:

$netAdapterList | fl Name, DeviceName, Guid, SharingEnabled

到现在为止还挺好。

现在我想调用一个传入 $netAdapterList 的函数

我创建了一个像这样的虚拟函数:

Function ShowAdapters($netAdapterListParam)
{
   $netAdapterListParam | fl Name, DeviceName, Guid, SharingEnabled
}

当我这样调用它时:

ShowAdapters $netAdapterList

什么都没有打印出来。

我尝试更改函数的签名,但仍然没有运气:

Function ShowAdapters([Object[]]$netAdapterListParam)

Function ShowAdapters([Object]$netAdapterListParam)

Function ShowAdapters([PSObject[]]$netAdapterListParam)    

Function ShowAdapters([array]$netAdapterListParam)

有人知道我在做什么错吗?如何访问函数内的自定义对象?

4

1 回答 1

0

感谢您的回复@Christian。尝试了您的步骤,将点点滴滴的内容复制到外壳中,它确实有效。但是,如果我运行完整的 .ps1 脚本,则不会打印出任何内容。

我已经在 Powershell IDE 中运行脚本,在 ShowAdapters 函数内设置断点,并且$netAdapterListParam确实具有我要传入的预期自定义对象数组,因此我已将问题缩小到 FL 命令行开关中。

由于某种原因$netAdapterList | fl Name, DeviceName, Guid, SharingEnabled对我不起作用,所以我最终改用以下内容:

$formatted = $netAdapterListParam | fl Name, DeviceName, Guid, SharingEnabled | Out-String
Write-Host $formatted

这样就成功了,4 个属性被打印在屏幕上。

得到教训:

1) Win7 内置的 Powershell IDE 可以成为调试脚本的非常有用的工具 2) 格式化自定义对象时,Format-List 可能很古怪,因此需要 Out-String。

于 2012-11-21T14:56:17.597 回答