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 スクリプトを実行しても何も出力されません。

ShowAdapters 関数内でブレークポイントを設定する Powershell IDE でスクリプトを実行しましたが、$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 に答える