Get-Content:无法将参数绑定到参数' Path'因为它是空的

时间:2016-10-25 07:09:48

标签: powershell batch-file cmd

我是ShellScript的新手。这是我删除' ONEWORD'的代码。从提到的路径:如果我不在文件名中引入空格,它的工作正常。但是如果文件名中有空格,则会抛出以下错误:

计划:

call:DoReplace "ONEWORD" "" "C:\Users\yeturukr\Desktop\Test\Dest\CMD COMET.txt" "C:\Users\yeturukr\Desktop\Test\Dest\CMD COMET.txt"
  exit /b

  :DoReplace
  echo ^(Get-Content "%3" ^) ^| ForEach-Object { $_ -replace %1, %2 } ^| Set-Content %4 >Rep.ps1
  Powershell.exe -executionpolicy ByPass -File Rep.ps1
  if exist Rep.ps1 del Rep.ps1
  echo Done
  pause

错误:

  

Get-Content:无法将参数绑定到参数' Path'因为它是   空洞的。在C:\ Users \ yeturukr \ Desktop \ Test \ Rep.ps1:1 char:13   +(Get-Content<<<<<"" C:\ Users \ yeturukr \ Desktop \ Test \ Dest \ CMD COMET_APIN002234   _20161025_0745_1.txt"" )| ForEach-Object {$ _ -replace" BARCAP","" } | Set-Co ntent" C:\ Users \ yeturukr \ Desktop \ Test \ Dest \ CMD   COMET_APIN002234_20161025_0745_1 .txt"       + CategoryInfo:InvalidData:(:) [Get-Content],ParameterBinding ValidationException       + FullyQualifiedErrorId:ParameterArgumentValidationErrorEmptyStringNotAl
  lowed,Microsoft.PowerShell.Commands.GetContentCommand

1 个答案:

答案 0 :(得分:1)

echo Get-Content "%3"会产生Get-Content ""…\CMD COMET.txt"",其中加倍双引号(无效的路径规范)。

按如下方式申请Parameter Extensions

:DoReplace
echo ^(Get-Content "%~3" ^) ^| ForEach-Object { $_ -replace "%~1", "%~2" } ^| Set-Content "%~4" >Rep.ps1

现在您可以完全控制使用双引号。

编辑:制作了一个复杂的示例脚本,用于证明以上工作原理:

@ECHO OFF >NUL
SETLOCAL EnableExtensions DisableDelayedExpansion

set "_fileIn=%userprofile%\Desktop\Test\Dest\CMD COMET.txt"
set "_fileOu=%userprofile%\Desktop\Test\Dest\CMD COMET.txt"

rem csteate sample files
md "%userprofile%\Desktop\Test\Dest\" 2>NUL
 >"%_fileOu%" type NUL
 >"%_fileIn%" echo 1st line 
>>"%_fileIn%" echo 2nd oneword
>>"%_fileIn%" echo 3rd line
type "%_fileIn%"

call:DoReplace "ONEWORD" "" "%_fileIn%" "%_fileOu%"

  type "%_fileOu%"
  exit /b

:endlocal
ENDLOCAL
goto :eof

  :DoReplace
  echo ^(Get-Content "%~3" ^) ^| ForEach-Object { $_ -replace "%~1", "%~2" } ^| Set-Content "%~4" >Rep.ps1
  Powershell.exe -executionpolicy ByPass -File Rep.ps1
  REM type Rep.ps1
  if exist Rep.ps1 del Rep.ps1
  echo Done
  goto :eof

<强>输出

==> D:\bat\SO\40233525.bat
1st line
2nd oneword
3rd line
Done
1st line
2nd
3rd line

==>