有没有办法在U盘插入PC时启动U盘上的PowerShell脚本?它必须将所有PDF文件从PC复制到USB驱动器,但这不是问题所在。我唯一不知道的是如何在插入USB驱动器后立即启动脚本。
有人能帮上忙吗?
发布于 2014-02-16 10:14:05
您可以使用Windows Management Instrumentation (WMI)事件来检测何时插入USB闪存驱动器。可以使用Register-WmiEvent
cmdlet创建临时事件注册。
假设您有一个名为c:\test\script.ps1
的脚本文件。此脚本将用于在事件发生时对其进行响应。
Add-Content -Path $PSScriptRoot\test.txt -Value 'USB Flash Drive was inserted.';
然后,您需要在单独的脚本中使用WMI注册Register-WmiEvent
事件。您至少需要指定-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;
由于您提到要在U盘上启动PowerShell脚本文件,因此当发生此事件时,您可以将-Action
ScriptBlock
更改为:
$Action = { & ('{0}\ufd.ps1' -f $event.SourceEventArgs.NewEvent.TargetInstance.Name); };
上面的代码将动态执行刚刚插入的U盘根目录下的ufd.ps1
脚本文件。
发布于 2014-02-16 10:15:48
好吧,我不能测试这个,但我认为你可以使用windows的AutoPlay功能,如果它没有被禁用的话。
所以,假设你在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
https://stackoverflow.com/questions/21805166
复制相似问题