Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何在以前连接的USB设备上获取时间戳?_C#_Windows_Powershell_Usb Drive_Computer Forensics - Fatal编程技术网

C# 如何在以前连接的USB设备上获取时间戳?

C# 如何在以前连接的USB设备上获取时间戳?,c#,windows,powershell,usb-drive,computer-forensics,C#,Windows,Powershell,Usb Drive,Computer Forensics,我正在尝试使用一个旧的PowerShell脚本来显示以前连接的USB设备的时间。在读了一些法医学之后,我发现。(杰森·沃克编剧) 不幸的是,它没有显示任何时间戳或关于设备的任何其他有用细节。所以我希望。只是我看不到如何把它结合起来 函数获取USBHistory{ [CmdletBinding()] Param ( [参数(ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)] [别名(“CN”、“计算机”)] [Strin

我正在尝试使用一个旧的PowerShell脚本来显示以前连接的USB设备的时间。在读了一些法医学之后,我发现。(杰森·沃克编剧)

不幸的是,它没有显示任何时间戳或关于设备的任何其他有用细节。所以我希望。只是我看不到如何把它结合起来

函数获取USBHistory{
[CmdletBinding()]
Param
( 
[参数(ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
[别名(“CN”、“计算机”)]
[String[]$ComputerName=$Env:ComputerName,
[开关]$Ping
) 
开始{
$TemperatorAction=$ErrorActionPreference
$ErrorActionPreference=“停止”
$Hive=“LocalMachine”
$Key=“SYSTEM\CurrentControlSet\Enum\USBSTOR”
} 
过程
{             
$USBDevices=@()
$ComputerCounter=0
ForEach($ComputerName中的计算机)
{ 
$USBSTORSubKeys1=@()
$ChildSubkeys=@()
$ChildSubkeys1=@()
$ComputerCounter++
$Computer=$Computer.Trim().ToUpper()
写入进度-活动“收集USB历史记录”-状态“从$Computer检索USB历史记录”-完成百分比($ComputerCounter/($ComputerName.Count)*100))
如果($Ping)
{ 
If(-not(测试连接-计算机名$Computer-计数1-安静))
{ 
写入警告“在$Computer上Ping失败”
继续
} 
}#如果ping结束
尝试
{ 
$Reg=[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($Hive,$Computer)
$USBSTORKey=$Reg.OpenSubKey($Key)
$USBSTORSubKeys1=$USBStorworky.GetSubKeyNames()
}#结束尝试
抓住
{ 
写入警告“连接到$Computer上的注册表时出错,或找不到USBSTOR项。请确保远程计算机上正在运行远程注册表服务。”
}#端接
ForEach($USBStorSubKey1中的SubKey1)
{     
$ErrorActionPreference=“继续”
$Key2=“SYSTEM\CurrentControlSet\Enum\USBSTOR\$SubKey1”
$RegSubKey2=$Reg.OpenSubKey($Key2)
$SubkeyName2=$RegSubKey2.GetSubKeyNames()
$ChildSubkeys+=“$Key2\$SubKeyName2”
$RegSubKey2.Close()
}#结束foreach子键1
ForEach($childsubkey中的Child)
{ 
如果($Child-match“”)
{ 
$BabySubkey=$null
$ChildSubkey1=($Child.split(“”)[0]
$SplitChildSubkey1=$ChildSubkey1.split(\“”)
0..4 | Foreach{[String]$BabySubkey+=($SplitChildSubkey1[$\])+“\”}
$childsubkey 1+=$BabySubkey+($Child.split(“”[-1])
$ChildSubkeys1+=$ChildSubkey1
} 
其他的
{ 
$ChildSubkeys1+=$Child
} 
$ChildSubKeys1.count
}#结束foreach子键
ForEach($ChildSubkey1中的$ChildSubkey1)
{     
$USBKey=$Reg.OpenSubKey($ChildSubkey1)
$USBDevice=$USBKey.GetValue('FriendlyName')
如果($usb设备)
{     
$USBDevices+=新对象-TypeName PSObject-Property@{
USBDevice=$USBDevice
计算机=$计算机
串行=$ChildSubkey1.Split(“\”[-1]
} 
} 
$USBKey.Close()
}#结束foreach ChildSubKey2
$usbstorky.Close()
#显示结果
$USB设备|选择计算机、USB设备、串行
}#每台计算机的末端
}#结束过程
终点
{         
#将错误操作首选项设置回原始设置
$ErrorActionPreference=$TemperatorAction
} 
}#端函数
C#代码:

使用系统;
使用系统诊断;
使用System.Linq;
使用System.Runtime.InteropServices;
使用Microsoft.Win32;
使用Microsoft.Win32.SafeHandles;
班级计划
{
静态void Main(字符串[]参数)
{
字符串usbStor=@“SYSTEM\ControlSet001\Enum\usbStor”;
使用(var keyusbtor=Registry.LocalMachine.OpenSubKey(usbStor))
{
var usbDevices=来自keyusbtor.GetSubKeyNames()中的className
让keyUsbClass=keyUsbStor.OpenSubKey(类名)
来自keyUsbClass.GetSubKeyNames()中的instanceName
让keyUsbInstance=newregistrykeyex(keyUsbClass.OpenSubKey(instanceName))
选择新的
{
UsbName=keyUsbInstance.Key.GetValue(“FriendlyName”),
ConnectTime=KeyusBinInstance.LastWriteTime
};
foreach(usbDevices.OrderBy(x=>x.ConnectTime)中的var usbDevice)
{
WriteLine(({0}--'{1}',usbDevice.ConnectTime,usbDevice.UsbName);
}
}
}
}
/// 
///包装RegistryKey对象和相应的上次写入时间。
/// 
/// 
///.NET不公开注册表项的上次写入时间
///在RegistryKey类中,因此需要P/Invoke。
/// 
公共类注册表KeyEx
{
#区域P/Invoke声明
//此声明仅用于最后一次写入。使用int
//而不是更方便的类型,因此0的伪值可以减少冗长。
[DllImport(“advapi32.dll”,EntryPoint=“RegQueryInfoKey”,CallingConvention=CallingConvention.Winapi,SetLastError=true)]
外部私有静态int RegQueryInfoKey(
安全注册表句柄hkey,
$code = @"
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.Win32;
using Microsoft.Win32.SafeHandles;

/// <summary>
/// Wraps a RegistryKey object and corresponding last write time.
/// </summary>
/// <remarks>
/// .NET doesn't expose the last write time for a registry key 
/// in the RegistryKey class, so P/Invoke is required.
/// </remarks>
public class RegistryKeyEx
{
    #region P/Invoke Declarations
    // This declaration is intended to be used for the last write time only. int is used
    // instead of more convenient types so that dummy values of 0 reduce verbosity.
    [DllImport("advapi32.dll", EntryPoint = "RegQueryInfoKey", CallingConvention = CallingConvention.Winapi, SetLastError = true)]
    extern private static int RegQueryInfoKey(
        SafeRegistryHandle hkey,
        int lpClass,
        int lpcbClass,
        int lpReserved,
        int lpcSubKeys,
        int lpcbMaxSubKeyLen,
        int lpcbMaxClassLen,
        int lpcValues,
        int lpcbMaxValueNameLen,
        int lpcbMaxValueLen,
        int lpcbSecurityDescriptor,
        IntPtr lpftLastWriteTime);
    #endregion
    #region Public Poperties
    /// <summary>
    /// Gets the registry key owned by the info object.
    /// </summary>
    public RegistryKey Key { get; private set; }
    /// <summary>
    /// Gets the last write time for the corresponding registry key.
    /// </summary>
    public DateTime LastWriteTime { get; private set; }
    #endregion
    /// <summary>
    /// Creates and initializes a new RegistryKeyInfo object from the provided RegistryKey object.
    /// </summary>
    /// <param name="key">RegistryKey component providing a handle to the key.</param>
    public RegistryKeyEx(RegistryKey key)
    {
        Key = key;
        SetLastWriteTime();
    }
    /// <summary>
    /// Creates and initializes a new RegistryKeyInfo object from a registry key path string.
    /// </summary>
    /// <param name="parent">Parent key for the key being loaded.</param>
    /// <param name="keyName">Path to the registry key.</param>
    public RegistryKeyEx(RegistryKey parent, string keyName)
        : this(parent.OpenSubKey(keyName))
    { }
    /// <summary>
    /// Queries the currently set registry key through P/Invoke for the last write time.
    /// </summary>
    private void SetLastWriteTime()
    {
        Debug.Assert(Key != null, "RegistryKey component must be initialized");
        GCHandle pin = new GCHandle();
        long lastWriteTime = 0;
        try
        {
            pin = GCHandle.Alloc(lastWriteTime, GCHandleType.Pinned);
            if (RegQueryInfoKey(Key.Handle, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, pin.AddrOfPinnedObject()) == 0)
            {
                LastWriteTime = DateTime.FromFileTime((long)pin.Target);
            }
            else
            {
                LastWriteTime = DateTime.MinValue;
            }
        }
        finally
        {
            if (pin.IsAllocated)
            {
                pin.Free();
            }
        }
    }
}
"@

$type = Add-Type -TypeDefinition $code -Language CSharp

$devices = Get-Item HKLM:\SYSTEM\ControlSet001\Enum\USBSTOR\*

$result = foreach($device in $devices) {
    Write-Verbose -Verbose "New device: $($device.PSPath)"

    Write-Verbose -Verbose "GetClass"
    foreach($classname in $device.GetSubKeyNames()) {
        $class = $device.OpenSubKey($class)

        if($class -eq $null) { 
            Write-Verbose -Verbose "Class is null" 
            continue
        }

        Write-Verbose -Verbose "GetInstance"
        foreach($instancename in $class.GetSubKeyNames()) {
            $instance = $class.OpenSubKey($instancename)

            if($instance -eq $null) {
                Write-Verbose -Verbose "Instance is null"
                continue
            }

            Write-Verbose -Verbose "RegistryKeyEx"
            $keyEx = New-Object RegistryKeyEx $instance

            [pscustomobject]@{
                FriendlyName = $keyEx.key.GetValue('FriendlyName')
                DevicePath = $device.PSPath
                LastWriteTime = $keyEx.LastWriteTime
            }
        }
    }
}
VERBOSE: New device: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Enum\USBSTOR\Disk&Ven_Kingston&Prod_DataTraveler_G2&Rev_PMAP
VERBOSE: GetClass
VERBOSE: GetInstance
VERBOSE: RegistryKeyEx
VERBOSE: New device: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Enum\USBSTOR\Disk&Ven_WD&Prod_My_Passport_0730&Rev_1015
VERBOSE: GetClass
VERBOSE: Class is null
VERBOSE: New device: Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Enum\USBSTOR\Other&Ven_WD&Prod_SES_Device&Rev_1015
VERBOSE: GetClass
VERBOSE: GetInstance
VERBOSE: RegistryKeyEx
PS C:\> $result

FriendlyName                    DevicePath                                                                                                                           LastWriteTime      
------------                    ----------                                                                                                                           -------------      
Corsair Survivor 3.0 USB Device Microsoft.PowerShell.Core\Registry::HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Enum\USBSTOR\Disk&Ven_Corsair&Prod_Survivor_3.0&Rev_1.00 2017-11-05 21:08:25

PS C:\> get-date

November 11, 2017 17:02:09