使用PowerShell测试应用程序链接

时间:2013-09-24 10:39:57

标签: powershell web

我正在使用powershell进行一些监控,我想检查一个应用程序的jnlp 存在于网站上,可供下载。 我有.jnlp的链接,到目前为止,我正在使用.navigate()下载文件。

$ie = new-object -com "InternetExplorer.Application"
Try { 
    $ie.navigate("http://bla.com/testApp.jnlp")
} Catch {
    #$_
    $ErrorMessage = $_.Exception.Message
}

我尝试通过提供无效的文件名来捕获异常,但它不起作用。 此外,我想到下载应用程序,然后尝试删除该文件,以便 检查它确实存在但是因为我有很多jnlps要检查它会太慢。

还有另一种更简单优雅的方法吗?我想避免下载 我要测试的每个文件。

2 个答案:

答案 0 :(得分:4)

如何使用.Net中的WebClient类?获取数据非常简单。像这样,

$webclient = new-object System.Net.WebClient
try {
    # Download data as string and store the result into $data
    $data = $webclient.DownloadString("http://www.google.com/")
} catch [Net.WebException] {
    # A 404 or some other error occured, process the exception here
    $ex = $_
    $ex.Exception
}

答案 1 :(得分:2)

如果您使用的是PowerShell 3.0或更高版本,则可以使用Invoke-WebRequest通过发出HTTP HEAD请求并检查状态代码来查看页面是否存在。

$Result = Invoke-WebRequest -uri `http://bla.com/testApp.jnlp` -method head
if ($Result.StatusCode -ne 200){
    # Something other than "OK" was returned.
}

这也适用于System.Net.WebClient,但需要更多的努力。