【发布时间】:2026-01-13 16:25:02
【问题描述】:
我犯了一个非常不幸的错字,浪费了我不少宝贵的时间:
$errors.Count
这会返回“0”,即使有错误,因为变量名应该是单数。这确实工作:
$error.clear() # To ensure a correct repro
Copy-Item asdf fdsa # Will show an error
$error.Count # Will output "1"
但是,我现在想知道为什么$errors.Count 给了我任何东西,以及为什么它给了我“0”。于是我继续做了一些测试,得到了如下结果:
$asdf.Count # Will output "0"
$nrOfEinsteinsInSpace.Count # Will output "0"
$a = 0; $a.Count; # Will output "1"
$b = 2; $a.Count; # Will output "1"
$x = 1,2,3; $x.Count; # Will output "3"
并收集更多数据以便能够在这里提出一个明智的问题:
$true.Count # Will output "1"
$false.Count # Will output "1"
所以我们有以下不同的情况:
- Array(like) 变量,其中
.Count将输出项目数。 - 不存在的变量,
.Count将输出“0”。 - 声明的变量,其中
.Count将输出“1”。 - 内置变量,其中
.Count将输出“1”。
案例 2、3 和 4 对我来说没有任何意义(目前)。这里发生了什么?这是在哪里记录的? .Count 属性是如何工作的?
【问题讨论】:
标签: powershell