![](/img/trans.png)
[英]How can avoid an error inline PowerShell script The process cannot access the file because it is being used by another process?
[英]Set-Content Error : The process cannot access the file because it is being used by another process (Powershell)
我要在此处执行的操作是删除计算机上的所有共享文件夹,但默认文件夹除外,默认文件夹是我在循环浏览之前用一个空格删除的文件夹。 当我突然收到一条错误消息,说我的Set-Content命令由于“正在被另一个进程使用”而无法通过时,它已经工作了大约10分钟。 有任何想法吗? 提前致谢!
旁注:我知道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
您正在使事情复杂化:
for /f
tokens=1
默认情况下为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脚本既不是有用的也不neccessary。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.