插入 USB 驱动器时启动 PowerShell 脚本 [英] Start PowerShell script when USB drive is inserted
问题描述
USB 驱动器上的 PowerShell 脚本是否可以在驱动器插入 PC 的那一刻启动?它必须将所有 PDF 文件从 PC 复制到 USB 驱动器,但这不是问题.我唯一不知道的是如何在插入 U 盘后立即启动脚本.
Is there any way the PowerShell script located on a USB drive can be started the moment the drive is inserted in PC? It has to copy all PDF files from PC to the USB drive, but that's not the question. The only thing I don't know is how to start the script as soon as the USB drive is inserted.
有人可以帮忙吗?
推荐答案
您可以使用 Windows Management Instrumentation (WMI) 事件来检测 USB 闪存驱动器何时插入.您可以使用 Register-WmiEvent
cmdlet 创建临时事件注册.
You can use Windows Management Instrumentation (WMI) events to detect when a USB flash drive is inserted. You can create a temporary event registration using the Register-WmiEvent
cmdlet.
假设您有一个名为 c:\test\script.ps1
的脚本文件.此脚本将用于响应发生的事件.
Let's say that you have a script file called c:\test\script.ps1
. This script will be used to respond to events when they occur.
Add-Content -Path $PSScriptRoot\test.txt -Value 'USB Flash Drive was inserted.';
然后,您需要在单独的脚本中使用 Register-WmiEvent
cmdlet 注册 WMI 事件.您至少需要指定 -Action
和 -Query
参数.传递给 -Action
参数的 PowerShell ScriptBlock
将在事件发生时调用.-Query
参数包含将用于轮询 WMI 事件的 WMI 事件查询.我在下面提供了一个示例.
Then, you need to register for WMI events using the Register-WmiEvent
cmdlet in a separate script. You will need to specify the -Action
and -Query
parameters at a minimum. The PowerShell ScriptBlock
that is passed to the -Action
parameter will be invoked when an event occurs. The -Query
parameter contains the WMI event query that will be used to poll WMI for events. I have provided a sample below.
# 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;
既然你提到要启动一个 PowerShell 脚本文件在 U 盘上,当这个事件发生时,你可以改变 -Action
ScriptBlock
到这个:
Since you mentioned that you wanted to launch a PowerShell script file on the USB drive, when this event occurs, you can change the -Action
ScriptBlock
to this:
$Action = { & ('{0}\ufd.ps1' -f $event.SourceEventArgs.NewEvent.TargetInstance.Name); };
以上代码会动态执行刚刚插入的U盘根目录下的ufd.ps1
脚本文件.
The above code will dynamically execute the ufd.ps1
script file on the root of the USB drive that was just inserted.
这篇关于插入 USB 驱动器时启动 PowerShell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!