【问题标题】:Powershell: Unexpected Token in expression or statementPowershell:表达式或语句中的意外标记
【发布时间】:2020-08-20 02:24:08
【问题描述】:

很难解决这个问题

$source = $args[0]
$dest = $args[1]
$fstr = $args[2]
$rstr = $args[3]
If(!(test-path $dest))
{
New-Item -ItemType Directory -Force -Path $dest | out-null
}
If((test-path $source))
{
$files = Get-ChildItem $source *.ICMS
ForEach ($file in $files)
{
$filePath = $source + "\" + $file;
$x = Get-Content $filePath
$x[0] = $x[0].Replace($fstr,$rstr)
$outfile =  $dest + "\" + $file.Name $x2 = $x[0..($x.Length-2)]
$x = $x2.ForEach({ $_ + "`n"})
$x | Set-Content -NoNewline $outfile
}
}
Else {"Source directory doesn't exist"}  

我收到一条错误消息,提示 Unexpected token '$x2' in expression or statement

【问题讨论】:

    标签: powershell


    【解决方案1】:

    您需要将$x2 = $x[0..($x.Length-2)] 移动到下一行。

    $source = $args[0]
    $dest = $args[1]
    $fstr = $args[2]
    $rstr = $args[3]
    If(!(test-path $dest))
    {
    New-Item -ItemType Directory -Force -Path $dest | out-null
    }
    If((test-path $source))
    {
    $files = Get-ChildItem $source *.ICMS
    ForEach ($file in $files)
    {
    $filePath = $source + "\" + $file;
    $x = Get-Content $filePath
    $x[0] = $x[0].Replace($fstr,$rstr)
    $outfile =  $dest + "\" + $file.Name 
    $x2 = $x[0..($x.Length-2)]
    $x = $x2.ForEach({ $_ + "`n"})
    $x | Set-Content -NoNewline $outfile
    }
    }
    Else {"Source directory doesn't exist"}  
    

    【讨论】:

      【解决方案2】:

      我错过了一个分号......当然

      $outfile =  $dest + "\" + $file.Name
      

      应该是

      $outfile =  $dest + "\" + $file.Name;
      

      【讨论】:

      • 这也有效。我还通过简单地将“$x2=...”移动到下一行来解决该错误。请参阅我提供的答案。
      猜你喜欢
      • 1970-01-01
      • 2014-11-12
      • 2018-07-25
      • 1970-01-01
      • 1970-01-01
      • 2019-10-09
      • 1970-01-01
      • 2020-10-20
      • 1970-01-01
      相关资源
      最近更新 更多