簡體   English   中英

存儲在PowerShell中的變量中的字符串出現意外行為

[英]Unexpected behavior with a string stored in a variable in PowerShell

我從Excel的Cells.Find()方法中得到了一些奇怪的行為:

我正在搜索的變量:

PS > $volumename
vol_01       

PS > $volumename.GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                                                            
-------- -------- ----                                     --------                                                                                                                                            
True     True     String                                   System.Object 

沒有結果:

PS > $sheet.Cells.Find($volumename).Row

但是如果我手動復制並粘貼該變量的值:

PS > $volumename = "vol_01"
PS > $volumename.GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                                                            
-------- -------- ----                                     --------                                                                                                                                            
True     True     String                                   System.Object 

獲得我期望的值:

PS > $sheet.Cells.Find($volumename).Row
198

在我看來,它們似乎是完全相同的類型。 並非在所有情況下都如此。 一些卷名可以很好地通過,而另一些則不能。 我確實清除了該帖子的卷名,因為它具有客戶命名約定。 它與上述格式相同,並且與有效的卷名相同。

以下代碼段可用於檢查字符串中是否包含隱藏的控制字符

PS> & { [int[]] [char[]] $Args[0] | % { '0x{0:x} [{1}]' -f $_, [char] $_ } } "vol_01`n"
0x76 [v]
0x6f [o]
0x6c [l]
0x5f [_]
0x30 [0]
0x31 [1]
0xa [
]

第一列是每個字符的Unicode代碼點(“ ASCII代碼”),第二列是字符本身,用[...]括起來

請注意,我在字符串的末尾添加了"`n" -一個換行符( U+000A -其代碼點表示為十六進制。 數字是0xa

如果像您這樣,字符串中唯一不需要的部分是尾隨空格 ,則可以按以下方式刪除它們:

$volumename.TrimEnd() # trim trailing whitespace

在您的情況下,尾隨空格為0xa0 ,即NO-BREAK SPACE( U+00A0 ,正如Tom Blodget指出的那樣, .TrimEnd()也將其刪除。


基於上述的簡單函數包裝器 ,用於管道輸入:

filter debug-Chars { [int[]] [char[]] $_ | % { '0x{0:x} [{1}]' -f $_, [char] $_ } }

樣品使用:

"vol_01`n" | debug-Chars

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM