Windows 插入USB驱动器时启动PowerShell脚本

Windows 插入USB驱动器时启动PowerShell脚本,windows,powershell,Windows,Powershell,是否有任何方法可以在USB驱动器插入PC时启动该驱动器上的PowerShell脚本?它必须将所有PDF文件从PC复制到USB驱动器,但这不是问题所在。我唯一不知道的是如何在插入USB驱动器后立即启动脚本 有人能帮忙吗?您可以使用Windows Management Instrumentation(WMI)事件来检测何时插入USB闪存驱动器。您可以使用Register-WmiEventcmdlet创建临时事件注册 假设您有一个名为c:\test\script.ps1的脚本文件。此脚本将用于在事件发

是否有任何方法可以在USB驱动器插入PC时启动该驱动器上的PowerShell脚本?它必须将所有PDF文件从PC复制到USB驱动器,但这不是问题所在。我唯一不知道的是如何在插入USB驱动器后立即启动脚本


有人能帮忙吗?

您可以使用Windows Management Instrumentation(WMI)事件来检测何时插入USB闪存驱动器。您可以使用
Register-WmiEvent
cmdlet创建临时事件注册

假设您有一个名为
c:\test\script.ps1
的脚本文件。此脚本将用于在事件发生时响应事件

Add-Content -Path $PSScriptRoot\test.txt -Value 'USB Flash Drive was inserted.';
然后,需要在单独的脚本中使用
register WmiEvent
cmdlet注册WMI事件。您至少需要指定
-Action
-Query
参数。事件发生时,将调用传递给
-Action
参数的PowerShell
ScriptBlock
-Query
参数包含用于轮询WMI事件的WMI事件查询。我在下面提供了一个样本

# Define a WMI event query, that looks for new instances of Win32_LogicalDisk where DriveType is "2"
# http://msdn.microsoft.com/en-us/library/aa394173(v=vs.85).aspx
$Query = "select * from __InstanceCreationEvent within 5 where TargetInstance ISA 'Win32_LogicalDisk' and TargetInstance.DriveType = 2";

# Define a PowerShell ScriptBlock that will be executed when an event occurs
$Action = { & C:\test\script.ps1;  };

# Create the event registration
Register-WmiEvent -Query $Query -Action $Action -SourceIdentifier USBFlashDrive;
由于您提到要在USB驱动器上启动PowerShell脚本文件,因此发生此事件时,您可以将
-操作
脚本块
更改为:

$Action = { & ('{0}\ufd.ps1' -f $event.SourceEventArgs.NewEvent.TargetInstance.Name);  };

上面的代码将在刚刚插入的USB驱动器的根目录上动态执行
ufd.ps1
脚本文件。

嗯,我无法测试这个,但我认为如果没有禁用,您可能可以使用windows的自动播放功能

那么,假设您在USB驱动器的根上有MyPowerShell.ps1。您将创建一个Autorun.ini文件,该文件将启动cmd,从而启动powershell脚本。您甚至可以绕过cmd,但正如我所说的,我现在无法测试

Autorun.ini将包括:

[autorun]
icon=yourIconFile.ico
open=autorun.cmd
Action=Click "OK" to copy PDF files!
那么您的Autorun.cmd将包含以下行

%Windir%\System32\WindowsPowerShell\v1.0\PowerShell.exe -exec bypass -noprofile -file MyPowerShell.ps1