我有一个 powershell 脚本,它从 json 文件中获取客户列表,然后根据到目前为止输入的内容打印它。 但是,即使“列表”块位于“userInput header”之后,它也会显示前面的列表,为什么?
json 示例:
[
{
"id": 123,
"name": "Example LTDA",
"database": "SqlServer"
},
{
"id": 321,
"name": "ECOMMERCE SA",
"database": "Oracle"
}
]
脚本:
$customersJson = Get-Content "%jsonpath%\customers.json" | ConvertFrom-Json | ForEach-Object { $_.name }
while ($true) {
#Clear-Host
[console]::CursorVisible = $false
#Write-Host "DEBUG: `nfullString: $fullstring `nuserInput: $userInput `nFIM." -ForegroundColor Red
Write-Host "Type the customer name:" -ForegroundColor Yellow
Write-Host "> " -NoNewline
Write-Host $fullstring -ForegroundColor Cyan
$userInput = [System.Console]::ReadKey($true)
if( $userInput.Key -eq "Backspace" ) { $fullstring = $fullString -replace “.$” }
elseif( $userInput.Key -eq "Enter" ) { return $fullstring }
else { $fullstring = $fullString + $userInput.KeyChar }
if(($fullstring.Length -gt 1) -and ($null -ne $fullstring)) {
$customersList = $customersJson | Where-Object { $_ -match $fullstring } #| Select-Object -First 10
Write-Host "____________________________`n" -ForegroundColor DarkGray
foreach($customer in $customersList) {
# Primeira letra maíúscula
$customer = $customer.ToLower()
$customer = $customer.Replace($customer[0],$customer[0].ToString().ToUpper())
if ($fullstring -eq $customer) {
Write-Host $customer -ForegroundColor DarkRed
} else {
Write-Host $customer -ForegroundColor DarkGray
}
}
Write-Host "____________________________" -ForegroundColor DarkGray
}
}
[console]::CursorVisible = $true
Write-Host "Typed customer: $fullString" -ForegroundColor Red
在提示(“输入客户名称”)标题之后而不是之前显示客户列表。
如果您希望在客户列表之后出现提示,请将
ReadKey
语句移至呈现列表之后:
$customersJson = Get-Content '%jsonpath%\customers.json' | ConvertFrom-Json | ForEach-Object { $_.name }
$fullString = ''
[console]::CursorVisible = $false
while ($true) {
Clear-Host
# 1. Write prompt header
Write-Host 'Type the customer name:' -ForegroundColor Yellow
# 2. Optionally write customer list
if ($fullstring.Length) {
$customersList = $customersJson | Where-Object { $_ -match $fullstring } #| Select-Object -First 10
Write-Host "____________________________`n" -ForegroundColor DarkGray
foreach ($customer in $customersList) {
# Primeira letra maíúscula
$customer = $customer.ToLower()
$customer = $customer.Replace($customer[0], $customer[0].ToString().ToUpper())
if ($fullstring -eq $customer) {
Write-Host $customer -ForegroundColor DarkRed
}
else {
Write-Host $customer -ForegroundColor DarkGray
}
}
Write-Host '____________________________' -ForegroundColor DarkGray
}
# 3. Prompt for next char
Write-Host '> ' -NoNewline
Write-Host $fullstring -ForegroundColor Cyan
$userInput = [System.Console]::ReadKey($true)
if ( $userInput.Key -eq 'Backspace' ) {
$fullstring = $fullString -replace '.$'
}
elseif ( $userInput.Key -eq 'Enter' ) {
return $fullstring
}
else {
$fullstring = $fullString + $userInput.KeyChar
}
}
[console]::CursorVisible = $true
Write-Host "Typed customer: $fullString" -ForegroundColor Red