因此,我尝试使用普通的空格和制表符根据不同条件的颜色来格式化某些输出到控制台,并很快发现我创建了很多“ if”和“ elseif”陈述。不好看我也没有完成它,因为数据表中有许多“列”,并且表中每一列的值的length属性可以在6到20个以上的字符之间变化。真的很丑。这就是我开始尝试使用DataTable对象的时候。我有这样的东西:
$queueTable = New-Object System.Data.DataTable
$Queue.Columns.Add("Identity",[string]) | Out-Null
#same thing for 5 more columns, just different column names and types
现在将数据添加到表中
$queues = Get-Queue
foreach ($queue in $queues) {
$NewRow = $queueTable.NewRow()
$NewRow.Identity = $queue.Identity
#And so for the next 5 columns
$queueTable.Rows.Add($NewRow)
}
现在,我要执行的操作是将DataTable对象输出到屏幕,但根据条件使用颜色进行格式化。这是我的那件作品:
foreach ($row in $queueTable) {
if ($row.item("MessageCount") -gt 1) {Write-Host -ForegroundColor Red $row
else {Write-Host $row}
}
该代码的输出只是“ System.Data.Row”,而不是行内的数据。我也尝试使用Write-Output
,它实际上输出数据,但不是很漂亮,它也不允许使用颜色格式化。
当我运行$queueTabel | Format-Table
时,它以我想要的表格格式输出输出,但是它不允许我进行条件格式设置。
请记住,我正在尝试将其写入控制台,因此Out-GridView,DataGrid或DataGridView将无法工作。
答案 0 :(得分:0)
据我所知,我们必须根据列中的值为特定的行着色。 下面提出的解决方案创建了一个并行的“字符串数组”,用于创建彩色输出。也许循环中的代码也可以优化
# Creating the table and adding rows
$queueTable = New-Object System.Data.DataTable
$queueTable.Columns.Add("Identity",[string]) | Out-Null
$queueTable.Columns.Add("MessageCount",[int]) | Out-Null
$queueTable.Rows.Add("test1",1) | Out-Null
$queueTable.Rows.Add("test2",2) | Out-Null
$queueTable.Rows.Add("test3",3) | Out-Null
# convert the datatable to an array of strings
$tableTest = $queueTable | Format-Table | Out-String -Stream
# the first two lines are the header and separator to be printed in any case
$tableTest[0..2] | Write-Host
# then we process the original datatable rows
# if a row matches the criteria, then we print the related line in $tableText
# using the correct format
for ($i=0; $i -lt $queueTable.Rows.Count; $i++) {
if ($queueTable.Rows[$i].MessageCount -gt 1) {
$tableTest[$i+3] | Write-Host -ForegroundColor Red -NoNewline; Write-Host }
else { $tableTest[$i+3] | Write-Host -NoNewline; Write-Host }
}