构建URL字符串

时间:2015-01-13 15:43:23

标签: string url powershell

尝试使用变量和字符串构建链接,但我总是在它们之间留一个空格。我该如何解决这个问题?

$sub是来自sharepoint的SPWeb对象。

Write-Host $sub.Url "/default.aspx"

结果:

https://intra.mycompany/pages/sales /default.aspx

2 个答案:

答案 0 :(得分:3)

$sub变量放在字符串文字中,以便将其视为一个字符串:

Write-Host "$($sub.Url)/default.aspx"

请注意,由于您要访问$sub属性,因此需要使用sub expression operator $(...)


另一种方法,取决于字符串的复杂程度,是使用-f format operator

Write-Host ("{0}/default.aspx" -f $sub.Url)

如果您需要插入许多变量,则可以使代码更清晰,更易于阅读。

答案 1 :(得分:0)

使用URL类'构造函数进行连接,而不是使用字符串操作。这将具有额外的优势,即自动处理附加所需的任何斜杠。

function Join-Uri {
    [CmdletBinding()]
    param (
        [Alias('Path','BaseUri')] #aliases so naming is consistent with Join-Path and .Net's constructor
        [Parameter(Mandatory)]
        [System.Uri]$Uri
        ,
        [Alias('ChildPath')] #alias so naming is consistent with Join-Path
        [Parameter(Mandatory,ValueFromPipeline)]
        [string]$RelativeUri
    )
    process {
        (New-Object -TypeName 'System.Uri' -ArgumentList $Uri,$RelativeUri)
        #the above returns a URI object; if we only want the string:
        #(New-Object -TypeName 'System.Uri' -ArgumentList $Uri,$RelativeUri).AbsoluteUri
    }
}

$sub = new-object -TypeName PSObject -Property @{Url='http://demo'}

write-host 'Basic Demo' -ForegroundColor 'cyan'
write-host (Join-Uri $sub.Url '/default.aspx')
write-host (Join-Uri $sub.Url 'default.aspx') #NB: above we included the leading slash; here we don't; yet the output's consistent

#you can also easily do this en-masse; e.g.
write-host 'Extended Demo' -ForegroundColor 'cyan'
@('default.aspx','index.htm','helloWorld.aspx') | Join-Uri $sub.Url | select-object -ExpandProperty AbsoluteUri

上面我创建了一个包含此功能的函数;但你可以轻松地做下面的事情:

[string]$url = (new-object -TypeName 'System.Uri' -ArgumentList ([System.Uri]'http://test'),'me').AbsoluteUri

相关文档的链接:https://msdn.microsoft.com/en-us/library/9hst1w91(v=vs.110).aspx