iT邦幫忙

0

利用powershell取代文字

VP 2019-03-04 13:38:154254 瀏覽

小弟我想利用變數(我從batch傳值過去ps1)來自動取代文字檔裡的文字
ps1內容如下:

$a=$args[0]
$b=$args[1]
(Get-Content -path C:\Program Files\BRAINBURST\res\tool_u.ini) -replace $a, $b | Set-Content -Encoding UTF8 C:\Program Files\BRAINBURST\res\tool_u.ini

但是出現以下錯誤:

Get-Content : 找不到接受引數 'Files\BRAINBURST\res\tool_u.ini' 的位置參數。
位於 C:\Program Files\BRAINBURST\res\DIFDIR.ps1:8 字元:2

  • (Get-Content -path C:\Program Files\BRAINBURST\res\tool_u.ini) -repla ...
  •  + CategoryInfo          : InvalidArgument: (:) [Get-Content],ParameterBindingException
     + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommand
    
    

請問有大大有解的嗎?

先用powershell -file "xxx.ps1 arg1 arg2" 跑看看..是不是參數帶入來的問題.
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
jeles51
iT邦研究生 3 級 ‧ 2019-03-04 14:28:32
最佳解答

重新模擬 LAB 如下,有修改部份指令,已實測成功

bat檔

@echo off
set JDK_Version=1.8
for /d %%i in ("%ProgramFiles%\Java\jdk%jdk_Version%*") do (set Located=%%i)
set JAVA_HOME=%Located%
SET SC=C:\Program Files\Java\jdk1.8.0_181

REM 將值存成文字檔,方便 powershell呼叫
md c:\programdata
md c:\programdata\tmp
echo %SC%>c:\programdata\tmp\sc.txt
echo %JAVA_HOME%>c:\programdata\tmp\jh.txt

REM 如果兩個資料夾不相等,就執行REPLACE的部份
if "%JAVA_HOME%" NEQ "%SC%" goto REPLACE
else goto END

:REPLACE
powershell.exe -ExecutionPolicy Bypass -File "C:\Program Files\BRAINBURST\res\DIFDIR.ps1" 

:END
echo SC=%SC%
echo JHOME=%JAVA_HOME%
echo done!!

DIFDIR.ps1

#gc=Get-Content
$a=gc c:\programdata\tmp\sc.txt
$b=gc c:\programdata\tmp\jh.txt
$c=gc 'C:\Program Files\BRAINBURST\res\tool_u.ini'
#主要問題出在下面這行 replace
$c.replace($a, $b) | Set-Content -Encoding UTF8 'C:\Program Files\BRAINBURST\res\tool_u.ini'
VP iT邦新手 1 級 ‧ 2019-03-04 14:36:24 檢舉

加了引號以後還是一樣... (((炸

規則運算式模式 C:\Program Files\Java\jdk1.8.0_181 無效。
位於 C:\Program Files\BRAINBURST\res\DIFDIR.ps1:8 字元:1

  • (Get-Content -path 'C:\Program Files\BRAINBURST\res\tool_u.ini') -rep ...
  •   + CategoryInfo          : InvalidOperation: (C:\Program Files\Java\jdk1.8.0_181:String) [],RuntimeException
      + FullyQualifiedErrorId : InvalidRegularExpression
    
VP iT邦新手 1 級 ‧ 2019-03-17 21:37:25 檢舉

抱歉這麼晚才回
這問題好像是卡在PS比較的部分
我猜它"可能"是不能含有空格
所以我找到了另外一個替代方案
可以利用PS建一個FUNCTION從右至左去三碼版本號碼
https://ss64.com/ps/right.html
這樣實測沒有問題

我要發表回答

立即登入回答