检查谁在Powershell中打开了Excel文件

时间:2016-01-19 19:57:01

标签: excel powershell

我在win7 64位上使用Powershell 4.0,我想看看谁打开了excel文件,或者即使文件是打开的。

实施例。我在网络驱动器B上有excel文件“test”。如果一个人打开“test”我明白会创建一个excel锁文件,看起来像这样的“〜$ test.xls”。 到目前为止,我已使用Test-path验证excel锁文件是否存在。然后我相信我可以使用Get-Acl来查找该文件的所有者。有没有更简单的方法来找出谁有一个excel文件打开?或者我的检查锁文件所有权的解决方法是否有效?

2 个答案:

答案 0 :(得分:0)

我仍然使用基于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

答案 1 :(得分:0)

如果将锁定文件的内容复制到控制台,则应包含锁定文件的用户的名称。您可能必须复制锁定文件才能读取它。我不熟悉PowerShell,但我认为它具有DOS批处理文件的所有功能,并且可以创建类似于我在下面编写的技术。

这是我添加到SendTo文件夹的批处理文件,它允许我右键单击Excel文件,它会显示锁定文件的人。我已使用.xlsx.xlsm文件对此进行了测试。

@echo off
REM ===================================================================
REM  Put this in your SendTo folder and it will let you right-click 
REM  on an .xlsx/.xlsm  file and show you the user name in the lock file
REM 
REM  If an Excel file is locked, look to see if a hidden lock file exists.  If
REM  the file is found, make a local temp copy of it and display the contents which 
REM  should be the name of the user holding the lock.
REM ===================================================================

setlocal
set file="%1"

REM Make sure the file has a compatible extension.
if  "%~x1"==".xlsx"   goto :ExtensionIsValidExcel
if  "%~x1"==".xlsm"   goto :ExtensionIsValidExcel

echo.
echo "%~n1%~x1" is not a supported file type.
echo.
pause
exit


:ExtensionIsValidExcel

REM  If an Excel file is locked, look to see if a hidden lock file exists.  If
REM  the file is found, make a local temp copy of it and display the contents which 
REM  should be the name of the user holding the lock.

IF EXIST %~dp1~$%~n1%~x1 ( 
    ECHO f | Xcopy %~dp1~$%~n1%~x1 "%TEMP%\~temp.txt" /H /R /Y /F
    attrib -h -s %TEMP%\~temp.txt

    cls
    ECHO.
    ECHO The Excel file "%~n1%~x1" file is locked by:
    ECHO.
    REM copy the file to the console to show the user name.
    copy %TEMP%\~temp.txt con | Find /v "file(s) copied" 
    del %TEMP%\~temp.txt
) Else (
    cls
    ECHO.
    ECHO The Excel file "%~n1%~x1" file is not locked in a way this was expecting.
)
ECHO.
ECHO.
pause