【问题标题】:Get-Content : Cannot bind argument to parameter 'Path' because it is an empty s tringGet-Content:无法将参数绑定到参数“路径”,因为它是一个空字符串
【发布时间】:2016-10-25 07:09:48
【问题描述】:

我是 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:无法将参数绑定到参数“路径”,因为它是 一个空的字符串。在 C:\Users\yeturukr\Desktop\Test\Rep.ps1:1 char:13 + (获取内容 降低,Microsoft.PowerShell.Commands.GetContentCommand

【问题讨论】:

    标签: powershell batch-file cmd


    【解决方案1】:

    echo Get-Content "%3" 结果类似于带有 doubled 双引号的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
    
    ==>
    

    【讨论】:

    • JosefZ,我在尝试时遇到了错误。错误:获取内容:找不到路径“C:\Users\yeturukr\Desktop\Test\Dest\.txt”,因为它不存在。
    • 请仔细检查您的脚本。看起来像扩展 %~dpx3%~dpx4。应该按照建议,例如%~3 或可能是 %~dpnx3%~f3
    • 非常感谢 JosefZ。你的代码有效。我在写代码时犯了一个错误。
    猜你喜欢
    • 1970-01-01
    • 2017-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 1970-01-01
    相关资源
    最近更新 更多