2014-11-04 83 views
0

我使用Powershell来完成一些高级别的自动操作,并且想通过一个网站上的下拉列表中的2个数值循环......不知道如何如何实现它。Powershell - 为循环访问数组提供建议

下面的代码:

 $Array = "FirstItem", "SecondItem" 

     Foreach ($i in $Array) 

     { 
    while($ie.busy) {sleep 1} 
      $doc = $ie.document 
      $ie.document.getElementById("DropDownListBtn").click() 
      $link = $ie.Document.getElementsByTagName('A') | where-object {$_.innerText -eq '$i'} 
     # Note: without using the variable above, I would expect the statement would look like this: 
       # $link = $ie.Document.getElementsByTagName('A') | where-object {$_.innerText -eq 'FirstItem'} 
      $link.click() 
     } 

这里的错误:

You cannot call a method on a null-valued expression. 
At line:9 char:28 

+     $link.click <<<<() 

    + CategoryInfo   : InvalidOperation: (click:String) [], RuntimeException 

    + FullyQualifiedErrorId : InvokeMethodOnNull 
+0

这里您的实际问题是什么?代码是否会产生意想不到的结果?你有错误吗? – 2014-11-04 19:40:37

+0

对不起...是的,我得到一个错误:你不能调用一个空值表达式的方法。 在行:9字符:28 + $ link.click <<<<() + CategoryInfo:InvalidOperation:(点击:字符串)[],RuntimeException的 + FullyQualifiedErrorId:InvokeMethodOnNull 不能调用方法上的空高估的表达。 在行:9字符:28 + $ link.click <<<<() + CategoryInfo:InvalidOperation:(点击:字符串)[],RuntimeException的 + FullyQualifiedErrorId:InvokeMethodOnNull – user4068021 2014-11-04 19:42:34

+0

请编辑您的问题,并添加错误信息那里。正如你所看到的,它在评论中变得不可读。 – 2014-11-04 19:43:30

回答

0

你需要一些错误处理/检查。

我想通过添加错误处理到$ ie和$连接实例代码,例如启动:

$ie = <code to create object> -erroraction silentlycontinue; 
if ($?) { 
    # All ok - proceed 
} else { 
    # it failed 
} 

...或者,使用的try ... catch,但是这并不总是工作因为并非所有的PowerShell调用都会引发异常。

try { 
    $ie = <code to create object> -erroraction silentlycontinue; 
    } 
catch [Exception] { 
    # it failed 
    } 
+0

-erroraction参数只能在cmdlet上使用,而不是在像对象方法调用那样的对象方法调用上使用 – Paul 2014-11-04 19:58:26

0

谢谢大家。我进一步排除故障,并意识到我需要删除$ i周围的单引号:

$link = $ie.Document.getElementsByTagName('A') | where-object {$_.innerText -eq $i}