Powershell foreach错误

时间:2014-11-07 15:08:30

标签: powershell foreach

我在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 char:18   + foreach($&file;<<<<< $ files){`       + CategoryInfo:ParserError :( in:String)[],ParentContainsErrorRecordException       + FullyQualifiedErrorId:UnexpectedToken

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

2 个答案:

答案 0 :(得分:3)

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名称。

答案 1 :(得分:2)

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中的反引号用作转义字符。它们可用于将一段代码继续到新行上以便于阅读,并且不需要在每一行上。以你的方式使用它们可以连接不应该的代码。你只需要小心就没有错。你提到了更多的错误,但我用其他正确的格式解决了其他问题。