在Powershell中保存.dat文件的查找和替换文本函数

在Powershell中保存.dat文件的查找和替换文本函数,powershell,replace,Powershell,Replace,我正在制作一个脚本,该脚本将查找一个单词的所有实例,并将其替换为另一个。但是,我不确定如何保存更改 $file = Get-Content "C:\Script.dat" -Raw $old = 'oldword' $new = 'newword' $file.Replace($old,$new) 起初,我使用了以下方法,但这导致了一些问题 $file.Replace($old,$new) | Set-Content $file 这导致了错误的问题 Set-Content : Canno

我正在制作一个脚本,该脚本将查找一个单词的所有实例,并将其替换为另一个。但是,我不确定如何保存更改

$file = Get-Content "C:\Script.dat" -Raw
$old = 'oldword' 
$new = 'newword'
$file.Replace($old,$new) 
起初,我使用了以下方法,但这导致了一些问题

$file.Replace($old,$new) | Set-Content $file
这导致了错误的问题

Set-Content : Cannot find drive. A drive with the same *some random stuff*...

如何保存更改和/或修复上述问题?

您非常接近,但设置内容需要两件事:文件位置的路径和要存储的值。就我个人而言,我更喜欢在使用
.Replace()
方法时覆盖变量,而不是将其导入其他cmdlet

$file = Get-Content "C:\Script.dat" -Raw
$old = 'oldword' 
$new = 'newword'
$file.Replace($old,$new) | Out-File -FilePath C:\Script.dat
这可以做到:

$file = Get-Content "C:\Script.dat" -Raw
$old = 'oldword' 
$new = 'newword'
$file = $file.Replace($old,$new)
Set-Content -Path "C:\Script.dat" -Value $file
如果可能,尽量避免将文件直接存储在
C:\
上,因为这通常需要管理员权限才能写入

此外,您可以使用与最初列出的方式类似的管道连接到
设置内容
,但仍需要为其提供文件路径:

$file.Replace($old,$new) | Set-Content "C:\Script.dat"

您非常接近,但是设置内容需要两件事:文件位置的路径和要存储的值。就我个人而言,我更喜欢在使用
.Replace()
方法时覆盖变量,而不是将其导入其他cmdlet

这可以做到:

$file = Get-Content "C:\Script.dat" -Raw
$old = 'oldword' 
$new = 'newword'
$file = $file.Replace($old,$new)
Set-Content -Path "C:\Script.dat" -Value $file
如果可能,尽量避免将文件直接存储在
C:\
上,因为这通常需要管理员权限才能写入

此外,您可以使用与最初列出的方式类似的管道连接到
设置内容
,但仍需要为其提供文件路径:

$file.Replace($old,$new) | Set-Content "C:\Script.dat"