xlogI125’s blog

パソコン作業を効率化したい

PowerShell練習 PSObject.Properties

メモ

ConvertFrom-Csv で取得した配列を Add-Type で定義してあるC#に渡して PSObject.Properties の様子を見る。

使い捨てスクリプト

# PowerShell 5.1, Windows 11

Set-StrictMode -Version Latest

$row0 = [PSCustomObject]@{colA = "1行A列"; colB = "1行B列"}
$row1 = [PSCustomObject]@{colA = "2行A列"; colB = "2行B列"}
$row2 = [PSCustomObject]@{colA = "3行A列"; colB = "3行B列"}
$a = @($row0, $row1, $row2)
$b = $a | ConvertTo-Csv -NoTypeInformation
$c = $b | ConvertFrom-Csv

Get-Member -Force -InputObject $c[1]

Add-Type -Language CSharp -TypeDefinition @'
using System.Management.Automation;

namespace MyNamespace {
  public class MyClass {
    public static void MyTest(PSObject[] psObjs) {
      
      System.Console.WriteLine(
        "PSMemberInfoCollection<PSPropertyInfo>で" + 
        "Item[name]のnameが事前に分かっている場合"
      );
      
      System.Console.WriteLine(
        "{0}, {1}, {2}, {3}", 
        psObjs[1].Properties["colA"].Name, 
        psObjs[1].Properties["colA"].Value.ToString(), 
        psObjs[1].Properties["colB"].Name, 
        psObjs[1].Properties["colB"].Value.ToString()
      );
      
      System.Console.WriteLine(
        "PSMemberInfoCollection<PSPropertyInfo>で" + 
        "Match(name)のnameにワイルドカード文字を指定する場合"
      );
      
      ReadOnlyPSMemberInfoCollection<PSPropertyInfo> matches;
      matches = psObjs[1].Properties.Match("*");
      
      System.Console.WriteLine(
        "Count {0}, {1}, {2}, {3}, {4}", 
        matches.Count, 
        matches[0].Name, matches[0].Value.ToString(), 
        matches[1].Name, matches[1].Value.ToString()
      );
      
      System.Console.WriteLine(
        "PSMemberInfoCollection<PSPropertyInfo>で" + 
        "GetEnumeratorを使用する場合"
      );
      
      System.Collections.Generic.IEnumerator<PSPropertyInfo> enumerator;
      PSPropertyInfo psPropInfo;
      
      for (int i = 0; i < psObjs.Length; i++) {
        enumerator = psObjs[i].Properties.GetEnumerator();
        enumerator.Reset();
        
        while (enumerator.MoveNext() != false) {
          psPropInfo = enumerator.Current;
          System.Console.WriteLine(
            "i={0}, {1}, {2}", 
            i, psPropInfo.Name, psPropInfo.Value.ToString()
          );
        }
        
      }
      
    }
  }
}
'@

[MyNamespace.MyClass]::MyTest($c)