Search code examples
powershellif-statementcountwrite-host

How do I write out a string whose length is dependent upon a user's entry's length?


I'm writing a script that has a lot of output, and can take multiple computer names. The output announces the computer name, then a lot of info about that particular computer. I want to have a series of #s above and below where it announces the computer name before each section of info, but would like to see if I can have the amount of #s be the same as the length of the provided computer name(s). For example:

########
COMPNAME
########

or

##############
LONGERCOMPNAME
##############

I'd rather not have to have an if else for every possible case, such as

if ($compname.length -eq "8") {
  Write-Host "########"
  Write-Host "$compname"
  Write-Host "########"
} elseif ($compname -eq "9") {
  Write-Host "#########"
  Write-Host "$compname"
  Write-Host "#########"

and so on. If I have to, I will, it'd just be ten of those or so. Or I could just use some amount of #s that will always definitely cover at least the max length a computer name might be.


Solution

  • You're gonna love this feature of PowerShell. You can "multiply" a string.

    Try this:

    $sep = '@'
    
    Write-Output ($sep*5)
    
    $names = "Hello World", "me too", "goodbye"
    
    $names | % {
    Write-Output ($sep*($_.Length))
    Write-Output $_
    Write-Output ($sep*($_.Length))
    }
    

    OUTPUT

    @@@@@
    @@@@@@@@@@@
    Hello World
    @@@@@@@@@@@
    @@@@@@
    me too
    @@@@@@
    @@@@@@@
    goodbye
    @@@@@@@