-在 Powershell 中替换更改数据但不保存它
-replace in powershell changing data but not saving it
$xmlFilePath = 'Desktop\original.xml'
$xmlfile = get-content $xmlFilePath
$xmlfile -Replace 'box','boxes'
original.xml 包含一些数据,我想用 'box' 替换 xml 文件中的“框”值。 power shell 给出预期的输出但不改变实际文件 original.xml。我在 power shell 中得到了更改的输出,但是当我在桌面上查看文件时,文件没有更改。
你只是在改变内存中的值。您必须再次将该变量输出到原始 .xml 文件。方法如下:
$xmlFilePath = 'Desktop\original.xml'
$xmlfile = get-content $xmlFilePath
$xmlfile = $xmlfile -Replace 'box','boxes'
$xmlfile | Out-File $xmlFilePath
您可以使用 Get-Content to read a file's contents into memory, apply the string replacements, and then pass the contents through the pipeline to Set-Content.
$xmlFilePath = 'Desktop\original.xml'
(Get-Content $xmlFilePath) -replace 'box','boxes' | Set-Content $xmlFilePath
必须在 Get-Content
命令周围使用 ()
以防止解析器将 -replace
解释为参数。
请注意,如果您想将文件内容作为单个字符串读入,可以使用 -Raw
开关打开 Get-Content
。不使用 -Raw
可能会添加额外的换行符。
$xmlFilePath = 'Desktop\original.xml'
$xmlfile = get-content $xmlFilePath
$xmlfile -Replace 'box','boxes'
original.xml 包含一些数据,我想用 'box' 替换 xml 文件中的“框”值。 power shell 给出预期的输出但不改变实际文件 original.xml。我在 power shell 中得到了更改的输出,但是当我在桌面上查看文件时,文件没有更改。
你只是在改变内存中的值。您必须再次将该变量输出到原始 .xml 文件。方法如下:
$xmlFilePath = 'Desktop\original.xml'
$xmlfile = get-content $xmlFilePath
$xmlfile = $xmlfile -Replace 'box','boxes'
$xmlfile | Out-File $xmlFilePath
您可以使用 Get-Content to read a file's contents into memory, apply the string replacements, and then pass the contents through the pipeline to Set-Content.
$xmlFilePath = 'Desktop\original.xml'
(Get-Content $xmlFilePath) -replace 'box','boxes' | Set-Content $xmlFilePath
必须在 Get-Content
命令周围使用 ()
以防止解析器将 -replace
解释为参数。
请注意,如果您想将文件内容作为单个字符串读入,可以使用 -Raw
开关打开 Get-Content
。不使用 -Raw
可能会添加额外的换行符。