tri*_*leq 7 windows powershell
驱动器插入PC后,是否可以启动USB驱动器上的PowerShell脚本?它必须将所有PDF文件从PC复制到USB驱动器,但这不是问题.我唯一不知道的是如何在插入USB驱动器后立即启动脚本.
有人可以帮忙吗?
Tre*_*van 10
您可以使用Windows Management Instrumentation(WMI)事件来检测何时插入USB闪存驱动器.您可以使用Register-WmiEventcmdlet 创建临时事件注册.
假设您有一个名为的脚本文件c:\test\script.ps1.此脚本将用于在事件发生时对其进行响应.
Add-Content -Path $PSScriptRoot\test.txt -Value 'USB Flash Drive was inserted.';
Run Code Online (Sandbox Code Playgroud)
然后,您需要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;
Run Code Online (Sandbox Code Playgroud)
由于您提到要在USB驱动器上启动PowerShell脚本文件,因此发生此事件时,您可以将其更改-Action ScriptBlock为:
$Action = { & ('{0}\ufd.ps1' -f $event.SourceEventArgs.NewEvent.TargetInstance.Name); };
Run Code Online (Sandbox Code Playgroud)
上面的代码将动态执行ufd.ps1刚插入的USB驱动器根目录下的脚本文件.
好吧,我无法对此进行测试,但我认为如果未禁用该功能,您可能可以使用 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!
Run Code Online (Sandbox Code Playgroud)
然后您的 Autorun.cmd 将包含以下行
%Windir%\System32\WindowsPowerShell\v1.0\PowerShell.exe -exec bypass -noprofile -file MyPowerShell.ps1
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12226 次 |
| 最近记录: |