以前、PowerShell3.0のユーザー変数のみを取得する記事を書きました。
PowerShell 3.0のBuild-In Variableを取得する
が、PowerShell 2.0では、そもそもこの部分が動かせないので使えません。
$builtinVariable = [psobject].Assembly.GetType('System.Management.Automation.SpecialVariables').GetFields('NonPublic,Static') ` | Where-Object FieldType -eq ([string]) ` | ForEach-Object GetValue $null
そこで今回は、PowerShell 2.0で取得する方法です。
変数の取得
簡単です。新規Runspaceを作ってしまうのです。 新規Runspace = ユーザー変数の入る余地はありませんね! よって、PowerShell 3.0でしか動かなかった部分をいかに差し替えます。
[powershell]::create().addcommand('Get-Variable').invoke() | Select-Object -ExpandProperty Name
残りは同じ要領でできちゃいます。
ユーザー定義変数取得Function
はい簡単。 3.0からの変更点1. 追加するハードコード部分が増えています。 3.0からの変更点2. -notinが使えないので、-notcontainsに変更しています。
function Get-UserVariables{ param( ) $builtinVariable = [powershell]::create().addcommand('Get-Variable').invoke() | Select-Object -ExpandProperty Name $other = , @( "FormatEnumerationLimit", "MaximumAliasCount", "MaximumDriveCount", "MaximumErrorCount", "MaximumFunctionCount", "MaximumVariableCount", "PGHome", "PGSE", "PGUICulture", "PGVersionTable", "PROFILE", "PSSessionOption", "MyInvocation", "other", "PSBoundParameters", "this", "_", "args", "input" ) $other ` | ForEach-Object {$builtinVariable += $_} Get-Variable ` | Where {$builtinVariable -notcontains $_.Name} ` | select Name, Value, Description }
実行は、一文だけです。
Get-UserVariables | Format-List
Functionで利用した変数だけですね!
Name : builtinVariable
Value : {$, ?, ^, ConfirmPreference...}
Description :
まとめ
PowerShell3.0を使いつつー、PowerGUI使いましょう。