我试图在PowerShell中做一些非常简单的事情.
将修改后的测试保存回文件
function Replace {
$file = Get-Content C:\Path\File.cs
$file | foreach {$_ -replace "document.getElementById", "$"} |out-file -filepath C:\Path\File.cs
}
Run Code Online (Sandbox Code Playgroud)我也试过Set-Content了.
我总是得到未经授权的例外 我可以看到$file有文件内容,写入文件时出错.
我怎样才能解决这个问题?
Get-Content这可能是由获取读取锁并Out-File尝试获取写入锁的cmdlet引起的。类似的问题在这里: Powershell: how do you read & write I/O inside one pipeline?
所以解决方案是:
${C:\Path\File.cs} = ${C:\Path\File.cs} | foreach {$_ -replace "document.getElementById", '$'}
${C:\Path\File.cs} = Get-Content C:\Path\File.cs | foreach {$_ -replace "document.getElementById", '$'}
$content = Get-Content C:\Path\File.cs | foreach {$_ -replace "document.getElementById", '$'}
$content | Set-Content C:\Path\File.cs
Run Code Online (Sandbox Code Playgroud)
基本上,您需要缓冲文件的内容,以便可以关闭文件(Get-Content用于读取),然后应将缓冲区刷新到文件(Set-Content在此期间将需要写锁)。
| 归档时间: |
|
| 查看次数: |
7244 次 |
| 最近记录: |