Xaml Powershell中的变量,包括新行字符
我对PowerShell还比较陌生,但我已经创建了一个XAML表单来对我们的环境进行一些健康检查。在第一部分中,我创建了一个if语句来检查设备的连接状态。从Xaml Powershell中的变量,包括新行字符,xaml,powershell,Xaml,Powershell,我对PowerShell还比较陌生,但我已经创建了一个XAML表单来对我们的环境进行一些健康检查。在第一部分中,我创建了一个if语句来检查设备的连接状态。从文本框中提取设备名称,然后,如果该设备已连接,它将继续运行状况检查。但是,当项目从文本框中提取时,它包含了行的“`n”,因此查询失败。这是相关代码 Remove-Item C:\Healthlog.txt #This is where the problem is happening $Computers = $CompNames.T
文本框中提取设备名称,然后,如果该设备已连接,它将继续运行状况检查。但是,当项目从文本框中提取时,它包含了行的“`n”,因此查询失败。这是相关代码
Remove-Item C:\Healthlog.txt
#This is where the problem is happening
$Computers = $CompNames.Text.Split("`n")
Foreach ($Comp in $Computers){
$log= "C:\Healthlog.txt"
Add-Content $log "$Comp"
#Check to see if machines are connected
Write-Host "$TestConnection = Test-Connection -ComputerName $Comp - Quiet"
$TestConnection = Test-Connection -ComputerName $Comp -Quiet
Write-Host $TestConnection
If ($TestConnection -eq $False) {
Add-Content $log "Connection to Device has failed"
}
$Compnames
是分配给文本框的变量的名称
每次输出都是失败的查询,因为变量中包含新行字符。我尝试过在$Comp
以及$Computers
上执行-replace
,但我不确定是否正确
任何帮助都将不胜感激。您确定这只是一个新行值弄乱了吗?您是否也尝试过更换结转退货
$Computers = $CompNames.Text.Split("`n")
Foreach ($Comp in $Computers)
{
$newComp = $Comp.Replace("`n", "").Replace("`r", "")
$log= "C:\Healthlog.txt"
Add-Content $log "$newComp"
#Check to see if machines are connected
Write-Host "$TestConnection = Test-Connection -ComputerName $newComp - Quiet"
$TestConnection = Test-Connection -ComputerName $newComp -Quiet
Write-Host $TestConnection
If ($TestConnection -eq $False) {
Add-Content $log "Connection to Device has failed"
}
你确定这仅仅是一个新行值弄乱了吗?您是否也尝试过更换结转退货
$Computers = $CompNames.Text.Split("`n")
Foreach ($Comp in $Computers)
{
$newComp = $Comp.Replace("`n", "").Replace("`r", "")
$log= "C:\Healthlog.txt"
Add-Content $log "$newComp"
#Check to see if machines are connected
Write-Host "$TestConnection = Test-Connection -ComputerName $newComp - Quiet"
$TestConnection = Test-Connection -ComputerName $newComp -Quiet
Write-Host $TestConnection
If ($TestConnection -eq $False) {
Add-Content $log "Connection to Device has failed"
}
请注意此命令的输出:
("1`n2`n").Split("`r`n").Count
输出为3
,因为第三行为空。您可以通过忽略空条目(我认为这是您想要的)来解决此问题:
请注意此命令的输出:
("1`n2`n").Split("`r`n").Count
输出为3
,因为第三行为空。您可以通过忽略空条目(我认为这是您想要的)来解决此问题:
基于这里的两个注释,我得到了代码的功能。空条目和回车都有问题。最终的代码是这样的
$Computers = $CompNames.text.split("`n", [StringSplitOptions]::RemoveEmptyEntries) | % { $_.replace("`r", "") }
基于这里的两个注释,我得到了代码的功能。空条目和回车都有问题。最终的代码是这样的
$Computers = $CompNames.text.split("`n", [StringSplitOptions]::RemoveEmptyEntries) | % { $_.replace("`r", "") }
Shorter只是$CompNames.text.split(`r`n',[StringSplitOptions]::removeMptyEntries)
。更新了我的答案,加入了`r
。效果很好。谢谢Shorter只是$CompNames.text.split(`r`n',[StringSplitOptions]::removeMptyEntries)
。更新了我的答案,加入了`r
。效果很好。谢谢