大家早上好!
自从我在另一篇文章中发现了这件事后,我就一直在胡乱处理开关声明。
我在下面的代码中有这个问题,它用相同的信息打印多行,我知道为什么会这样做,但是,我不知道如何修复它。我相信当我分配变量时它会搞砸,但是,我不太确定。有人能为我指出可能导致问题的正确方向吗?任何帮助都是非常感谢的。
$gc = Get-ChildItem -Path 'C:\users\abrah\OneDrive\Desktop'
Foreach ($File in $gc) {
switch -Wildcard ($file) {
"deskt*" { $Desk = "This is the location: $($File.FullName)" }
"*v*" { $VA = "This is the location: $($File.FullName)" }
}
$VCount = $va | Measure-Object | Select-Object -ExpandProperty Count
$Dcount = $Desk | Measure-Object | Select-Object -ExpandProperty Count
$PS = [pscustomobject]@{
DesktopLocation = $Desk
DCount = $Dcount
VLocation = $VA
VCount = $VCount
}
$PS
}关于脚本:我只是想在我的桌面上找到以deskt开头的任何文件,以及其中包含字母V的任何文件。然后im将其扔到自定义对象中,同时试图计算包含这些键字母的文件数量。
以下是结果:

发布于 2021-01-10 16:28:21
至于基于switch语句的方法:
switch本身能够处理集合,因此不需要将其包装在foreach循环中.- initialize `$Desk` and `$VA` as a collection data type.
- _append_ to these collections in the `switch` branch handlers.# Initialize the collections.
$Desk = [System.Collections.Generic.List[string]] @()
$VA = [System.Collections.Generic.List[string]] @()
# Make `switch` loop over the .FullName values of all items in the target dir.
switch -Wildcard ((Get-ChildItem C:\users\abrah\OneDrive\Desktop).FullName) {
'*\deskt*' { $Desk.Add("This is the location: $_") } # add to collection
'*\*v*' { $VA.Add("This is the location: $_") } # add to collection
}
# Construct and output the summary object
[pscustomobject] @{
DesktopLocation = $Desk
DCount = $Desk.Count
VLocation = $VA
VCount = $VA.Count
}注意:
+=的数组中,虽然方便,但效率低下,因为每次都必须在幕后创建一个新数组,因为数组在元素计数方面是不可变的。虽然只包含几个元素的数组可能并不重要,但使用System.Collections.Generic.List`1作为一种有效的可扩展集合类型是一个好习惯。
switch和foreach循环等语句在分配给变量时可以充当表达式,如果要在单个集合中捕获所有输出,则甚至不需要显式地使用集合类型,这种类型既简洁又高效;例如:$collection = foreach ($i in 0..2) { $i + 1 }将数组1, 2, 3存储在$collection中;请注意,如果只输出一个对象,则$collection将不是数组,因此要确保可以使用$collection
或者,更简单的解决方案是利用通过-Filter参数进行基于通配符的筛选是快速的,因此即使两次调用Get-ChildItem也不会成为问题:
$dir = 'C:\users\abrah\OneDrive\Desktop'
[array] $Desk = (Get-ChildItem -LiteralPath $dir -Filter deskt*).FullName
[array] $VA = (Get-ChildItem -LiteralPath $dir -Filter *v*).FullName
[pscustomobject] @{
DesktopLocation = $Desk
DCount = $Desk.Count
VLocation = $VA
VCount = $VA.Count
}https://stackoverflow.com/questions/65655061
复制相似问题