在switch语句中分配变量

大家早上好!

自从我在我发表的另一篇文章中发现它以来,我一直在搞乱 switch 语句。

我在下面的代码中有这个问题,它用相同的信息打印多行,我明白为什么这样做,但是,我不知道如何解决它。我相信它在我分配变量时搞砸了,但我不太确定。有人可以为我指出可能导致问题的正确方向吗?任何帮助表示赞赏。

$gc = Get-ChildItem -Path 'C:usersabrahOneDriveDesktop'  
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-statement-based 方法:

  • 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:usersabrahOneDriveDesktop).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用作有效可扩展的集合类型是一个好习惯。

  • 也就是说,考虑到诸如switchforeach循环之类的语句在赋值给变量时可以充当表达式,如果所有输出都将在单个集合中捕获,则您甚至不需要显式集合类型,既简洁又高效;例如:
    $collection = foreach ($i in 0..2) { $i + 1 }将数组存储1, 2, 3$collection;注意,如果只有一个对象是输出,$collection不会是一个数组,所以为了保证您可以使用[array] $collection = ...


或者,一个更简单的解决方案是利用通过-Filter参数进行基于通配符的过滤速度很快的事实,这样即使调用两次也可能不会成为问题:Get-ChildItem

$dir = 'C:usersabrahOneDriveDesktop' 
[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
}


以上是在switch语句中分配变量的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>