使用Powershell下载未知文件名

时间:2011-06-30 15:22:38

标签: .net file-io webclient

我正在尝试设置PowerShell脚本来获取加密密钥。该公司将其发布在一个网站上,并希望我们每6个月手动获取一次,但是,我很懒散,健忘。所以我写了一个脚本为我做这个,我计划每3个月左右运行一次。以下是我到目前为止的情况:

$url ="http://www.theirwebsite.com/pgp/corp07272011Public.asc"
$client = new-object System.Net.WebClient
$proxy = New-Object System.Net.WebProxy("http://OurProxy:80")
$proxy.UseDefaultCredentials = $true
$client.proxy = $proxy
$client.DownloadFile( $url, ".\CorpPublicKey.asc" )

这适用于他们当前的密钥。 但是,我正在下载的文件使用日期作为其名称的一部分。 2011年7月27日到来时,大概是新密钥将在2011年1月27日之后命名,或类似的东西。

所以这可能是一个简单的.NET问题,但我如何找到网站上的文件?或者有更好的方法来解决这个问题吗?

编辑:好的,我没有提到的一个小问题是这个文件链接到一个已知的网站上。 Soooo ......从理论上讲,我可以解析链接的网页,并使用它来查找文件名。如果我把它全部整理出来,我会发布代码。

编辑,部分Deux
所以我想出了这一个。
1)您不能简单地在网络服务器上列出文件。这就是网站管理员发布文件树的原因。或者,您可以通过蜘蛛爬过网站上的所有链接。
2)知道网站上总会有链接到我的目标,我获取网页,找到链接/文件名,然后可以下载文件。
3)执行此操作的正确方法是将其解析为xml,然后使用Xpath或其他内容搜索锚标记以查找我的链接。
4)但这很烦人所以我只是为.asc文件重新编写并调用它。

$url ="http://www.theirwebsite.com/pgp/"
$client = new-object System.Net.WebClient
$proxy = New-Object System.Net.WebProxy("http://ourproxy:80")
$proxy.UseDefaultCredentials = $true
$client.proxy = $proxy
$webstring = $client.DownloadString( $url) 
$webstring -match "aspecifcname.*asc"
$matches[0]
$url ="http://www.theircompany.com/pgp/" + $matches[0]
"url: " + $url
#Huh, we need to use the full path for downloading this file. .\ didn't cut it
$client.DownloadFile( $url, "C:\Program Files (x86)\theirCompany\savedKey.asc" )

1 个答案:

答案 0 :(得分:0)

回答这里没有悬而未决的问题。

所以我想出了这个。 1)您不能简单地在网络服务器上列出文件。这就是网站管理员发布文件树的原因。或者,您可以通过蜘蛛爬过网站上的所有链接。 2)知道网站上总会有链接到我的目标,我获取网页,找到链接/文件名,然后可以下载文件。 3)执行此操作的正确方法是将其解析为xml,然后使用Xpath或其他内容搜索锚标记以查找我的链接。 4)但这很烦人,所以我只是为.asc文件重新编写并调用它。

$url ="http://www.theirwebsite.com/pgp/"
$client = new-object System.Net.WebClient
$proxy = New-Object System.Net.WebProxy("http://ourproxy:80")
$proxy.UseDefaultCredentials = $true
$client.proxy = $proxy
$webstring = $client.DownloadString( $url) 
$webstring -match "aspecifcname.*asc"
$matches[0]
$url ="http://www.theircompany.com/pgp/" + $matches[0]
"url: " + $url
#Huh, we need to use the full path for downloading this file. .\ didn't cut it
$client.DownloadFile( $url, "C:\Program Files (x86)\theirCompany\savedKey.asc" )