我正在使用 PowersHell 来自动化 iTunes,但发现错误处理/等待 com 对象处理不是最佳的。
示例代码
#Cause an RPC error
$iTunes = New-Object -ComObject iTunes.Application
$LibrarySource = $iTunes.LibrarySource
# Get "playlist" objects for main sections
foreach ($PList in $LibrarySource.Playlists)
{
if($Plist.name -eq "Library") {
$Library = $Plist
}
}
do {
write-host -ForegroundColor Green "Running a loop"
foreach ($Track in $Library.Tracks)
{
foreach ($FoundTrack in $Library.search("$Track.name", 5)) {
# do nothing... we don't care...
write-host "." -nonewline
}
}
} while(1)
#END
进入iTunes并做一些让它弹出消息的事情 - 在我的情况下,我进入Party Shuffle并且我得到一个横幅“Party shuffle automatic blah blah ....”和“不要显示”消息。
此时如果运行脚本会重复执行此操作:
+ foreach ($FoundTrack in $Library.search( <<<< "$Track.name", 5)) {
Exception calling "Search" with "2" argument(s): "The message filter indicated
that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVER
CALL_RETRYLATER))"
At C:\Documents and Settings\Me\My Documents\example.ps1:17 char:45
+ foreach ($FoundTrack in $Library.search( <<<< "$Track.name", 5)) {
Exception calling "Search" with "2" argument(s): "The message filter indicated
that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVER
CALL_RETRYLATER))"
At C:\Documents and Settings\Me\My Documents\example.ps1:17 char:45
如果您等到出现对话框后才运行示例,那么您将重复得到:
Running a loop
You cannot call a method on a null-valued expression.
At C:\Documents and Settings\Me\example.ps1:17 char:45
+ foreach ($FoundTrack in $Library.search( <<<< "$Track.name", 5)) {
那是因为 $Library 句柄无效。
如果我的示例正在做一些重要的事情——比如转换曲目然后删除旧的,不正确处理错误可能对 iTunes 中的曲目是致命的。我想强化代码,以便它处理 iTunes 繁忙,并且会静默重试,直到成功。有什么建议么?