tech.guitarrapc.cóm

Technical updates

PowerShellで動的にPropertyにアクセスする

前回の補足というか、PowerShell 3.0での動的なPropertyアクセスの方法例を紹介します。

今回紹介するのは、変数に含まれるプロパティへ順にアクセスして結果を表示/操作する例です。 運用でも利用しているコードですので参考になればです。

※ 本コードはPowerShell 3.0以降で動作します。

プロパティを取得する

要は、プロパティの一覧を取得して順にアクセスすればいいわけです。 Get-Memberで一発です。

$path = Get-ChildItem -Path c:\
$propaties = $path | Get-Member -MemberType Properties | select -ExpandProperty Name

これで、$properties変数には、$パスのptopertyやNotePropertyが入りました。

プロパティにアクセスする

では順にプロパティにアクセスしてみましょう。

foreach ($p in $propaies)
{
  Write-Host $p -ForegroundColor Cyan
  $path.$p | Format-Table -AutoSize
  ""
}

結果、各プロパティの内容を表示できます。

Mode
d----
d----
d----
d-r--
d-r--
d----
d-r--
d----
-a---
-a---

PSChildName
downloads
inetpub
PerfLogs
Program Files
Program Files (x86)
sources
Users
Windows
RAMDisk.img
RAMDisk.img.bak

PSDrive

Name Used (GB) Free (GB) Provider   Root  CurrentLocation
---- --------- --------- --------   ----  ---------------
C        73.29     38.49 FileSystem C:\  Windows\system32
C        73.29     38.49 FileSystem C:\  Windows\system32
C        73.29     38.49 FileSystem C:\  Windows\system32
C        73.29     38.49 FileSystem C:\  Windows\system32
C        73.29     38.49 FileSystem C:\  Windows\system32
C        73.29     38.49 FileSystem C:\  Windows\system32
C        73.29     38.49 FileSystem C:\  Windows\system32
C        73.29     38.49 FileSystem C:\  Windows\system32
C        73.29     38.49 FileSystem C:\  Windows\system32
C        73.29     38.49 FileSystem C:\  Windows\system32



PSIsContainer
True
True
True
True
True
True
True
True
False
False

PSParentPath
Microsoft.PowerShell.Core\FileSystem::C:\
Microsoft.PowerShell.Core\FileSystem::C:\
Microsoft.PowerShell.Core\FileSystem::C:\
Microsoft.PowerShell.Core\FileSystem::C:\
Microsoft.PowerShell.Core\FileSystem::C:\
Microsoft.PowerShell.Core\FileSystem::C:\
Microsoft.PowerShell.Core\FileSystem::C:\
Microsoft.PowerShell.Core\FileSystem::C:\
Microsoft.PowerShell.Core\FileSystem::C:\
Microsoft.PowerShell.Core\FileSystem::C:\

プロパティ毎に操作してみる

このやり方なら、予め作っておいたオブジェクトの名称毎にModule Direcotryを作ったりも簡単ですね。

$Users = [PSCustomObject]@{
  hoge="hoge"
  fuga="fuga"
  foo="foo"
}

$prop = $Users | Get-Member -MemberType Properties

foreach ($p in $prop)
{
  $PSModulePath = "C:\Users\$($Users.$p)\Documents\WindowsPowerShell\Modules"
  if (-not(Test-Path $PSModulePath))
  {
    Write-Verbose "Create Module path"
    New-Item -Path $PSModulePath -ItemType Directory -Force
  }
  else
  {
    Write-Verbose " $PSModulePath already exist. Nothing had changed. `n"
  }
}

もちろんUserはCIMから取得してもいいでしょう。この辺はお好きにさじ加減を。 楽にかけて調整できる、PowerShellっていいですよね!