2

Trying to build a link with a variable and a string, but I always get a space in between them. How can I fix this?

The $sub is a SPWeb object from sharepoint.

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

result:

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

2 Answers 2

3

Put the $sub variable inside the string literal so that it is treated as one string:

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

Note that you will need to use a sub expression operator $(...) since you are accessing an attribute of $sub.


Another approach, depending on how complicated your string is, is to use the -f format operator:

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

If you have many variables that you need to insert, it can make for cleaner and easier to read code.

Sign up to request clarification or add additional context in comments.

1 Comment

Apologize for my deplorable spelling and grammar.
1

Use the URL class' constructor to do the join, rather than using string manipulation. This will have the additional advantage of automatically take care of appending any slashes required.

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

Above I created a function to wrap up this functionality; but you could just as easily do something such as below:

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

Link to related documentation: https://msdn.microsoft.com/en-us/library/9hst1w91(v=vs.110).aspx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.