powershell突出显示找到的空白区域

时间:2016-01-07 13:43:13

标签: powershell powershell-v3.0 highlight

我有以下脚本,它通过逐行扫描在csv文件中找到一个空格

$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

问题是:当找到空间时,我如何突出显示它在线上的位置或在那里放置颜色,哪些东西可以简化找到它的过程?

编辑:不想更改文件或文本,只应在PowerShell控制台或ISE窗口弹出窗口中显示。

1 个答案:

答案 0 :(得分:1)

使用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
}

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

初始帖子代码:

$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