首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >powershell -循环输出中的神秘空格

powershell -循环输出中的神秘空格
EN

Stack Overflow用户
提问于 2020-06-12 23:55:16
回答 2查看 106关注 0票数 0

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

代码语言:javascript
运行
复制
#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

输出文件示例:

代码语言:javascript
运行
复制
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。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-06-13 00:04:21

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

代码语言:javascript
运行
复制
#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
票数 1
EN

Stack Overflow用户

发布于 2020-06-13 00:32:05

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

如果您只打印$output,您将看到多个项目分隔成新行,但是如果您将其放在一个字符串中,它将由一个空格分隔符表示。

示例:

代码语言:javascript
运行
复制
$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

您可以通过连接连接数组,这样输出中就不会打印空格。

代码语言:javascript
运行
复制
"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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62347957

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档