2012-10-05 24 views
5

He leído varios métodos para convertir una matriz char en una cadena en PowerShell, pero ninguno de ellos parece funcionar con mi cadena. La fuente de mi cadena es:PowerShell convertir Char Array a la cadena

$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 

El WPageText resultante es una matriz de caracteres, así que no puedo usar Seleccione Cadena--pattern "días" -Context

He intentado:

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

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

Las únicas cosas que he tenido éxito con el hasta ahora es:

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

¿Alguna manera de hacer esto aparte de escribir y leer un archivo?

Respuesta

3

La forma más barata de hacerlo es modificando la variable $ofs y adjuntando la matriz en una cadena. $ofs es un separador de PS interno para imprimir matrices usando Object.ToString() de .NET.

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

Usted puede (debe) también utilizar el constructor System.String así:

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

++ para la información '$ OFS'; vale la pena recomendar _localizing_ el cambio '$ OFS', por ejemplo .:' & {$ OFS = ''; "$ c"} '. Tenga en cuenta que, aunque el valor predeterminado de _effective_ es un espacio único, _variable_ '$ OFS' está predeterminado _not defined_. No estoy seguro de lo que está recomendando con respecto al constructor de cadenas; '$ result = $ a' hace lo mismo mucho más simple y más eficientemente. – mklement0

0

Sea cual sea su busca, creo que le pasa algo en relación con $WPageText. si echas un vistazo, es un PSCustomObject dentro del cual estás interesado en outerText que es una cadena.

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= ... 

Así

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

Usted puede utilizar el operador -join (con piezas adicionales para probar tipos de datos):

$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 

Alternativamente, la unión también se puede escribir como:

$x -join "" 

Ambos son legales; -join sin un LHS solo combina la matriz en su RHS. El segundo formato se une al LHS usando el RHS como delimitador. Ver help about_Join para más.

+0

+1, pero no veo ninguna necesidad de convertir explícitamente $ x a una matriz de caracteres. Un mucho más simple "-join $ x" funciona bien para mí. –

+0

Podría ser una resaca de las versiones anteriores de Powershell; sinceramente, no lo sé; Acabo de ver este método aconsejado en algún lugar hace algún tiempo. –