-1

我希望验证 URL 类似于可以使用 Test-Path 对文件系统和注册表路径执行的操作。

但是,当然,Test-Path不适用于 URL,而且我一直无法在 PowerShell 中找到执行此操作的方法。

我可以使用Invoke-WebRequest,但据我所知,没有验证,如果找到它,我可以获得返回码 200,如果没有,我可以获得 404。

唯一的例外是无效的主机名,例如host,com,这让我想知道:

  • 除了无效的主机名之外,是否存在无效 URL 之类的东西?

  • 或者,一旦正确定义了端口和主机,它基本上是 URL 路径中有效的任何字符吗?

4

2 回答 2

0

vonPryziRon提供了关键指针:

您可以使用该System.Uri.IsWellFormedUriString方法测试 URI(URL)是否格式正确,即形式上有效(无论域是否存在、是否可达、路径是否存在……)。

要另外确保给定的 URI 仅限于特定的 URI方案,例如http://and https://,您可以执行以下操作:

$uri = 'https://example.org/foo?a=b&c=d%20e'

[uri]::IsWellFormedUriString($uri, 'Absolute') -and ([uri] $uri).Scheme -in 'http', 'https'

请注意,给定的 URI 必须已经包含转义形式的保留字符 才能被视为格式正确;例如,空格必须编码为%20,如上例所示,该System.Uri.EscapeDataString方法可以对 URI 的组成(非句法)部分执行此操作(例如[uri]::EscapeDataString('a b')

于 2021-08-28T19:53:01.687 回答
0

我认为你可以用不同的方式来解决这个问题。

  1. 使用正则表达式检查 URL 格式是否正确
  2. 解析那个 url 后面的 IP 地址,这会让你知道那个地址后面是否有东西。

检查下面的示例:

#1 URL format validation

#input the URL here
$urlInput = 'www.google.com'

#This is the regex pattern you can use to validate the format - reference : https://www.regextester.com/94502
$regEx="^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$"

if($urlInput -match $regEx){
    Write-Host "$urlInput is a Valid URL!"

    #2 is there a server behind this url
    try{
        Resolve-DnsName -Name $urlInput -ErrorAction Stop
    }catch{
        if($_ -like '*DNS name does not exist*'){
            Write-Host "No DNS record for the following URL : $urlInput"
        }else{
            Write-Output $_
        }
    }
}
else{
    Write-Host "Invalide URL - $urlInput "
}

PS 我使用了以下表达式 - https://www.regextester.com/94502,您可以使用它来匹配您的用例。

于 2021-08-26T08:57:06.777 回答