4

存在しないプロパティを選択しようとすると PowerShell にエラーをスローさせたいのですが、代わりに出力として空の列を取得します。例:

$ErrorActionPreference=[System.Management.Automation.ActionPreference]::Stop;
Set-StrictMode -Version 'Latest'
Get-Process *ex* | Select-Object Id,ProcessName,xxx

   Id ProcessName   xxx
   -- -----------   ---
 9084 explorer
11404 procexp

によって複数のテキスト ファイルをインポートするスクリプトを作成しましたImport-Csvが、それらのファイルのヘッダーが変更される可能性があり、空の列がシステムに読み込まれてしまいます。

編集:これは、ヘッダーが一致するかどうかを確認する方法です:

$csv = Import-Csv -Delimiter ';' -Path $file.FullName 
$FileHeaders = @(($csv | Get-Member -MemberType NoteProperty).Name) 
if (Compare-Object $ProperHeaders $FileHeaders) {'err'} else {'ok'}

それがPowerShellの仕組みであることは知っていSet-StrictModeますが、@Mattが述べたように、ドキュメントは実際には少し誤解を招くものでした。Select-Object「-NoNewImplicitProps」または「-ReadOnlyPipeline」スイッチがあればいいのにと思います:) 。答えてくれてありがとう。

4

4 に答える 4

5

あなたは実際に、一部の人々が機能と呼ぶものを使用しています。Add-Memberこれは、すべての配列メンバーで使用して空の列を追加する簡単な表現です。

その場合に行うことは、呼び出す場所のImport-CSVプロパティ名を確認することです。Select

$data = Import-csv C:\Temp\file.csv 
$props = $data | Get-member -MemberType 'NoteProperty'  | Select-Object -ExpandProperty Name

次のように書かれていると、ドキュメントが少し誤解を招くSet-StrictModeことがわかります。

オブジェクトの存在しないプロパティへの参照を禁止します。

ただし、この場合、プロパティ参照を取得しようとしているのではなく、Select-Objectコマンドレットの関数を使用しています。ただし、次の場合はエラーが発生します

PS C:\Users\mcameron> Set-StrictMode -Version 'Latest'
(Get-Process *ex*).Bagels
The property 'Bagels' cannot be found on this object. Verify that the property exists.
At line:2 char:1
+ (Get-Process *ex*).Bagels
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], PropertyNotFoundException
    + FullyQualifiedErrorId : PropertyNotFoundStrict
于 2015-10-02T11:40:54.927 に答える
1

このようなもの...?

$props = 'Id','ProcessName','xxx'
$availableProps = Get-Process *ex*|Get-Member -MemberType Properties | Select -ExpandProperty Name
$missingProps = $props | Where-Object {-not ($availableProps -contains $_)}
if ($missingProps) {
  Write-Error "invalid property(s) $missingProps"
  throw { [System.Management.Automation.PropertyNotFoundException] }
}

Get-Process *ex* | Select-Object $props
于 2015-10-02T12:08:31.327 に答える