我有一個檔案 test001.txt,我需要用檔案名替換一個詞。例如:
檔案名:test001.txt 包含“發送禮物給客戶”
我需要將 CUSTOMER 替換為檔案“test001”的名稱,但要自動生成。這意味著我在一個檔案夾中有多個檔案,我想將它們復制到另一個檔案夾中,當我復制它們時,我希望所有檔案都用該詞替換其檔案名的名稱
test001, test002, test003 ..etc,所以每個檔案中都不是CUSTOMER,而是:test001, test002, test003 ...
我試過:
Copy-Item "C:\Location1\*" -Destination "C:\location2" -----to copy all files
$fileName = "C:\Location1\*" ----to take names for all files
$currentDate = get-date -format "yyMMdd"
$automationTest = "C:\Location2\test1.DDI" ---name of new file
$content = [System.IO.File]::ReadAllText($automationTest).Replace("CUSTOMER",$fileName)
[System.IO.File]::WriteAllText($automationTest, $content)
但它實際上是替換為“C:\Location1*”,而不是該位置的檔案名
有任何想法嗎?感謝你!:)
uj5u.com熱心網友回復:
您可以Get-ChildItem為此使用一個回圈。BaseName是下面代碼中不帶擴展名的檔案名,請注意,我使用的-creplace是區分大小寫的(“customer”不會被替換,但“CUSTOMER”會),以防您不需要使用-replace。
$replaceWord = 'CUSTOMER'
Get-ChildItem path/to/giftfiles -Filter *.txt | ForEach-Object {
(Get-Content $_ -Raw) -creplace $replaceWord, $_.BaseName |
Set-Content $_.FullName
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/392530.html
