在 PowerShell 中獲取變數的字串長度
    
    Rohan Timalsina
    2023年1月30日
    
    PowerShell
    PowerShell String
    
- 
          
            使用 
GetType()檢查 PowerShell 中變數的資料型別 - 
          
            在 PowerShell 中使用 
$string.Length獲取變數的字串長度 - 
          
            在 PowerShell 中使用 
Measure-Object獲取變數的字串長度 
字串是 PowerShell 中最常用的資料型別之一;它包含字元或文字的序列。你可以使用單引號或雙引號定義字串。
PowerShell 字串具有 System.String 物件型別。本教程將教你在 PowerShell 中獲取變數的字串長度。
使用 GetType() 檢查 PowerShell 中變數的資料型別
我們建立了一個字串變數 $text,如下所示。
$text = "hello, how are you?"
你可以使用 GetType() 方法檢查變數的資料型別。
$text.GetType()
輸出:
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object
在 PowerShell 中使用 $string.Length 獲取變數的字串長度
$string.Length 是在 PowerShell 中檢查變數字串長度的最直接方法。
$text.Length
輸出:
19
你可以使用以下命令測試變數是否超過八個字元。
if ($text.Length -gt 8){
    Write-Output "True"
}
如果變數字串長度超過 8 個字元,則返回 True,否則不列印任何內容。
輸出:
True
除了 if 條件,你還可以使用三元運算子 ?:。三元運算子僅在 PowerShell 7.0 中可用。
($text.Length -gt 8) ? "True" : "False"
輸出:
True
-gt 是 PowerShell 中的比較運算子,表示大於。比較運算子用於比較 PowerShell 中的值和測試條件。
其他有用的比較運算子如下:
-eq: equals
-ne: not equals
-ge: greater than or equal
-lt: less than
-le: less than or equal
在 PowerShell 中使用 Measure-Object 獲取變數的字串長度
Measure-Object cmdlet 計算 PowerShell 中某些型別物件的數值屬性。它計算字串物件的單詞、行和字元的數量。
你可以使用以下命令獲取變數的字串長度。
$text | Measure-Object -Character
字元總數是字串的總長度。
輸出:
Lines Words Characters Property
----- ----- ---------- --------
                    19
你可以分別使用引數 -Line 和 -Word 檢查行數和單詞數。
        Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
    
作者: Rohan Timalsina
    
