【问题标题】:Power shell foreach errorPowershell foreach 错误
【发布时间】:2015-01-04 10:00:34
【问题描述】:

我在 Powershell 上制作了一个程序来列出所有大于 1MB、介于 0.5MB 和 1Mb 之间以及小于 0.25MB 的文件。 这是我的代码:

$files = Get-ChildItem "C:\Temp" |`
Where {!$_.PsIsContainer}`
foreach ($file in $files){`
switch ($file.Length){`
{$_ -gt 1MB}{Write-Host $file.Name, $file.Length`
-ForegroundColor Red; break}`
{$_ -gt 0.5MB}{Write-Host $file.Name, $file.Length`
-ForegroundColor Magenta; break}`
{$_ -ge 0.25MB}{Write-Host $file.Name, $file.Length`
-ForegroundColor Cyan; break}`
default {Write-Host $file.Name, $file.Length}`
}`
}`

我从第三行 (foreach ($file in $files)) 收到错误消息。错误说:

表达式或语句中出现意外标记“in”。在行:3 字符:18 + foreach ($file in

我现在是 Powershell 的初学者。任何帮助将不胜感激

【问题讨论】:

  • 请正确缩进您的代码,并将其格式化为代码。
  • @Matt OP 可以用我建议的清理方法覆盖待处理的编辑。
  • Liam,在您粘贴的代码中,每行末尾的反引号 (`) 是因为它在您的代码中,还是因为您试图格式化此站点的代码而存在?如果是前者,那是你的问题。反引号不是行尾字符。这是一个此行继续字符。
  • 我批准了这个待修改的编辑,因为那是用户实际写的。
  • 一开始我以为反引号是在编辑中添加的。我正在查看使我感到困惑的渲染输出。编辑是正确的。我也批准了。 @BaconBits

标签: powershell foreach


【解决方案1】:

ForEach(... in ...) 并不意味着是管道或任何东西的一部分。它是独立存在的,应该这样编码。你的代码的方式是反引号组合了不应该的行。

$files = Get-ChildItem "C:\Temp" |`
Where {!$_.PsIsContainer}`
foreach ($file in $files){`

也可以读作如下。请注意,Where 子句和 ForEach 定义之间没有分隔符/运算符,这在语法上是错误的,也是错误的根源。

$files = Get-ChildItem "C:\Temp" | Where {!$_.PsIsContainer} foreach ($file in $files){

这是您遇到问题的地方。相反,以下内容看起来更简洁,功能也更符合您的预期。

$files = Get-ChildItem "C:\Temp" | Where {!$_.PsIsContainer} 

foreach ($file in $files){
    switch ($file.Length){ 
        {$_ -gt 1MB}{Write-Host $file.Name, $file.Length -ForegroundColor Red; break} 
        {$_ -gt 0.5MB}{Write-Host $file.Name, $file.Length -ForegroundColor Magenta; break} 
        {$_ -ge 0.25MB}{Write-Host $file.Name, $file.Length -ForegroundColor Cyan; break} 
        default {Write-Host $file.Name, $file.Length}
    } 
}

缩进代码以提高可读性也是一种很好的做法。您在-ForegroundColor 处也有换行符,这是不正确的。 powershell 中的反引号用作转义字符。它们可用于将一段代码继续到新行以提高可读性,并且并非每行都需要。以您的方式使用它们可以连接不应该的代码。这没有错,你只需要小心。你有比你提到的更多的错误,但我用一些正确的格式解决了其他错误。

【讨论】:

    【解决方案2】:

    foreach 既是 cmdlet (ForEach-Object) 的别名,也是关键字 (foreach)。在管道中使用时,PowerShell 假定别名,不使用 in

    如果您想在管道中将其用作ForEach-Object,则需要使用以下语法:

    $test_array = @("this","that")
    
    $test_array | foreach{Write-Output $_}
    
    > this
    > that
    

    否则,您需要像这样使用foreach

    foreach($thing in $test_array)
    {
        Write-Output $thing
    }
    
    > this
    > that
    

    这不会在管道上产生或产生输出。

    请注意,这是两个不同的命令,使用foreach 作为ForEach-Object 的别名可能会造成混淆。在管道中,我建议使用完整的 cmdlet 名称。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多