大家早上好!
自从我在另一篇文章中发现它以来,我一直在搞乱switch语句。
我在下面的代码中遇到了这个问题,其中的代码以相同的信息打印多行,我知道为什么这样做,但是,我不知道如何解决。我相信我在分配变量时会搞砸,但是我不太确定。有人可以向我指出可能导致问题的原因的正确方向吗?任何帮助表示赞赏。
$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
。然后,在尝试计算包含这些关键字母的文件数量时,将其扔到自定义对象中。
这是结果,顺便说一句:
至于switch
基于陈述的方法:
switch
本身具有处理集合的能力,因此无需将其包装在foreach
循环中。
您正在寻找的是从输入中构建两个集合,这需要您:
$Desk
并$VA
作为集合数据类型。switch
分支处理程序中追加到这些集合。# 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
andforeach
循环的语句可以在分配给变量时充当表达式,如果所有输出都将被捕获在单个集合中,则您甚至不需要显式且高效的显式集合类型;例如:
$collection = foreach ($i in 0..2) { $i + 1 }
将数组存储1, 2, 3
在$collection
;中。请注意,如果仅输出一个对象,$collection
则不会是数组,因此请确保可以使用[array] $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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句