如何写出长度取决于用户输入长度的字符串?

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

我正在编写一个有很多输出的脚本,并且可以使用多个计算机名称。输出宣布计算机名称,然后是有关该特定计算机的大量信息。我想在上面和下面有一系列 #s,它在每个信息部分之前宣布计算机名称,但想看看我是否可以让 #s 的数量与提供的计算机名称。例如:

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

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

我宁愿不必为每种可能的情况都使用 if else,例如

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

等等。如果必须的话,我会的,它只是其中的十个左右。或者我可以只使用一定数量的 #s,它们肯定至少会覆盖计算机名称可能的最大长度。

您一定会喜欢 PowerShell 的这个功能。你可以 "multiply" 一个字符串。

试试这个:

$sep = '@'

Write-Output ($sep*5)

$names = "Hello World", "me too", "goodbye"

$names | % {
Write-Output ($sep*($_.Length))
Write-Output $_
Write-Output ($sep*($_.Length))
}

输出

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

你可以做到这一点

$NbChar=5


#method 1 (best)
'@' * $NbChar

#method 2
New-Object  System.String "@", $NbChar

#method 3
-join (1..$NbChar | %{"@"})

#method 4
"".PadLeft($NbChar, '@')

我建议将 的建议包含在自定义函数中,以便您可以轻松地格式化任何给定名称:

function Format-ComputerName([string]$ComputerName) {
  $separator = '#' * $ComputerName.Length
  '{0}{1}{2}{1}{0}' -f $separator, [Environment]::NewLine, $ComputerName
}

或 fixed-width 横幅:

"{0}`r`n# {1,-76} #`r`n{0}" -f ('#' * 80), $compname;

例如:

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

您还可以添加日期、时间等:

"{0}`r`n# {1:G} : {2,-54} #`r`n{0}" -f ('#' * 80), (Get-Date), $compname;

例如:

################################################################################
# 04/02/2017 16:42:07 : LONGERCOMPNAME                                         #
################################################################################

有关字符串格式的详细信息here