将驱动器插入PC后,有什么方法可以启动USB驱动器上的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
参数。发生事件时,将调用ScriptBlock
传递给该-Action
参数的PowerShell 。该-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
为:
$Action = { & ('{0}\ufd.ps1' -f $event.SourceEventArgs.NewEvent.TargetInstance.Name); };
上面的代码将ufd.ps1
在刚插入的USB驱动器的根目录上动态执行脚本文件。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句