Function 尝试将函数转换为脚本

Function 尝试将函数转换为脚本,function,powershell,scripting,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')

我有一个函数,我正试图把它变成一个运行脚本

$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

我想你想要这样的东西:

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

你的剧本到底应该做什么?(显然,你想做字符串操作,但你能提供一个输入样本和基于它的预期输出吗?)哦,是的,那会很有帮助。对不起,我试图制作一个脚本,让你输入一个电影的标题,然后它只会以适当的大写字母返回,就像《乱世佳人》到《乱世佳人》。还添加了一个-AllCaps选项,使其成为所有caps。我认为您得到了
-包含向后比较的内容。应该是
$Collection-包含$Item
而不是其他方式,这不正确,我尝试了一点,但没有骰子。代码应该足够明显,但我在答案中添加了逻辑部分,以确保我们完全在同一页上。如果这个逻辑不是你想要的,那么问题是:你想要什么?)