简体   繁体   中英

Replacing strings in a PowerShell file and then calling it via batch + command line arguments

This is my PowerShell file:

#Replace.ps1

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

    $content = Get-Content  $filepath

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

    $content | out-file $filepath

This is the batch file which I am using it to call this

#ChangeIP.bat
@echo on
powershell.exe -File E:\Replace.ps1 %1 %2 %3

Now when I try to call the batch file from cmd as:

ChangeIP.bat  "E:\foreign logs.txt" firstword secondword

then it is showing some ridiculous errors.

I basically am stuck in passing the file name (which is having white spaces).

The code I need basically should be able to do the following things:

  1. A PowerShell script that takes three command line arguments:

    • FilePath // With white spaces (don't know how)
    • String to replace
    • String to be replaced with
  2. The PowerShell script should be able to fetch the contents of the "FilePath" supplied. Find the "String to replace" string and Replace it with "String to be replaced with" string

  3. Then calling this PowerShell script via batch file and supplying the three command line arguments there.

Please keep in the mind, the file path contains spaces.

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

$content = $content -replace $find $replace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM