Powershell 如何写出长度取决于用户的字符串';s条目';长度是多少?
我正在编写一个脚本,它有很多输出,可以使用多个计算机名。输出将公布计算机名称,然后公布有关该特定计算机的大量信息。我想在上面和下面有一系列的Powershell 如何写出长度取决于用户的字符串';s条目';长度是多少?,powershell,if-statement,count,write-host,Powershell,If Statement,Count,Write Host,我正在编写一个脚本,它有很多输出,可以使用多个计算机名。输出将公布计算机名称,然后公布有关该特定计算机的大量信息。我想在上面和下面有一系列的s,在每个信息部分之前都会宣布计算机名,但我想看看是否可以使#s的数量与提供的计算机名的长度相同。例如: ######## COMPNAME ######## 等等。如果必须的话,我会的,大概只有十个。或者我可以只使用一些#来至少覆盖计算机名的最大长度。你会喜欢PowerShell的这个功能的。你可以“乘”一个字符串 试试这个: $sep = '@' Wr
s,在每个信息部分之前都会宣布计算机名,但我想看看是否可以使#s的数量与提供的计算机名的长度相同。例如:
########
COMPNAME
########
等等。如果必须的话,我会的,大概只有十个。或者我可以只使用一些
#
来至少覆盖计算机名的最大长度。你会喜欢PowerShell的这个功能的。你可以“乘”一个字符串
试试这个:
$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
@@@@@@@
你会喜欢PowerShell的这个功能的。你可以“乘”一个字符串 试试这个:
$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, '@')
你可以这样做
$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
}
我建议在自定义函数中包装的建议,这样您就可以轻松地格式化任何给定名称:
function Format-ComputerName([string]$ComputerName) {
$separator = '#' * $ComputerName.Length
'{0}{1}{2}{1}{0}' -f $separator, [Environment]::NewLine, $ComputerName
}
或固定宽度的横幅:
"{0}`r`n# {1,-76} #`r`n{0}" -f ('#' * 80), $compname;
e、 g:
您还可以添加日期、时间等:
"{0}`r`n# {1:G} : {2,-54} #`r`n{0}" -f ('#' * 80), (Get-Date), $compname;
e、 g:
有关字符串格式或固定宽度横幅的详细信息:
"{0}`r`n# {1,-76} #`r`n{0}" -f ('#' * 80), $compname;
e、 g:
您还可以添加日期、时间等:
"{0}`r`n# {1:G} : {2,-54} #`r`n{0}" -f ('#' * 80), (Get-Date), $compname;
e、 g:
有关字符串格式的详细信息谢谢你,Kory!这正是我想要的。关于我想使用的格式,我改变了一些想法,但这完美地回答了我的问题。谢谢你,Kory!这正是我想要的。关于我想要使用的格式,我改变了一些想法,但这完美地回答了我的问题。