简体   繁体   中英

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. 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. If you want to edit the CSV row content, use this instead.

$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. (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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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