我正在尝试在插入Doxie Go扫描仪时自动执行复制和重命名功能。要检测何时将设备连接到我的机器,我使用以下脚本:https://superuser.com/questions/219401/starting-scheduled-task-by-detecting-connection-of-usb-device
#Requires -version 2.0
Register-WmiEvent -Class win32_VolumeChangeEvent -SourceIdentifier volumeChange
Write-Host (Get-Date -format s) " Beginning script..."
do
{
$newEvent = Wait-Event -SourceIdentifier volumeChange
$eventType = $newEvent.SourceEventArgs.NewEvent.EventType
$eventTypeName = switch($eventType)
{
1 {"Configuration changed"}
2 {"Device arrival"}
3 {"Device removal"}
4 {"docking"}
}
Write-Host (Get-Date -format s) " Event detected = " $eventTypeName
if ($eventType -eq 2)
{
$driveLetter = $newEvent.SourceEventArgs.NewEvent.DriveName
$driveLabel = ([WMI]"Win32_LogicalDisk='$driveLetter'").VolumeName
Write-Host (Get-Date -format s) " Drive name = " $driveLetter
Write-Host (Get-Date -format s) " Drive label = " $driveLabel
# Execute process if drive matches specified condition(s)
if ($driveLabel -eq 'DOXIE')
{
Write-Host (Get-Date -format s) " Starting task in 3 seconds..."
Start-Sleep -seconds 3
Start-Process -FilePath "D:\My Archives\Automation\PowerShell\Batch Move and Rename for Google Cloud.ps1"
}
}
Remove-Event -SourceIdentifier volumeChange
}
while (1-eq1) #Loop until next event
Unregister-Event -SourceIdentifier volumeChange
这是按预期工作的。我遇到的问题是这行代码:
Start-Process -FilePath "D:\My Archives\Automation\PowerShell\Batch Move and Rename for Google Cloud.ps1"
运行此行时,PowerShell窗口会暂时打开,然后立即关闭。我知道脚本需要的时间比运行时长,特别是当扫描仪上有数百个文档时。另外,被调用的脚本运行正常。
我使用的是PowerShell v5.1.14393.693的Windows 10。任何帮助表示赞赏。谢谢!
答案 0 :(得分:2)
控制台可能在退出前显示错误。通常的怀疑是您的执行策略不允许脚本执行等,您可以绕过powershell.exe -ExecutionPolicy Bypass
(除非策略由GPO设置)。
尝试使用-NoExit
启动它以使控制台保持打开状态,以便查看是否存在错误。
Start-Process -FilePath powershell -ArgumentList "-NoExit", "-File", "D:\My Archives\Automation\PowerShell\Batch Move and Rename for Google Cloud.ps1"
此外,在将脚本作为新进程启动时,应始终指定powershell
作为进程。 1}}默认情况下在文件名(或双击)调用时在记事本中打开。