Power Shell: 需要在文件内容中放入文件具体名称
Power Shell: Need to put the file specific name in the file content
我有一个文件 test001.txt,我需要在其中用文件名替换一个词。例如:
文件名:test001.txt 包含“向客户发送礼物”
我需要将 CUSTOMER 替换为文件“test001”的名称,但要自动生成。这意味着我在一个文件夹中有多个文件,我想将它们复制到另一个文件夹中,并且当我复制它们时我希望所有文件都有那个词替换其文件名的名称
test001, test002, test003 ..等等,所以在每个文件中都不是 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*”,而不是该位置的文件名
有什么想法吗?感谢你! :)
您可以为此使用 Get-ChildItem
和一个循环。 BaseName 是下面代码中不带扩展名的文件名,请注意我使用的 -creplace
区分大小写(“customer”不会被替换,但“ CUSTOMER" will) 如果你不需要这个使用 -replace
.
$replaceWord = 'CUSTOMER'
Get-ChildItem path/to/giftfiles -Filter *.txt | ForEach-Object {
(Get-Content $_ -Raw) -creplace $replaceWord, $_.BaseName |
Set-Content $_.FullName
}
我有一个文件 test001.txt,我需要在其中用文件名替换一个词。例如:
文件名:test001.txt 包含“向客户发送礼物”
我需要将 CUSTOMER 替换为文件“test001”的名称,但要自动生成。这意味着我在一个文件夹中有多个文件,我想将它们复制到另一个文件夹中,并且当我复制它们时我希望所有文件都有那个词替换其文件名的名称
test001, test002, test003 ..等等,所以在每个文件中都不是 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*”,而不是该位置的文件名
有什么想法吗?感谢你! :)
您可以为此使用 Get-ChildItem
和一个循环。 BaseName 是下面代码中不带扩展名的文件名,请注意我使用的 -creplace
区分大小写(“customer”不会被替换,但“ CUSTOMER" will) 如果你不需要这个使用 -replace
.
$replaceWord = 'CUSTOMER'
Get-ChildItem path/to/giftfiles -Filter *.txt | ForEach-Object {
(Get-Content $_ -Raw) -creplace $replaceWord, $_.BaseName |
Set-Content $_.FullName
}