请原谅我的无知 - 我正在尝试编写一个powershell cmdlet,它接受用户输入并构建查询uri到API(一个强制性,3个选项) - 我有一般的想法,我需要使用哈希表的字典查询字符串和参数.
我正在努力建立 $baseurl + $querystring + '=' + $parameter + '&' + $querystring + '=' $value (if not null)
例如 https://example.com/api?param1=value¶m2=value
到目前为止 - 这是非常粗糙的,完全不起作用:
Function Get-commonURI{ #takes 4 params from user
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[String[]]$value1
[Parameter(Mandatory=$false,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[String[]]$value2,
[String[]]$value3,
[String[]]$value4
) #end param
}
#put the input into a paramter hash table with the query strings
$Parameters = @{
query = 'querysting1', 'querystring2', 'querystring3', 'querystring4'
values = $value1,$value2.$value2, $value4
}
uri = https://example.com/api?
$HttpValueCollection = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
foreach ($Item in $Parameters.GetEnumerator()) {
#I want to append each query passed in on the cli
foreach ($Value in $Item.Value) {
$ParameterName = $Item.value
$HttpValueCollection.Add($ParameterName, $Value)}
$Request = [System.UriBuilder]($Uri)
$Request.Query = $HttpValueCollection.ToString()
invoke-webrequest $Request.Uri
}
Run Code Online (Sandbox Code Playgroud)
我有类似的东西写但是它不起作用 - 我甚至在这里正确的轨道? - 我确定这已经完成了一百万次,但甚至不知道谷歌的内容 - 有些事情告诉我,我不应该用变量设置哈希表.谢谢你的期待.
Sim*_*lin 12
我总是喜欢不重新发明轮子:
$ub = new-object System.UriBuilder -argumentlist 'http', 'myhost.com', 80, 'mypath/query.aspx', '?param=value'
$ub.Uri.AbsoluteUri
>>>> http://myhost.com/mypath/query.aspx?param=value
Run Code Online (Sandbox Code Playgroud)
更新:
这是一个内置的.NET类,它有许多构造函数.上面的一个接受协议,主机,端口号,路径和查询字符串.它似乎处理一个空的或空的查询字符串,所以不需要自己处理.有关信息,可以在此处查看类的构造函数.为了从用户检索输入,您可以使用Read-Host,例如:
[String] $Local:strServer = '';
[String] $Local:strPath = '';
[String] $Local:strQuery = '';
[String] $Local:strUri = '';
while ( $strServer -eq '' ) {
$strServer = Read-Host -Prompt 'Please enter a server name';
} #while
while ( $strPath -eq '' ) {
$strPath = Read-Host -Prompt 'Please enter a path';
} #while
# Get query string and ensure it begins with a "?".
$strQuery = Read-Host -Prompt 'Please enter a query string';
if ( ($strQuery -ne '') -and (! $strQuery.StartsWith('?')) ) { $strQuery = '?' + $strQuery; }
try {
$strUri = [System.UriBuilder]::new( 'http', $strServer, 80, $strPath, $strQuery );
Write-Host -Object ( 'URI is {0}' -f $strUri );
} #try
catch [System.ArgumentException] {
# Something went wrong.
} #catch
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4490 次 |
| 最近记录: |