简体   繁体   English

Powershell子串设置特定的单元格长度

[英]Powershell Substring Setting Specific Cell Length

Been working on trying to Trim/Delete a data in Specific Row (Results)in CSV file to a specific length. 一直在努力试图修剪/删除在CSV文件的具体行(结果)数据到特定的长度。 Keep getting an "Overload for Substring". 不断收到“子字符串超载”。 Any ideas? 有任何想法吗?

$Csv = Import-Csv $FileIn
$CsvNew = ForEach($Row in $Csv){
$Row.Results.Substring((0,[System.Math]::Min(254,$Row.Results.Length)))}

Looks like a simple mistake in your Substring usage. 看起来像你的子字符串使用一个简单的错误。 Remove one of the parenthesis. 删除括号中的一个。

From : 来自:

$Row.Results.Substring((0,[System.Math]::Min(254,$Row.Results.Length)))}

To : 至 :

$Row.Results.Substring(0,[System.Math]::Min(254,$Row.Results.Length))}

For the sake of readability, you could have put your substring count into a variable. 对于可读性的原因,你可能已经把你的子数到一个变量。 The error would have appeared even more obvious. 该错误会出现更加明显。

$Csv = Import-Csv $FileIn
$CsvNew = ForEach($Row in $Csv)
{
    $MaxLength = [System.Math]::Min(254,$Row.Results.Length)
    $Row.Results.Substring(0,$MaxLength )
}

Edit: 编辑:

Finally, please note that $CsvNew (that I took from your example) store nothing. 最后,请注意$ CsvNew(我从您的示例中获取)不存储任何内容。 If you want to edit the CSV row content, use this instead. 如果你要编辑的CSV行内容,使用它代替。

$Csv = Import-Csv $FileIn
$Csv | ForEach-Object {
    $MaxLength = [System.Math]::Min(254,$_.Results.Length)
    $_.Results.Substring(0,$MaxLength )
}

This last snippet will actually edit $Csv variable content to trim your results column to a maximum of 254 characters. 最后一个代码段实际上将编辑$ Csv变量内容,以将您的结果列修剪为最多254个字符。 (It won't be exported to the file though. For that, you will need to export the new $Csv content using the ExportTo-CSV Cmdlet ). (尽管它不会导出到文件中。为此,您将需要使用ExportTo-CSV Cmdlet导出新的$ Csv内容)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM