0

powershell 3.0を使用して結合を分割し、各単語の最初の文字を大文字にする必要があります

私はこれを理解しようとして夢中になっています。

どんな助けでも大歓迎です。

Function Proper( [switch]$AllCaps, [switch]$title, [string]$textentered=" ")
{ 
    if ($AllCaps)
        {$textentered.Toupper()}
    Elseif ($title)
        {$textentered -split " "

        $properwords = $textentered | foreach { $_ }


            $properwords -join " "
            $properwords.substring(0,1).toupper()+$properwords.substring(1).tolower()

            }
}
proper -title "test test"
4

1 に答える 1

2

System.Globalization.TextInfoクラスにはToTitleCase使用できるメソッドがあります。通常どおり単語を文字列に結合し ($lowerstringたとえば、呼び出します)、`Get-Culture コマンドレットを使用してその文字列のメソッドを呼び出します::

$titlecasestring = (Get-Culture).TextInfo.ToTitleCase($lowerstring)

文字列の連結には、次の形式を使用する傾向があります。

$lowerstring = ("the " + "quick " + "brown " + "fox")

ただし、以下も有効です。

$lowerstring = 'the','quick','brown','fox' -join " "

$lowerstring = $a,$b,$c,$d -join " "

編集:

提供したコードに基づいて、渡すものが文字列内の単なるフレーズである場合、文字列を分割/結合する必要はありません。したがって、次のものが必要です

Function Proper{
    Param ([Parameter(Mandatory=$true, Position=0)]
           [string]$textentered,
           [switch]$AllCaps,
           [switch]$Title)

    if ($AllCaps){$properwords = $textentered.Toupper()} 

    if ($title) {
                 $properwords = (Get-Culture).TextInfo.ToTitleCase($textentered)
                }

    if ((!($Title)) -and (!($AllCaps))){
        Return $textentered}
} 

Proper "test test" -AllCaps
Proper "test test" -Title
Proper "test test"

ブロックではParam ()、$textentered パラメーターを必須として設定し、最初のパラメーター (Position = 0) にする必要があります。

AllCaps パラメータも Title パラメータも渡されない場合、元の入力文字列が変更されずに返されます。

于 2013-07-23T02:33:30.137 に答える