Powershell: неожиданный токен в выражении или инструкции

#powershell

#powershell

Вопрос:

Трудно устранить это

 $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"}  
  

Я получаю сообщение об ошибке, в котором говорится, что неожиданный токен ‘$ x2’ в выражении или инструкции

Ответ №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;
  

Комментарии:

1. Это тоже работает. Я также устранил ошибку, просто переместив «$ x2 = …» на следующую строку. Смотрите предоставленный мной ответ.