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

时间:2014-02-15 23:33:53

标签: windows powershell

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

有人可以帮忙吗?

2 个答案:

答案 0 :(得分:10)

您可以使用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参数。发生事件时,将调用传递给ScriptBlock参数的PowerShell -Action-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 ScriptBlock更改为:< / p>

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

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

答案 1 :(得分:4)

好吧,我无法测试这个,但我认为你可以使用Windows的自动播放功能,如果它没有被禁用。

所以,假设您在USB驱动器的根目录上有MyPowerShell.ps1。您将创建一个可以启动cmd的Autorun.ini文件,该文件可以启动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