powershell - 来自循环输出的神秘空白

powershell - mystery whitespace from output of loops

我在以下代码部分的输出中添加了空格。我需要以某种方式对其进行格式化,以便找出这个空格的来源,我只是输出变量。我什至添加了 .trim() 以确保它不是来自变量本身。这个空格到底是从哪里来的?

#sort by Name and sort Values of each
$output += foreach($icon in $table.GetEnumerator() | sort -Property Name) {
    $icon.Name.trim()
    foreach($type in $icon.Value | sort) {
        $fa_types[$type].trim()
    }
}

#Output to file
"version: " + $fa_version + "`r`nicons:`r`n" + $output | Out-File $output_file

示例输出文件:

version: 5.13.0
icons:
arrow-circle-right solid regular calendar-week regular users solid usb-drive solid file-alt regular key solid user-graduate solid comment-dots regular plus solid calendar-check regular spinner regular stopwatch regular file-search solid user-chart solid map-marker-alt regular calculator regular apple brands 

运行 Windows 10.

上的 powershell 版本 5

创建字符串的方式很奇怪...我推荐一种更安全的方式,其中不涉及 PowerShell 的输出函数:

#sort by Name and sort Values of each
$output = ""
foreach($icon in $table.GetEnumerator() | sort -Property Name) {
    $output += $icon.Name
    foreach($type in $icon.Value | sort) {
        $output += $fa_types[$type]
    }
}

#Output to file
"version: " + $fa_version + "`r`nicons:`r`n" + $output | Out-File $output_file

发生这种情况的原因是您在字符串中打印数组。当您遍历项目并仅打印 $fa_types[$type] 时,它会将其作为数组的项目写入 $output

如果你只打印 $output,你会看到多个项目分隔新行,但如果你把它放在一个字符串中,它由 space 分隔符表示。

示例:

$outp = foreach($var in (0..5)) { $var }
$outp

# shows the following output
# 0
# 1 
# 2
# 3
# 4
# 5

Write-Output "string  $outp  end"

# prints it in a single line
# string  0 1 2 3 4 5  end

您可以通过联接连接您的数组,因此不会在输出中打印 space。

"version: " + $fa_version + "`r`nicons:`r`n" + $output -join "" | Out-File $output_file
#or
"version: " + $fa_version + "`r`nicons:`r`n" + -join $output | Out-File $output_file