2011-10-11 3 views
102

Come posso convertire un oggetto array in stringa?Come si converte un oggetto array in una stringa in PowerShell?

ho provato:

$a = "This", "Is", "a", "cat" 
[system.String]::Join(" ", $a) 

senza fortuna. Quali sono le diverse possibilità in PowerShell?

+3

Vedere la mia risposta, ma il codice funziona bene, anche. Perché dici "senza fortuna"? –

+3

Scusa, sì, sembra funzionare, penso di aver incasinato qualcosa quando ho provato questo. – jrara

risposta

190
$a = 'This', 'Is', 'a', 'cat' 

Uso virgolette (e facoltativamente utilizzare il separatore $ofs)

# This Is a cat 
"$a" 

# This-Is-a-cat 
$ofs = '-' # after this all casts work this way until $ofs changes! 
"$a" 

Uso operatore join

# This-Is-a-cat 
$a -join '-' 

# ThisIsacat 
-join $a 

Utilizzo conversione [string]

# This Is a cat 
[string]$a 

# This-Is-a-cat 
$ofs = '-' 
[string]$a 
+5

Per il non inizializzato (come me) '$ ofs' è documentato [qui] (http: // stackoverflow.com/documentation/powershell/5353/automatic-variables/19045/ofs) – Liam

+3

La documentazione StackOverflow è stata chiusa, quindi il collegamento di Liam è morto. Ecco un'altra spiegazione di $ OFS, Output Field Separator: https://blogs.msdn.microsoft.com/powershell/2006/07/15/psmdtagfaq-what-is-ofs/ –

2

è possibile specificare il tipo di simile:

[string[]] $a = "This", "Is", "a", "cat" 

Controllo del tipo:

$a.GetType() 

conferma:

 
    IsPublic IsSerial Name          BaseType 
    -------- -------- ----          -------- 
    True  True  String[]         System.Array 

Output $ a:

 
PS C:\> $a 
This 
Is 
a 
cat 
26

Ho scoperto che il piping della matrice per il cmdlet out-string funziona correttamente.

Ad esempio:

PS C:\> $a | out-string 

This 
Is 
a 
cat 

dipende dal vostro obiettivo finale su quale metodo è il migliore da utilizzare.

+3

FYI: solo facendo '$ a' sarebbe ha lo stesso effetto di $ a | out-string' – JohnLBevan

+7

@JohnLBevan Non sempre. '($ a | out-string) .getType()' = String. '$ a.getType()' = Oggetto []. Se stai usando $ a come argomento per un metodo che prevede una stringa (come ad esempio 'invoke-expression'), quindi' $ a | out-string' ha un chiaro vantaggio. – rojo

5

da un tubo

# This Is a cat 
'This', 'Is', 'a', 'cat' | & {"$input"} 

# This-Is-a-cat 
'This', 'Is', 'a', 'cat' | & {$ofs='-';"$input"} 

Write-Host

# This Is a cat 
Write-Host 'This', 'Is', 'a', 'cat' 

# This-Is-a-cat 
Write-Host -Separator '-' 'This', 'Is', 'a', 'cat' 

Example

11
1> $a = "This", "Is", "a", "cat" 

2> [system.String]::Join(" ", $a) 

Linea due esegue l'operazione e le uscite per ospitare, ma non modifica $ un :

3> $a = [system.String]::Join(" ", $a) 

4> $a 

Questo è un gatto

5> $a.Count 

1 
0
$a = "This", "Is", "a", "cat" 

foreach ($word in $a) { $sent = "$sent $word" } 
$sent = $sent.Substring(1) 

Write-Host $sent