我可以讓這個 PowerShell 腳本接受逗號嗎?

我可以讓這個 PowerShell 腳本接受逗號嗎?

以下 powershell 腳本在有逗號時輸出結果兩次。它將字串分隔為兩個條目。我怎麼能讓它把它當作一個字串而不是兩個?

Function Get-Weather {
    [Alias('Wttr')]
    [Cmdletbinding()]
    Param(
            [Parameter(
                Mandatory = $true,
                HelpMessage = 'Enter name of the City to get weather report',
                ValueFromPipeline = $true,
                Position = 0
            )]
            [ValidateNotNullOrEmpty()]
            [string[]] $City,
            [switch] $Tomorrow,
            [switch] $DayAfterTomorrow
    )

    Process
    {
        Foreach($Item in $City){
            try {

                # Check Operating System Version
                If((Get-WmiObject win32_operatingsystem).caption -like "*Windows 10*") {
                    $Weather = $(Invoke-WebRequest "http://wttr.in/$City" -UserAgent curl -UseBasicParsing).content -split "`n"
                }
                else {
                    $Weather = (Invoke-WebRequest "http://wttr.in/$City" -UseBasicParsing).ParsedHtml.body.outerText  -split "`n"
                }

                If($Weather)
                {
                    $Weather[0..16]
                    If($Tomorrow){ $Weather[17..26] }
                    If($DayAfterTomorrow){ $Weather[27..36] }
                }
            }
            catch {
                $_.exception.Message
            }
        }            
    }

}

Get-Weather Shrewsbury,MA?n1

答案1

另請記住,當您使用單引號“單引號(單引號字串)時,該字串將與您鍵入的內容完全相同地傳遞到命令。不會執行任何替換。”與使用雙引號時的情況不同,“雙引號(雙引號字串)、前面帶有美元符號 ($) 的變數名稱將在字串傳遞到命令進行處理之前替換為變數的值。”

這是來自:https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_quoting_rules?view=powershell-6適用於 PowerShell 6,但相同的規則適用於 PowerShell 1 到 6。

因此,除非您需要在字串中使用變量,否則單引號將強制 PowerShell 按照您編寫的方式使用該字串。

相關內容