.count 在多个 powershell 版本中
.count in multiple powershell versions
我有一部分 powershell 脚本可以检查位置并验证文件数量,然后根据数量运行检查。 powershell脚本在多台机器上是运行,其中一台是运行 powershell 2.0。
我正在使用类似的东西:
$folder = Get-Item "Parent Folder"
$files = (Get-ChildItem $folder.Fullname)
当我检查 $files.Count
时,它在大于 2.0 的 powershell 版本中是准确的。
在 Powershell 2.0 中,如果 $files
仅包含 1 个文件,files.Count
将不会 return 任何内容。如果有超过 1 个文件,那么它 return 是正确的计数(非空)。
如果 Get-ChildItem 只有 return 一个值,我假设这与 $files
不是数组有关。
我知道检查 powershell 版本并修改每个版本的脚本可以解决这个问题,但我宁愿避免它。
是否有其他方法可以跨多个 powershell 版本统一检查计数?
这是一个已知问题,您必须将 return 值转换为 PS 2.0 的数组。它已在 PS 3.0:
中修复
You can now use Count or Length on any object, even if it didn’t have
the property. If the object didn’t have a Count or Length property,
it will will return 1 (or 0 for $null). Objects that have Count or
Length properties will continue to work as they always have.
示例:
$files = @(Get-ChildItem $folder.Fullname)
或
[array]$files = Get-ChildItem $folder.Fullname
参考文献:
- New V3 Language Features
- How does the Count property work in Powershell?
我有一部分 powershell 脚本可以检查位置并验证文件数量,然后根据数量运行检查。 powershell脚本在多台机器上是运行,其中一台是运行 powershell 2.0。
我正在使用类似的东西:
$folder = Get-Item "Parent Folder"
$files = (Get-ChildItem $folder.Fullname)
当我检查 $files.Count
时,它在大于 2.0 的 powershell 版本中是准确的。
在 Powershell 2.0 中,如果 $files
仅包含 1 个文件,files.Count
将不会 return 任何内容。如果有超过 1 个文件,那么它 return 是正确的计数(非空)。
如果 Get-ChildItem 只有 return 一个值,我假设这与 $files
不是数组有关。
我知道检查 powershell 版本并修改每个版本的脚本可以解决这个问题,但我宁愿避免它。
是否有其他方法可以跨多个 powershell 版本统一检查计数?
这是一个已知问题,您必须将 return 值转换为 PS 2.0 的数组。它已在 PS 3.0:
中修复You can now use Count or Length on any object, even if it didn’t have the property. If the object didn’t have a Count or Length property, it will will return 1 (or 0 for $null). Objects that have Count or Length properties will continue to work as they always have.
示例:
$files = @(Get-ChildItem $folder.Fullname)
或
[array]$files = Get-ChildItem $folder.Fullname
参考文献:
- New V3 Language Features
- How does the Count property work in Powershell?