试图将功能转换为脚本

时间:2015-07-27 22:47:01

标签: function powershell scripting

我有一个功能,我试图变成一个正在运行的脚本。

$string = New-Object.CustomTitleCase
$InputString = $String

{ $string = read-host -prompt "Please give me a title to Correct."
    if ($String -contains 
        'are','to','a','the','at','in','of','with','and','but','or') 
        ( $InputString -split " " |ForEach-Object {
        if ($_ -notin $NoCapitalization) {
            "$([char]::ToUpper($_[0]))$($_.Substring(1))"
            if $string -contains "-AllCaps "string".ToUpper()
        } else { $_ }
    }) -join " "
}
Pause

1 个答案:

答案 0 :(得分:0)

我想你想要这样的东西:

function Format-Title {
    param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$InputString,
        [Parameter(Mandatory=$false)]
        [Switch]$AllCaps
    )

    $NoCapitalization = @('are', 'to', 'a', 'the', 'at', 'in', 'of', 'with', `
                          'and', 'but', 'or')

    $Words = $String -split ' '
    for ($i = 0; $i -lt $Words.Count; $i++) {
        if ( ($i -eq 0) `
         -or ($AllCaps) `
         -or ($NoCapitalization -notcontains $Words[$i]) ) {
            $FirstLetter = $Words[$i].Substring(0,1)
            $Words[$i] = $FirstLetter.ToUpper() + $Words[$i].Substring(1)
        }
    }

    return $Words -join ' '
}

逻辑:

  • 始终将第一个字词大写
  • 如果指定了-AllCaps开关,则将所有字词大写
  • 否则跳过$ NoCapitalization集合中包含的字词

示例:

Format-Title -InputString "gone with the wind" -AllCaps

输出:

Gone With The Wind