PowerShell将Char Array转换为字符串

Jes*_*ris 7 powershell-3.0

我已经阅读了在PowerShell中将char数组转换为字符串的各种方法,但它们似乎都不适用于我的字符串.我的字符串的来源是:

$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
Run Code Online (Sandbox Code Playgroud)

生成的WPageText是一个Char数组,所以我不能使用Select-String -Pattern"days"-Context

我试过了:

$WPageText -join
[string]::Join("", ($WPageText))
Run Code Online (Sandbox Code Playgroud)

根据 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
Run Code Online (Sandbox Code Playgroud)

除了编写和读取文件之外,还有什么方法可以做到这一点?

Chr*_*s J 9

您可以使用-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
Run Code Online (Sandbox Code Playgroud)

或者,连接也可以写成:

$x -join ""
Run Code Online (Sandbox Code Playgroud)

两者都是合法的; -join没有LHS只是在其RHS上合并阵列.第二种格式使用RHS作为分隔符加入LHS.有关更多信息,请参阅about_Join帮助.


mhu*_*mhu 6

将 char 数组转换为字符串的最快方法:

[String]::new($WPageText)
Run Code Online (Sandbox Code Playgroud)


Car*_*nez 5

这样做的廉价方法是修改$ofs变量并将数组包含在字符串中。$ofs是一个内部 PS 分隔符,用于使用Object.ToString().NET打印数组。

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

您还可以(应该)System.String像这样使用构造函数:

$a = "another mind blowing string"
$result = New-Object System.String ($a,0,$a.Length)
Run Code Online (Sandbox Code Playgroud)