2012-10-05 57 views
5

我已經閱讀了將字符數組轉換爲PowerShell中的字符串的各種方法,但是它們都沒有處理我的字符串。 我的字符串的來源是:PowerShell將字符串轉換爲字符串

$ComputerName = "6WMPSN1" 
$WarrantyURL = "http://www.dell.com/support/troubleshooting/au/en/aulca1/TroubleShooting/ProductSelected/ServiceTag/$ComputerName" 
$WarrantyPage = Invoke-WebRequest -Uri $WarrantyURL 
$WPageText = $WarrantyPage.AllElements | Where-Object {$_.id -eq "TopContainer"} | Select-Object outerText 

產生的WPageText是一個字符數組,所以我不能使用選擇串-pattern「天」 -Context

我已經試過:

$WPageText -join 
[string]::Join("", ($WPageText)) 

http://softwaresalariman.blogspot.com.au/2007/12/powershell-string-and-char-sort-and.html

唯一的事情,我已經成功與迄今:

$TempFile = New-Item -ItemType File -Path $env:Temp -Name $(Get-Random) 
$WPageText | Out-File -Path $TempFile 
$String = Get-Content -Path $TempFile 

除了寫入和讀取文件之外,還有什麼辦法可以做到這一點?

回答

3

這樣做的便宜的方法是修改$ofs變量並將數組括在一個字符串中。 $ofs是使用.NET的Object.ToString()打印陣列的內部PS分離器。

$a = "really cool string" 
$c = $a.ToCharArray() 
$ofs = '' # clear the separator; it is ' ' by default 
"$c" 

你可以(應該)也使用System.String構造是這樣的:

$a = "another mind blowing string" 
$result = New-Object System.String ($a,0,$a.Length) 
+0

++爲$ OFS信息;值得推薦_localizing_'$ OFS'的變化,例如:'&{$ OFS =''; 「$ c」}'。請注意,即使_effective_默認爲單個空格,默認情況下,_variable_「$ OFS」是_not defined_。不確定你在推薦關於字符串構造函數的東西; '$ result = $ a'做同樣的事情更加簡單和高效。 – mklement0

0

無論您正在尋找的,我認爲你錯過關於$WPageText東西。如果你看看它是一個PSCustomObject,其中你對outerText感興趣,它是一個字符串。

PS C:\PowerShell> $WPageText | Get-Member 

    TypeName: Selected.System.Management.Automation.PSCustomObject 

Name  MemberType Definition                       ----  ---------- ----------            
Equals  Method  bool Equals(System.Object obj)                                
GetHashCode Method  int GetHashCode()                                    
GetType  Method  type GetType()                                    
ToString Method  string ToString()                                    
outerText NoteProperty System.String outerText= ... 

所以

PS C:\PowerShell> $WPageText.outerText 

Precision M6500 
Service Tag: 6WMPSN1 

Select A Different Product > 
Warranty Information 
Warranty information for this product is not available. 
7

可以使用-join運算符(帶有多餘的部分,以證明數據類型):

$x = "Hello World".ToCharArray(); 
$x.GetType().FullName   # returns System.Char[] 
$x.Length      # 11 as that's the length of the array 
$s = -join $x     # Join all elements of the array 
$s       # Return "Hello World" 
$s.GetType().FullName   # returns System.String 

另外,連接也可以寫爲:

$x -join "" 

兩者都是合法的;沒有LHS的-join只是在其RHS上合併陣列。第二種格式使用RHS作爲分隔符連接LHS。有關更多信息,請參閱help about_Join

+0

+1,但我沒有看到任何需要顯式將$ x轉換爲char數組。一個簡單得多的「-join $ x」對我來說工作得很好。 –

+0

這可能是早期版本的Powershell的宿醉 - 我真的不知道;我剛看到這種方法在某個時候回到某個地方。 –