我正在尝试编写一个脚本来监控网址。我设法得到了我想要的信息,我的脚本看起来像这样
$logfile = "C:\LogFileTest.log"
Function WriteHeader-Websites {
[cmdletbinding()]
param (
[string]$URL
)
if ($logfile -eq "nologfile"){
write-host
write-host "$URL"
write-host
}
else {
add-content -path $logfile -value ""
add-content -path $logfile -value "$URL"
add-content -path $logfile -value ""
}
}
Function Test-Websites {
$URLs = Get-Content -Path C:\WebsiteChecks.txt
foreach ($URL in $URLs) {
$ArrayLine =$Line.split(",")
$
$Line.name =
try {
$request = [System.Net.WebRequest]::Create($URL)
$response = $request.GetResponse()
WriteHeader-Websites "$URL is available!"
} catch {
WriteHeader-Websites ("$URL failed! The error message was '{0}'." -f $_)
} finally {
if ($response) {
$response.Close()
Remove-Variable response
}
}
}
}
Test-Websites
我的文本文件如下所示:
http://www.google.com
http://www.bing.com
http://www.bbc.co.uk
脚本的输出如下所示:
http://www.google.com is available!
我希望能够在文本文件中为网站添加简短名称,因此它会使用该名称。
文本文件的一个例子是:
http://www.google.com,Google Website
http://www.bing.com,Bing Website
我希望回归看起来像:
Google Website is available!
Bing Website is available!
或
Google Website failed! Error message is...
但我不知道该怎么做,或者我甚至谷歌要找到它。有什么建议吗?
由于
答案 0 :(得分:0)
最简单的方法是使用标题创建一个csv,然后你可以使用它们的标题来引用列。
url,description
http://www.google.com,Google Website
http://www.bing.com,Bing Website
然后使用Import-Csv导入文件,这样您就可以执行以下操作:
Import-Csv -Path C:\WebsiteChecks.txt | % {
$_.description
$_.url
}
<强>更新强> 这是你的代码使用Import-Csv重写的通知我把描述放在它自己的变量中,因为$ _将由你的catch语句中的异常更新。
$logfile = "C:\LogFileTest.log"
Function WriteHeader-Websites {
[cmdletbinding()]
param (
[string]$URL
)
if ($logfile -eq "nologfile"){
write-host
write-host "$URL"
write-host
}
else {
add-content -path $logfile -value ""
add-content -path $logfile -value "$URL"
add-content -path $logfile -value ""
}
}
Function Test-Websites {
Import-Csv -Path C:\WebsiteChecks.txt | % {
$url = $_.url
$description = $_.description
try {
$request = [System.Net.WebRequest]::Create($url)
$response = $request.GetResponse()
WriteHeader-Websites "$description is available!"
} catch {
WriteHeader-Websites ("$description failed! The error message was '{0}'." -f $_)
} finally {
if ($response) {
$response.Close()
Remove-Variable response
}
}
}
}
Test-Websites