powershell 突出显示找到的空白 space

powershell highlight the blank space found

我有以下脚本,它通过逐行

在 csv 文件中找到空白 space
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Retain blank space."

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

$n = @()

$f = Get-Content C:\MyPath\*.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}
        1 {$n+=$item -replace ' '}
    }


} else {
    $n+=$item -replace ' '
}

}

$n | Set-Content  C:\MyPath\*.csv

问题是:当找到 space 时,我怎样才能突出显示它在一条线上的位置或在那里涂上颜色,任何可以简化查找过程的方法?

编辑:不想更改文件或文本,这应该只显示在 PowerShell 的控制台或 window 弹出窗口中伊势.

注释中描述的方法的基本代码示例使用 Read-Host 进行用户输入并使用 write-host 更改背景颜色如下所示:

$str= "test abc1 abc2 test3"

$index = $str.IndexOf(" ")
while ($index -gt -1) {
  write-host $str.Substring(0,$index) -NoNewline
  write-host "_" -foreground "magenta" -NoNewline
  $str = $str.Substring( $index + 1, $str.length -  $index - 1);
  $index = $str.IndexOf(" ")
}
write-host $str.Substring( $index + 1, $str.length -  $index - 1);
$confirmation = Read-Host "Do you want to keep the blank on this line?"
if ($confirmation -eq 'y') {
  #do action
}

编辑:包含多个空格的代码

初始代码 Post:

$n = @()

$f = Get-Content C:\MyPath\*.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)

    $str = $item
    $index = $str.IndexOf(" ")
    while ($index -gt -1) {
      write-host $str.Substring(0,$index) -NoNewline
      write-host "_" -foreground "magenta" -NoNewline
      $str = $str.Substring( $index + 1, $str.length -  $index - 1);
      $index = $str.IndexOf(" ")
    }
    write-host $str.Substring( $index + 1, $str.length -  $index - 1);
    $confirmation = Read-Host "Do you want to keep the blank on this line?"
    if (($confirmation -eq 'y') -or ($confirmation -eq 'Y')) {
      $n+=$item
    }
    else {
      $n+=$item -replace ' '
    }
} else {
    $n+=$item -replace ' '
}

}

$n | Set-Content  C:\MyPath\*.csv