I've read various methods for converting a char array to a string in PowerShell, but none of them seem to work with my string. The source of my string is:
$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
The resulting WPageText is an Char Array so I can't use Select-String -Pattern "days" -Context
I've tried:
$WPageText -join
[string]::Join("", ($WPageText))
as per http://softwaresalariman.blogspot.com.au/2007/12/powershell-string-and-char-sort-and.html
The only things I have been successful with so far is:
$TempFile = New-Item -ItemType File -Path $env:Temp -Name $(Get-Random)
$WPageText | Out-File -Path $TempFile
$String = Get-Content -Path $TempFile
Any way to do this aside from writing and reading a file?
The Out-String cmdlet converts input objects into strings. By default, Out-String accumulates the strings and returns them as a single string, but you can use the Stream parameter to direct Out-String to return one line at a time or create an array of strings.
Split() function. The . Split() function splits the input string into the multiple substrings based on the delimiters, and it returns the array, and the array contains each element of the input string. By default, the function splits the string based on the whitespace characters like space, tabs, and line-breaks.
Use one of the following patterns to split more than one string: Use the binary split operator (<string[]> -split <delimiter>) Enclose all the strings in parentheses. Store the strings in a variable then submit the variable to the split operator.
PowerShell uses the Split () function to split a string into multiple substrings. The function uses the specified delimiters to split the string into sub strings. The default character used to split the string is the whitespace.
You can use the -join
operator (with extra parts to prove datatypes):
$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
Alternatively, the join can also be written as:
$x -join ""
Both are legal; -join
without an LHS just merges the array on its RHS. The second format joins the LHS using the RHS as the delimiter. See help about_Join for more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With