Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Powershell 设置内容将生成新文件,但未成功';不要更换旧的_Powershell_Input_Output - Fatal编程技术网

Powershell 设置内容将生成新文件,但未成功';不要更换旧的

Powershell 设置内容将生成新文件,但未成功';不要更换旧的,powershell,input,output,Powershell,Input,Output,我有一个Powershell脚本,可以跟踪库存文本文件。我想用脚本更新文本文件。以下行将根据用户的请求从库存中删除项目: Get-Content inventory | Where-Object {$_ -notmatch "$removed"} | Set-Content inventory.new 它工作正常,但我想更新原始库存文件,即,我不想创建“inventory.new”,我只想更新“inventory”。如果我将inventory.out替换为inventory我会遇到以下错误:

我有一个Powershell脚本,可以跟踪库存文本文件。我想用脚本更新文本文件。以下行将根据用户的请求从库存中删除项目:

Get-Content inventory | Where-Object {$_ -notmatch "$removed"} | Set-Content inventory.new
它工作正常,但我想更新原始库存文件,即,我不想创建“inventory.new”,我只想更新“inventory”。如果我将
inventory.out
替换为
inventory
我会遇到以下错误:

Set-Content : The process cannot access the file 'path\inventory' because it is being used by another process.

有趣的是,我可以删除
库存
,然后将
库存.out
重命名为
库存
。同样,这是可行的,但并不理想。我只是觉得测试它很傻。一定有更优雅的解决方案

我的理解是,当您使用Get Content打开文件时,该文件一直在使用,直到该命令结束,因此在Get Content释放该文件之前,它不会允许您进行更改

一个简单的解决方法可能是:

$inventory = Get-Content inventory | Where-Object {$_ -notmatch "$removed"}
$inventory | Set-Content inventory

这很有效,谢谢你的解释。这确实在我的清单文件末尾添加了一个换行符(公平地说,它以前也这样做过)。Powershell是否有方法选择最后一行换行符,以便文件中的最后一行包含合法条目?@Reubens4Dinner您可以阅读此内容或答案,将gc括在括号中,以便在管道
(获取内容清单)|其中对象{$-notmatch“$removed”}之前处理并发布文件|设置内容目录。新建