首页 > 解决方案 > 设置内容错误:该进程无法访问该文件,因为它正在被另一个进程使用(Powershell)

问题描述

我在这里要做的是删除我计算机上的所有共享文件夹,但默认文件夹除外,我在循环之前用一个空格将其删除。它工作了大约 10 分钟,突然我收到一条错误消息,说我的 Set-Content 命令不会通过,因为“它正在被另一个进程使用”。有任何想法吗?提前致谢!

旁注:我知道这net share %%s /delete是回声。我只是想看看在我真正实施之前会删除哪些内容。


DeletingSharedFiles.bat

set /p name= "Name of the Admin user  |  "
net share> "C:\Users\%name%\Desktop\SharedFiles.txt"

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -Command 
"C:\Users\%name%\Desktop\SharedFiles.ps1"

for /f "tokens=1" %%s in (C:\Users\%name%\Desktop\SharedFiles.txt) do(
    echo net share %%s /delete  
)


SharedFiles.ps1

(Get-Content "C:\Users\$env:name\Desktop\SharedFiles.txt") | 
Foreach-Object {$_ -replace "ADMIN\$", ""} | 
Foreach-Object {$_ -replace "C\$", ""} | 
Foreach-Object {$_ -replace "IPC\$", ""} |  
Set-Content "C:\Users\$env:name\Desktop\SharedFiles.txt" 


的输出DeletingSharedFiles.bat

Set-Content : The process cannot access the file 
'C:\Users\Sebastian\Desktop\SharedFiles.txt' because it is being used
by another process.
At C:\Users\Sebastian\Desktop\SharedFiles.ps1:5 char:1
+ Set-Content "C:\Users\$env:name\Desktop\SharedFiles.txt"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo: NotSpecified: (:) [Set-Content], IOException
    + FullyQualifiedErrorId : 
System.IO.IOException,Microsoft.PowerShell.Commands.SetContentCommand

标签: windowspowershellbatch-filescripting

解决方案


你把事情复杂化了:

  • 绝对不需要临时文件,无论是在批处理中还是在 PowerShell 中。
  • 要删除应该从输出中保留的份额,请使用 findstr /v
  • for /f默认情况下tokens=1,不必表达。

所以一个 cmd 行应该做:

for /f %A in ('net share ^| findstr /IV "^Admin\$ ^C\$ ^IPC\$" ^| findstr ":\\"') do @Echo net share %A /del

或在批处理文件中:

@Echo off
for /f %%A in (
    'net share ^| findstr /IV "^Admin\$ ^C\$ ^IPC\$" ^| findstr ":\\"'
) do Echo net share %%A /del

执行完整任务的 PowerShell 脚本(需要 Win10):

Get-SmbShare | Where-Object Name -notmatch "^Admin\$|^C\$|^IPC\$" | Remove-SMBShare -WhatIf

您的Powershellscript 可以简化:

(Get-Content "C:\Users\$env:name\Desktop\SharedFiles.txt") -replace "^ADMIN\$|^C\$|^IPC\$" |  
Set-Content "C:\Users\$env:name\Desktop\SharedFiles.txt" 

但请记住,通过删除这些共享名称for /f您的批处理将忽略前导分隔符,然后将资源名称/描述作为第一个标记。


总而言之,混合批处理/PowerShell 脚本既没有用也没有必要。


推荐阅读