我试图将我的旧BAT脚本转换为PowerShell版本, 但一小时后Google搜索我不知道该怎么做。如何在PowerShell中关闭所有打开的网络文件?
我正在寻找一个非常类似于旧的结构,找到打开的网络文件, 得到它的PID并关闭它。
BAT:
for /f "skip=4 tokens=1" %a in ('net files ^| findstr C:\Apps\') do net files %a /close
PowerShell的?
我试图将我的旧BAT脚本转换为PowerShell版本, 但一小时后Google搜索我不知道该怎么做。如何在PowerShell中关闭所有打开的网络文件?
我正在寻找一个非常类似于旧的结构,找到打开的网络文件, 得到它的PID并关闭它。
BAT:
for /f "skip=4 tokens=1" %a in ('net files ^| findstr C:\Apps\') do net files %a /close
PowerShell的?
净文件仍然是你最好的选择。尝试是这样的:
$results = net file | Select-String -SimpleMatch "C:\Apps\"
foreach ($result in $results) {
#Get id
$id = $result.Line.Split(" ")[0]
#Close file
net file $id /close
}
试试这个:
#capture command output
$openfiles=net files
#parse all lines and watch for c:\apps\
$openfiles| foreach {
if($_ -like '*c:\apps\*'){
#if line contains c:\apps\ split it with space, the first element will be file id
net files $_.split(' ')[0] /close
}
}
你可以用它来查看打开文件:
$adsi = [adsi]"WinNT://./LanmanServer"
$resources = $adsi.psbase.Invoke("resources") | Foreach-Object {
New-Object PSObject -Property @{
ID = $_.gettype().invokeMember("Name","GetProperty",$null,$_,$null)
Path = $_.gettype().invokeMember("Path","GetProperty",$null,$_,$null)
OpenedBy = $_.gettype().invokeMember("User","GetProperty",$null,$_,$null)
LockCount = $_.gettype().invokeMember("LockCount","GetProperty",$null,$_,$null)
}
}
$resources
然后过滤要关闭的那些:
$resources | Where-Object { $_.Path -like 'c:\apps\*'} |
Foreach-Object { net files $_.ID /close }
我喜欢你要采用物体丰富的方法,而不是文本消除,但在这种情况下,它很笨拙。 –
是的,你可以将它包装在一个函数中,并隐藏复杂性。顺便说一下,它可能已经更完整了,过去曾使用Remove方法的集合具有Remove方法,但它似乎缺少。这样做的另一个优点是可以运行在远程计算机上,目前仅用于获取文件。 –
这里的另一种方式。我喜欢它更依赖流水线,这是PowerShell的成语:
net files |
where { $_.Contains("D:\") } |
foreach { $_.Split(' ')[0] } |
foreach { net file $_ /close }
我不认为这个范围太窄,或者不太可能帮助别人。关闭网络文件很常见。我只需要相同的东西。这个问题不是要求某人转换一个旧的批处理文件,而是要显示它是如何完成的。 – Knox
我同意,这个问题不应该被关闭。这正是我需要的 –
更适合http://superuser.com/。 –