none
How do I concatenate a variable with a string text? RRS feed

  • Question

  • I have a script that tests urls. If it comes across one that is not a valid url, I want to print out to the console a message that looks like this.... 

    Http://myDomian/myPath: This is not a valid url

    I currently have the url in a variable and this is what my attempted code looks like, so far.

    Write-Host -ForegroundColor Red $url "This url is not valid."

    but this is just giving me an output that looks like "This url is not valid", without displaying the url that it finds to be invalid. How to I get it to display the url that it finds not valid plus the text? Please help

    Tuesday, April 8, 2014 4:15 PM

Answers

  • Thank you so much for your response Mike Laughlin. I tried that and it didn't work for me, but I eventually ended up doing this...

    Write-Host "This url is not valid:" $url -ForegroundColor Red
    When I tried putting the variable within the quotes, it only printed the whole message out along with the variable and not its value. Well I learnt something new, and thanks for the help again.
    • Marked as answer by Spawn10 Monday, April 14, 2014 8:37 PM
    Tuesday, April 8, 2014 10:23 PM

All replies

  • Hi,

    Just enclose everything in double quotes:

    $url = 'Http://myDomian/myPath'
    
    Write-Host "$url : This URL is not valid" -ForegroundColor Red

    Using double quotes allows PowerShell to expand the variable.


    Don't retire TechNet! - (Don't give up yet - 12,830+ strong and growing)

    • Proposed as answer by tommymaynard Tuesday, April 8, 2014 4:40 PM
    Tuesday, April 8, 2014 4:20 PM
  • This is a case where reading the  help would have taught you many things as well as saved a  lot of typing.

    ¯\_(ツ)_/¯

    Tuesday, April 8, 2014 10:18 PM
  • Thank you so much for your response Mike Laughlin. I tried that and it didn't work for me, but I eventually ended up doing this...

    Write-Host "This url is not valid:" $url -ForegroundColor Red
    When I tried putting the variable within the quotes, it only printed the whole message out along with the variable and not its value. Well I learnt something new, and thanks for the help again.
    • Marked as answer by Spawn10 Monday, April 14, 2014 8:37 PM
    Tuesday, April 8, 2014 10:23 PM
  • You are not following instructions because you have not read the help:

    You wrote this which is a syntax violation

    Write-Host -ForegroundColor Red$url "This url is not valid."

    EXAMPLE: Write-Host <message> <switched>

    $url='http://www.google.com"
    Write-Host " This url is this url $url" -Fore red

    DO NOT CHANGE THE ORDER OF THINGS.

    Test the exact code as posted until you understand how it works then go back and fix your original code.

    Before posting back type: HELP Write-Host -FULL

    Read everything very carefully.


    ¯\_(ツ)_/¯


    • Edited by jrv Tuesday, April 8, 2014 10:44 PM
    Tuesday, April 8, 2014 10:43 PM