Get-Content
可能比Import-Csv
一個更好的辦法,因爲這將讓你檢查一整行以查找空格,而不必檢查每個單獨的字段。對於全自動化處理你只使用Where-Object
濾波器從輸出中刪除不匹配的行:
Get-Content 'C:\CrPowershell\test\input.csv' |
Where-Object { $_ -notlike '* *' } |
Set-Content 'C:\CrPowershell\test\output.csv'
不過,既然你想提示輸入包含空格的每根線,你需要一個ForEach-Object
(或similiar構建體)和一個嵌套條件,是這樣的:
Get-Content 'C:\CrPowershell\test\input.csv' | ForEach-Object {
if ($_ -notlike '* *') { $_ }
} | Set-Content 'C:\CrPowershell\test\output.csv'
以提示用戶進行輸入的最簡單方法是Read-Host
:
$answer = Read-Host -Prompt 'Message'
if ($answer -eq 'y') {
# do one thing
} else {
# do another
}
在您的特定情況下,你可能做這樣的事情對於任何匹配線路:
$anwser = Read-Host "$_`nKeep the line? [y/n] "
if ($answer -ne 'n') { $_ }
以上檢查如果答案是不n
盡遣行有意識的決定。
以提示用戶輸入其它方式choice.exe
(其中有允許超時和默認回答的額外優勢):
choice.exe /c YN /d N /t 10 /m "$_`nKeep the line"
if ($LastExitCode -ne 2) { $_ }
或host UI:
$title = $_
$message = 'Keep the line?'
$yes = New-Object Management.Automation.Host.ChoiceDescription '&Yes'
$no = New-Object Management.Automation.Host.ChoiceDescription '&No'
$options = [Management.Automation.Host.ChoiceDescription[]]($yes, $no)
$answer = $Host.UI.PromptForChoice($title, $message, $options, 1)
if ($answer -ne 1) { $_ }
我留下它作爲練習,將您選擇的任何提示程序與代碼的其餘部分集成在一起。
你的問題到底是什麼?如何提示用戶輸入?如何替換空白字符?或者如何逐行處理文件?這是三個不同的問題,你不應該混淆它們。 –
如何逐行替換空白字符並等待每行的用戶輸入。對不起,如果我混合起來,但即使我問3個不同的問題,不會解決我的問題。我需要所有3合一 – CM2K
@ CM2K你想刪除整行還是隻替換空白字符 – Paul