使用用户输入逐行删除空白

时间:2016-01-05 08:53:26

标签: csv powershell powershell-v3.0

昨天我问this question。现在我想做一个小改动几乎相同的练习:如果一行上有空白字符(在CSV中逐行),请询问用户是否应删除空白字符;不同的是,只有空白而不是整行。

适用于我之前问题的代码是:

$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Retain line."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Delete line."

$n = @()

$f = Get-Content .\test.csv
foreach ($item in $f) {
    if($item -like "* *"){
        $res = $host.ui.PromptForChoice("Title", "want to keep this line? `n $item", [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no), 0)
        switch ($res) {
            0 {$n+=$item}
            1 {}
        }
    } else {
        $n+=$item
    }
}

$n | Set-Content .\test.csv

我认为我应该使用的是Trim()功能来实现这一目标。 所以,我认为我应该在if子句中进行修改,如下所示(对于我可能会做的愚蠢的语法错误,请注意):

$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Retain blank."
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "Delete blank."

$n = @()

$f = Get-Content .\test.csv
foreach ($item in $f) {
    if ($item -like "* *") {
        $res = $host.ui.PromptForChoice("Title", "want to keep the blank on this line? `n $item", [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no), 0)
        switch ($res) {
            0 {$n+=$item.Trim()}
            1 {}
        }
    } else {
        $n+=$item.Trim()
    }
}

$n | Set-Content .\test.csv

这样可以运行,但是仍然会检测到这条线,所以如果我首先修剪它并不重要,我需要修复它以便保留或修剪但不会丢弃。

修改

像这样调整switch ($res)不起作用:

    switch ($res) {
        0 {$n+=$item.Trim()}
        1 {$n+=$item}
    }
} else {
    $n+=$item.Trim()
}

1 个答案:

答案 0 :(得分:1)

不带参数的

Trim()会从字符串的开头和结尾删除所有空格(而不仅仅是空格)。您不能使用它来删除字符串中任何其他位置的空格。而是使用-replace operator

$_ -replace ' '

请注意,这次您需要输出未修改的字符串,不仅要求它不包含空格,而且如果用户选择保留现有空格。

相关问题