
當該指令位於批次檔中的一行時,此指令可將txt 檔案中的 ,和實例替換為OldText1
,和,如下所示:OldText2
OldText3
NewText1
NewText2
NewText3
start /wait /min Powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "Get-ChildItem 'Old and New text.txt' | ForEach-Object {(Get-Content $_) -replace 'OldText1', 'NewText1' -replace 'OldText2', 'NewText2' -replace 'OldText3', 'NewText3' | Set-Content $_.FullName}"
如果我嘗試使用^
符號來拆分命令(通常在批次檔中工作),則它不起作用。例如,這不起作用,txt 檔案中沒有任何內容被替換:
start /wait /min Powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "Get-ChildItem 'Old and New text.txt' | ForEach-Object {(Get-Content $_) ^
-replace 'OldText1', 'NewText1' ^
-replace 'OldText2', 'NewText2' ^
-replace 'OldText3', 'NewText3' ^
| Set-Content $_.FullName}"
使用反引號也不起作用(但它不會起作用,因為這不是 PS1 腳本):
start /wait /min Powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "Get-ChildItem 'Old and New text.txt' | ForEach-Object {(Get-Content $_) `
-replace 'OldText1', 'NewText1' `
-replace 'OldText2', 'NewText2' `
-replace 'OldText3', 'NewText3' `
| Set-Content $_.FullName}"
我整個早上都在詢問聊天機器人的問題,但它無法提出任何有效的建議。有一半的時間它不斷地將命令再次放在一行上,而我只是在繞著它轉圈。
難道我想做的事情不可能嗎?
我想將命令拆分為多行的原因很簡單,因為我希望能夠讀取正在替換的內容,而不必沿著(最終將是)一個龐大的命令水平查看。我打算添加比這更多的替換命令,但即使對於三個替換命令它也不起作用......但是!
提前感謝任何可能知道為什麼這不起作用的人。
答案1
我不清楚:
Get-ChildItem 'Old and New text.txt' | ForEach-Object {(Get-Content $_)
這部分建議您將獲取資料夾中的項目,確切地說是文件項目,但您的命令立即定義一個文件,其中字串替換將在內容中完成。
看,透過刪除該部分,替換結果按預期出現,但如果這是針對相同替換的多個文件,那麼我建議編輯問題。雖然令人困惑,但對於內容處理你不需要“ Get-ChildItem 'Old and New text.txt' | ...
”,你可以直接使用Get-Content 'Old and New text.txt' ^|...
start "Start PS1/CMD" /wait /min PowerShell.exe -c ^
"$Strings=Get-Content 'Old And New Text.txt' ^| %% ^
^{ $_ -replace('OldText1','NewText1')^
-replace('OldText2','NewText2')^
-replace('OldText3','NewText3')^}^
; sc 'Old And New Text.txt' -Value $Strings -Force"