2017-01-16 112 views
1

我试图在插入我的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的窗口打开的一瞬间当第二然后立即关闭。我知道该脚本需要比运行时间更长的时间,特别是当扫描仪上有数百个文档时。另外,被调用的脚本工作正常。

我在Windows 10使用PowerShell v5.1.14393.693。任何帮助表示赞赏。谢谢!

回答

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的过程。 ps1默认情况下,在通过文件名(或双击)调用时在记事本中打开。

+0

谢谢你的帮助!我可以使它工作周围使用脚本名周围的论据单引号和双引号: 开始处理-FilePath PowerShell的-ArgumentList“ExecutionPolicy绕道”,“ - 文件“d:\我的档案\自动化\ PowerShell的\批量移动并重命名Google Cloud.ps1“' – Tchotchke

相关问题