PowerShell Out file-导出到文件时,宽度不会截断内容

PowerShell Out file-导出到文件时,宽度不会截断内容,powershell,powershell-4.0,Powershell,Powershell 4.0,我有Windows 7和PowerShell 4.0。将内容导出到文件时,-Width参数不会根据给定的设置进行格式化。以下是我尝试做的一个示例: “这是一个阳光明媚的好天气”| Out File-FilePath“\output.txt”-编码ASCII-Width 10 导出的结果不会在第10个字符处截断。它根本不会被截断。我不知道出了什么问题。这让我有些惊讶,但显然,-Width参数只适用于格式化对象: 字符串作为输入,无效 ,这个有效 ,这是可行的,但方式很奇怪: 因此,我们能得到的最

我有Windows 7和PowerShell 4.0。将内容导出到文件时,
-Width
参数不会根据给定的设置进行格式化。以下是我尝试做的一个示例:

“这是一个阳光明媚的好天气”| Out File-FilePath“\output.txt”-编码ASCII-Width 10

导出的结果不会在第10个字符处截断。它根本不会被截断。我不知道出了什么问题。

这让我有些惊讶,但显然,
-Width
参数只适用于格式化对象:

字符串作为输入,无效 ,这个有效 ,这是可行的,但方式很奇怪: 因此,我们能得到的最接近的是
格式表-HideTableHeaders

PS D:\> New-Object psobject -Property @{text="It is a nice hot sunny day"} | Format-Table -HideTableHeaders|Out-File '.\output.txt' -Width 10 -Force; gc '.\output.txt'

It is a...

受@Matt答案的启发,您可以编写自己的函数来截断字符串:

Function Resize-String {
    Param(
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [string[]]$InputObject,
        [int]$Width = 10
    )

    process{
        $InputObject.Substring(0,[System.Math]::Min([string]$InputObject[0].Length,$Width))
    }
}

PS C:\> "It is a nice hot sunny day" |Resize-String|Out-File '.\output.txt' -Width 10 -Force; gc '.\output.txt'
It is a ni

不幸的是,文档对此不是很清楚,但似乎
-Width
仅适用于将某种类型的对象渲染到文本输出时,并且字符串不起作用

例如:

([PSCustomObject]@{Value=“这是一个阳光明媚的好天气”})输出文件-文件路径“\output.txt”-编码ASCII-宽度10

对于字符串,甚至是数组,它根本没有使用
-Width

我也对
-Width
参数感到困惑,因为我本以为您键入的内容会起作用。然而,如果它真的起作用,我不认为你会得到你期望的结果。如果你在TechNet上阅读,你会看到宽度

指定每行输出中的字符数。任何附加字符都将被截断

所以我有一个类似的答案,我使用字符串输入,并基于整数进行换行

函数被折叠{
Param(
[string[]]$Strings,
[int]$Wrap=50
)
$strings-join”“-split”(.{$wrap,}?[|$])“|其中对象{$\uz}
}
所以如果我们尝试你的文字

折叠“这是一个阳光明媚的好天气”-包装5
将呈现此输出,其优点是不会分解单词

It is 
a nice 
hot sunny 
day
现在可以很容易地将其传输到文件中。更多的解释来自

PS D:\> New-Object psobject -Property @{text="It is a nice hot sunny day"} | Format-Table -HideTableHeaders|Out-File '.\output.txt' -Width 10 -Force; gc '.\output.txt'

It is a...
Function Resize-String {
    Param(
        [Parameter(Mandatory=$true,ValueFromPipeline=$true)]
        [string[]]$InputObject,
        [int]$Width = 10
    )

    process{
        $InputObject.Substring(0,[System.Math]::Min([string]$InputObject[0].Length,$Width))
    }
}

PS C:\> "It is a nice hot sunny day" |Resize-String|Out-File '.\output.txt' -Width 10 -Force; gc '.\output.txt'
It is a ni
It is 
a nice 
hot sunny 
day