选择不存在的属性时没有错误 [英] No error when selecting non-existing property
问题描述
我希望 PowerShell 在尝试选择不存在的属性时抛出错误,但我得到的是空列作为输出.示例:
I want PowerShell to throw an error when trying to select non-existing properties, but instead I get empty column as output. Example:
$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
导入多个文本文件,但这些文件中的标题可能会发生变化,最终我会将空列加载到系统中.
I wrote a script that is importing multiple text files by Import-Csv
, but headers in those file may change, and I'll end up with empty columns being loaded to the system.
这是我检查标题是否匹配的方式:
This is how I'm checking if the headers match:
$csv = Import-Csv -Delimiter ';' -Path $file.FullName
$FileHeaders = @(($csv | Get-Member -MemberType NoteProperty).Name)
if (Compare-Object $ProperHeaders $FileHeaders) {'err'} else {'ok'}
我知道这就是 PowerShell 的工作方式,但正如@Matt 提到的那样,Set-StrictMode
文档确实对我有点误导.我只是希望 Select-Object
有某种-NoNewImplicitProps"或-ReadOnlyPipeline"开关可以为我完成这项工作:).感谢您的回答.
I know that's the way PowerShell works, but Set-StrictMode
documentation was indeed a little misleading for me, as @Matt mentioned. I just wish Select-Object
had some kind of "-NoNewImplicitProps" or "-ReadOnlyPipeline" switch that would do the job for me :). Thanks for the answers.
推荐答案
您实际上使用的是什么 有些人会称之为功能.这是使用 Add-Member
对所有数组成员添加一个空列.
You are actually using what some people would call a feature. That is a simpler rendition of using Add-Member
on all the array members to add an empty column.
在 Import-CSV
的情况下,您在这种情况下所做的是检查 之前的属性名称选择
你在哪里打电话.
In the case of Import-CSV
what you do in that case is check the property names before the Select
where you call them.
$data = Import-csv C:\Temp\file.csv
$props = $data | Get-member -MemberType 'NoteProperty' | Select-Object -ExpandProperty Name
我可以看到文档在说 时有点误导Set-StrictMode
:
I can see the documentation be a little misleading when it says for Set-StrictMode
:
禁止引用对象不存在的属性.
Prohibits references to non-existent properties of an object.
但在这种情况下,您不是尝试获取属性引用,而是使用 Select-Object
cmdlet 的函数.尽管以下内容会产生错误
But in this case you are not trying to get the property reference but using a function of the Select-Object
cmdlet. The following would have generated an error though
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
这篇关于选择不存在的属性时没有错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!