How to close all open network files in PowerShell?

I am trying to convert my old BAT script to a PowerShell version, but after one hour of googling I have no idea how to do this.

I am looking for a structure very similar to the old one, I will find open network files, get its PID and close it.

BAT:

for /f "skip=4 tokens=1" %a in ('net files ^| findstr C:\Apps\') do net files %a /close

PowerShell?

+5
source share
4 answers

The network file is still the best. Try something like this:

$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

}
+1
source

Here is another way. I like that it relies more on pipelining, which is the PowerShell idiom:

net files | 
    where   { $_.Contains( "D:\" ) } |
    foreach { $_.Split( ' ' )[0] }   |
    foreach { net file $_ /close }
+6
source

:

$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 }
+2

:

#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
 }
}
0

All Articles