字符串变量在写入文本文件时表现异常

String variable acting strange when writing to text file

下面是我遇到问题的代码。它从 config.txt 文件中提取信息并将信息设置到 childofRoot.properties 文件中。出于某种原因,当我设置它时,字符串会额外添加。

$date = (Get-Date -Format "MM-dd-yyyy'_'HH-mm")
$backup = 'backuplocation'
$temp = 'replace'
$p = ($PSScriptRoot + 'childofRoot.properties')


$cuidConf = Get-Content -Path ($PSScriptRoot + 'config.txt') | Select-String "cuids_rootfolder=" | Out-String
$cuidConf = $cuidConf.replace("cuids_rootfolder=", "").replace("`n", "")
$cuids = $cuidConf.Split(";")

$backuppath = ((Get-Content -Path ($PSScriptRoot + 'config.txt'))) | Select-String "backuplocation=" | Out-String
$backuppath = $backuppath.replace("backuplocation=", "").replace("`n", "")
$backuppath = $backuppath + $date + "\"


$foldername, $cuid = ($cuids[0].Split(","))

$backup1 = ($backuppath + "Folder a.lcmbiar")
        


((Get-content -Path $p).replace($temp, $cuid)) | Set-Content -Path $p

((Get-content -Path $p).replace($backup, $backup1)) | Set-Content -Path $p

config.txt 的内容:

backuplocation=C:\backuplcm\backupfiles\

childofRoot.properties的内容:

exportLocation=backuplocation

写入 childofRoot.properties 的预期输出:

exportLocation=C:\backuplcm\backupfiles-18-2020_17-59\Folder\a.lcmbiar

我看到的输出写入 childofRoot.properties:

exportLocation=
C:\backuplcm\backupfiles\


08-18-2020_18-02\Folder a.lcmbiar

是的,我已经尝试使用 .replace("`n","") 删除换行符 我也让其他人查看了这个脚本,当我设置变量时,它看起来很好,但在文本文件中却有所不同。 我能够在不同机器上的 Powershell 4 和 Powershell 5 上复制它。如果有人会在他们的机器上尝试这个,看看他们是否能解决问题。

额外的换行符来自 | Select-String "backuplocation=" | Out-String.Replace("`n", "") 没有解决问题的原因是 Windows 使用序列 "`r`n" 换行.

我建议使用 Where-Object 而不是 Select-String | Out-String 来简化您的脚本:

$backuppath = Get-Content -Path (Join-Path $PSScriptRoot config.txt) | Where-Object {$_ -match "backuplocation="}
$backuppath = $backuppath -replace 'backuplocation='