【发布时间】:2021-05-31 02:32:38
【问题描述】:
Powershell - 获取文本到变量中,使用文本替换另一个文本文件中的文本
有人知道我怎样才能让这段代码工作吗?
#The following fetches the first word of the path of the Public folder to use to modify the string in the next command.
$PFNameString = Get-Content("H:\Temp\PublicFolder-powershell\Word_1_Export.csv")
$Option = [System.StringSplitOptions]::RemoveEmptyEntries
$Separator = "\"
$arr = $PFNameString.Split($Separator,$Option)
$Word = $arr[0] #This is the one word i want to use as replacement text to search for in text file loaded next.
$b = Get-Content -Path "H:\Temp\PublicFolder-powershell\PFPerm.02_YandU_correct_AccessRights.csv"
@(ForEach ($a in $b) {$a.Replace('",$Word', '"$Word')}) > "H:\Temp\PublicFolder-powershell\PFPerm.03_Qot_And_D_correct_AccessRights.csv"
我知道如何替换它,但我希望它使用从第一个文本文件导入的数组中提取的 $Word 变量中的单词,作为“通配符”在第二个文本文件。
在这种情况下,单词是“Distrikt”
我希望脚本将 '",Distrikt' 替换为 '"Distrikt'
如果变量文本发生变化,脚本仍会使用变量文本作为通配符进行搜索。
谢谢
编辑:之后工作脚本的结果:
########## This script first opens the file Word_1_Export.csv and split it into array segments.
######### Then the first word in the array is stored in the variable $Word to make the search function more selective
######## This script opens PFPerm.02_YandU_correct_AccessRights.csv and saves back to PFPerm.03_Qot_And_D_correct_AccessRights.csv after processing.
####### This code replace the first ",$Word in the line, with "$Word so the name will be valid for later processing.
###### This code replace the first ",$WORD" in the line with "$WORD" without comma.
##### The goal with this script is to replace the initial COMMA of the line, and saves back to the new file that can be later used.
#The following fetches the first word of the path of the Public folder to use to modify the string in the next command.
$PFNameString = Get-Content("H:\Temp\PublicFolder-powershell\Word_1_Export.csv") #Get text
$Option = [System.StringSplitOptions]::RemoveEmptyEntries
$Separator = "\" #Sign to use as separator of array segments
$arr = $PFNameString.Split($Separator,$Option) #Splits to array segments based on "\"
$Word = $arr[0] #Fetches the first array segment and stores it into the variable $Word
$b = Get-Content -Path "H:\Temp\PublicFolder-powershell\PFPerm.02_YandU_correct_AccessRights.csv" #Loads in the next text file.
#Special quotes under here is required for the Variable to be possible to access ("`",$Word", "`"$Word")}) - The special single quote here instead of "'" is needed.
#If you only had a static word to lookup, you could specify it with ('",StaticWord', '"StaticWord')}) and do the same, but it would not be dynamic as with this below line of code.
@(ForEach ($a in $b) {$a.Replace("`",$Word", "`"$Word")}) > "H:\Temp\PublicFolder-powershell\PFPerm.03_Qot_And_D_correct_AccessRights.csv"
Start-Sleep -Seconds 0.3 #grants time for script to save txt-files back.
【问题讨论】:
-
这是怎么失败的?请提供您想要的之前和之后的示例,以及您的实际之前和之后的示例。
-
它不会更改文本,因为它似乎无法理解它应该将 $Word 变量与第二个文件中的文本匹配。
标签: powershell variables text replace