替换PowerShell文件中的字符串,然后通过批处理+命令行参数调用它

时间:2017-06-20 20:58:49

标签: windows powershell batch-file

这是我的PowerShell文件:

#Replace.ps1

    Param(
       [string]$filepath,
       [string]$find,
       [string]$replace
     )

    $content = Get-Content  $filepath

    $content = $content.replace($find,$replace)

    $content | out-file $filepath

这是我用来调用此

的批处理文件
#ChangeIP.bat
@echo on
powershell.exe -File E:\Replace.ps1 %1 %2 %3

现在,当我尝试从cmd调用批处理文件时:

ChangeIP.bat  "E:\foreign logs.txt" firstword secondword
然后它显示出一些荒谬的错误。

我基本上没有传递文件名(有空格)。

我需要的代码基本上应该能够做到以下几点:

  1. 一个PowerShell脚本,它带有三个命令行参数:

    • FilePath //带有空格(不知道如何)
    • 要替换的字符串
    • 要替换为
    • 的字符串
  2. PowerShell脚本应该能够获取所提供的“FilePath”的内容。找到“要替换的字符串”字符串并将其替换为“要替换为字符串

  3. 的字符串
  4. 然后通过批处理文件调用此PowerShell脚本并在那里提供三个命令行参数。

  5. 请记住,文件路径包含空格。

1 个答案:

答案 0 :(得分:0)

如果您正在启动PowerShell v2,请尝试使用-replace运算符而不是Replace()方法:

$content = $content -replace $find $replace