我仍然使用基于 Netapi32 的函数来实现这一点。
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class Netapi
{
[DllImport("Netapi32.dll",CharSet=CharSet.Unicode)]
public static extern int NetApiBufferFree(IntPtr buffer);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct FILE_INFO_3
{
public uint FileID;
public uint Permissions;
public uint NumLocks;
[MarshalAs(UnmanagedType.LPWStr)] public string Path;
[MarshalAs(UnmanagedType.LPWStr)] public string User;
}
[DllImport("Netapi32.dll",CharSet=CharSet.Unicode)]
public static extern uint NetFileEnum(
[In,MarshalAs(UnmanagedType.LPWStr)] string server,
[In,MarshalAs(UnmanagedType.LPWStr)] string path,
[In,MarshalAs(UnmanagedType.LPWStr)] string user,
int level,
out IntPtr bufptr,
int prefmaxlen,
ref Int32 entriesread,
ref Int32 totalentries,
ref Int32 resume_handle);
}
"@
function Get-OpenFiles
{
[CmdletBinding()]
param ( [string]$Server = "localhost",
[string]$User = $null,
[string]$Path = $null)
$struct = New-Object netapi+FILE_INFO_3
$buffer = 0
$entries = 0
$total = 0
$handle = 0
$Level=3 # used to define the type of struct we want, i.e. FILE_INFO_3
$ret = [Netapi]::NetFileEnum($server, $path, $user, $level,
[ref]$buffer, -1,
[ref]$entries, [ref]$total,
[ref]$handle)
$files = @()
if (!$ret)
{
$offset = $buffer.ToInt64()
$increment = [System.Runtime.Interopservices.Marshal]::SizeOf([System.Type]$struct.GetType())
for ($i = 0; $i -lt $entries; $i++)
{
$ptr = New-Object system.Intptr -ArgumentList $offset
$files += [system.runtime.interopservices.marshal]::PtrToStructure($ptr, [System.Type]$struct.GetType())
$offset = $ptr.ToInt64()
$offset += $increment
}
}
else
{
Write-Output ([ComponentModel.Win32Exception][Int32]$ret).Message
if ($ret -eq 1208)
{
# Error Code labeled "Extended Error" requires the buffer to be freed
[Void][Netapi]::NetApiBufferFree($buffer)
}
}
$files
}
然后你可以调用 Get-OpenFiles 并传递一个特定的路径名:
Get-OpenFiles -Path C:\Temp\EXCEL.XLSX
FileID : 205
Permissions : 35
NumLocks : 0
Path : C:\Temp\EXCEL.XLSX
User : mickyb
使用Get-OpenFiles -Path C:\Temp 也可以:
FileID : 205
Permissions : 35
NumLocks : 0
Path : C:\Temp\EXCEL.XLSX
User : mickyb
FileID : 213
Permissions : 51
NumLocks : 0
Path : C:\Temp\~$Excel.xlsx
User : mickyb
您还可以查看特定用户是否打开了文件:
Get-OpenFiles -User mickyb