Fomatting text in RichTextBox

by chrisuk11 at 2013-02-03 03:08:20

I am outputting my results to a rich text box on a form.

However I am finding it difficult to actually format the data so it appears as I want.

Any tips / guides on how to do this? Or is it better to output to a different type of text box? I am using sapien powershell studio to design the forms.

Example -

$CFree = Get-WmiObject Win32_LogicalDisk -Filter “DeviceID=‘C:’” -Property FreeSpace -ComputerName $textboxPCName.Text |
Select-Object @{name=“CFreeMB”;expression={$_.FreeSpace/1MB}} |
Select-Object -ExpandProperty CFreeMB | Format-Table -AutoSize | Out-String
foreach ($line in $CFree) {

If ($CFree -gt 1000) { $richtextboxQueryPC.AppendText(“HDD - C drive is OK at $($CFree)MB free”) }
ElseIf ($CFree -lt 1000) { $richtextboxQueryPC.AppendText(“HDD - C drive is low at $($CFree)MB free”) }
ElseIf ($CFree -lt 100) { $richtextboxQueryPC.AppendText(“HDD - C drive is critically low at $($CFree)MB free”) }

# Free memory in MB
$MemFree = Get-WmiObject Win32_PerfFormattedData_PerfOS_Memory -Property AvailableMBytes -ComputerName $textboxPCName.text |
Select-Object -ExpandProperty AvailableMBytes | Format-Table -AutoSize | Out-String
If ($MemFree -gt 1000) { $richtextboxQueryPC.AppendText(“RAM - is OK at $($MemFree)MB”) }
ElseIf ($MemFree -lt 1000) { $richtextboxQueryPC.AppendText(“RAM - is low at $($MemFree)MB”) }
ElseIf ($MemFree -lt 100) { $richtextboxQueryPC.AppendText(“RAM - is critically low at $($MemFree)MB”) }

$CPU = Get-WmiObject Win32_PerfFormattedData_PerfOS_Processor -Property Name, PercentProcessorTime -ComputerName $TEXTBOXpcnAME.Text -Filter “Name=’_Total’” |
Select-Object -ExpandProperty PercentProcessorTime | Out-String

If ($CPU -gt 95) {$richtextboxQueryPC.AppendText(“CPU is pegged at $CPU%”) }
ElseIf ($CPU -gt 50) {$richtextboxQueryPC.AppendText(“CPU is high at $CPU%”) }
Else {$richtextboxQueryPC.AppendText(“CPU is OK at $CPU%”) }

This outputs in the rich text box as -

Disk, Memory, and CPU---------------------C Drive19726.0234375
HDD - C drive is OK at 19726.0234375
MB freeRAMRAM - is OK at 5320
MBCPUCPU is high at 53

Also the following code -

$PCServices = gwmi win32_service -ComputerName $textboxPCName.Text | sort DisplayName | select-object SystemName,DisplayName,StartMode,State,PathName,name
#| Out-String
foreach ($Service in $PCServices) {
$listboxServices.Items.add($ + " (" + $Service.state + “)”)

$PCProcesses = gwmi Win32_Process -ComputerName $textboxPCName.Text | sort Name | select-object Name
#| Out-String
foreach ($Process in $PCProcesses) {

Outputs as -

ServicesAxInstSVSensrSvcAdobeARMserviceAdobeFlashPlayerUpdateSvcApple Mobile DeviceAeLookupSvcAppIDSvcAppinfoALGAppMgmtaspnet_stateAtherosSvcavast! AntivirusBITSBFEBDESVCwbenginebthservBonjour ServicePeerDistSvcCertPropSvcKeyIsoEventSystemCOMSysAppBrowserVaultSvcCryptSvcCLKMSVC10_9EC60124DcomLaunchUxSmsDhcpDPSWdiServiceHostWdiSystemHostdefragsvcTrkWksMSDTCDnscacheEFSEapHostFaxfdPHostFDResPubgupdategupdatemgpsvchkmsvcHomeGroupProviderhidservIKEEXTcphsIAStorDataMgrSvcUI0DetectSharedAccessiphlpsvciPod ServicePolicyAgentKtmRmlltdsvcMcx2Svcclr_optimization_v2.0.50727_64clr_optimization_v2.0.50727_32clr_optimization_v4.0.30319_64clr_optimization_v4.0.30319_32MSiSCSIMicrosoft SharePoint Workspace Audit ServiceswprvmfsyncsvMMCSSMySQL55NetMsmqActivatorNetPipeActivatorNetTcpActivatorNetTcpPortSharingNetlogonnapagentNetmannetprofmNlaSvcnsioseosppsvcCscServiceWPCSvcPNRPsvcp2psvcp2pimsvcPerfHostplaPlugPlayIPBusEnumPNRPAutoRegWPDBusEnumPowerSpoolerwercplsupportPcaSvcProtectedStorageQWAVERasAutoRasManSessionEnvTermServiceUmRdpServicerpcapdRpcSsRpcLocatorRemoteRegistryRemoteAccessRpcEptMapperseclogonSstpSvcSamSswscsvcLanmanServerShellHWDetectionSCardSvrSCPolicySvcSNMPTRAPsppsvcsppuinotifySSDPSRVStorSvcSysMainSENSTabletInputServiceSchedulelmhostsTeamViewer8TapiSrvThemesTHREADORDERTBSupnphostProfSvcvdsVMAuthdServiceVMnetDHCPVMware NAT ServiceVMUSBArbServiceVSSWebClientWatAdminSvcAudioSrvAudioEndpointBuilderSDRSVCWbioSrvcidsvcWcsPlugInServicewcncsvcWinDefendwudfsvcWerSvcWecsvceventlogMpsSvcFontCachestisvcmsiserverWinmgmtehRecvrehSchedWMPNetworkSvcTrustedInstallerFontCache3.0.0.0WinRMWSearchW32TimewuauservWinHttpAutoProxySvcdot3svcWlansvcwmiApSrvLanmanWorkstationWwanSvcProcessesAdminService.exeAppleMobileDeviceService.exearmsvc.exeAthBtTray.exeaudiodg.exeAvastSvc.exeAvastUI.exebrs.exeBtvStack.exechrome.exechrome.exechrome.exechrome.exechrome.exechrome.exechrome.execoncentr.execsrss.execsrss.exedwm.exeexplorer.exehkcmd.exeIAStorDataMgrSvc.exeIAStorIcon.exeigfxpers.exeigfxtray.exeiPodService.exeiTunesHelper.exejucheck.exejusched.exelsass.exelsm.exemDNSResponder.exemfsyncsv.exemrfshl.exemstsc.exemysqld.exePDVD9Serv.exePowerShell Studio.exerundll32.exeScriptDriver64.exeSearchFilterHost.exeSearchIndexer.exeSearchProtocolHost.exeservices.exesmss.exeSMSvcHost.exespoolsv.exeSpotifyWebHelper.exesvchost.exesvchost.exesvchost.exesvchost.exesvchost.exesvchost.exesvchost.exesvchost.exesvchost.exesvchost.exesvchost.exesvchost.exesvchost.exesvchost.exeSystemSystem Idle Processtaskhost.exeTeamViewer_Service.exevmnat.exevmnetdhcp.exevmware-authd.exevmware-usbarbitrator64.exewfcrun32.exewininit.exewinlogon.exeWmiPrvSE.exewmpnetwk.exeWUDFHost.exeXBMC

As you can see its not very user friendly :frowning:

Any tips / help links would be appreciated. Thanks
by DonJ at 2013-02-03 07:08:28
Rich text is difficult to format. It uses its own markup language. I’d suggest using a normal text box and setting the font to a monospaced font like Consolas. You might also consider piping your results to Out-GridView instead. Much prettier.
by chrisuk11 at 2013-02-03 07:29:19
Thanks Don.

I have tried outputting, using the same code as above, to a multiline text box and the result is exactly the same

Disk, Memory, and CPU---------------------C Drive19726.0234375
HDD - C drive is OK at 19726.0234375
MB freeRAMRAM - is OK at 5320
MBCPUCPU is high at 53

This was using font - Courier New.

Could you elaborate on “Out-GridView instead. Much prettier.”

by DonJ at 2013-02-03 07:48:45
Get-Service | Out-GridView

My point is that the GridView is (a) more attractive, (b) lets the end user sort/filter interactively, © requires no work, and (d) keeps everything lined up.

The textbox problem is probably an issue with carriage returns and linefeeds. It’s fixable, but it’s going to be a PITA. It just isn’t what a textbox is designed for. I tend to use Out-GridView when I need a GUI way to display a table of information - it’s what it meant for. You can pipe any kind of object to it. PowerShell’s just not an awesome manipulator of formatted text, which is what any kind of textbox is going to require.

The trick with Out-GridView is that you need to be outputting objects to it. Right now I don’t think you are.

$CPU = Get-WmiObject Win32_PerfFormattedData_PerfOS_Processor -Property Name, PercentProcessorTime -ComputerName $TEXTBOXpcnAME.Text -Filter “Name=’_Total’” |
Select-Object -ExpandProperty PercentProcessorTime

If ($CPU -gt 95) {$message =(“CPU is pegged at $CPU%”) }
ElseIf ($CPU -gt 50) {$message = (“CPU is high at $CPU%”) }
Else {$message =(“CPU is OK at $CPU%”) }

$properties = @{‘Message’=$message;‘CPU%’=$cpu}
New-Object -Type PSObject -Prop $properties | Out-GridView

Something vaguely like that. The general moral in PowerShell is that, if you’re trying to format text, you might not be doing it right. In this case, I took basically your same code. But rather than sticking the message in a text box, I created an object with a couple of properties. Those turn into columns with Out-GridView.

Out-GridView does have some limitations - it isn’t designed for multi-section “reports,” so you’ll have to think in columns rather than in rows of text. And it certainly isn’t the answer for every situation. That said, PowerShell’s not the best tool in the universe for building a pretty GUI. You can do it, but it can be a lot of work.

When I need to generate a really nice-looking report with multiple sections (CPU, disk status, processes, etc)., I tend to use HTML. I can write an HTML file to disk, and invoke IE to open the file and display it. I wrote a book on how (it’s free) - “Creating HTML Reports in PowerShell.” It’s at if you’re interested.

If you got fancy, you could build your GUI tool in PowerShell Studio to generate the HTML report, and instead of out-ing it to a file, just keep it in a variable. You could then have a form that used a WebView control, which is basically the IE rendering engine. You could then stock the HTML report from the variable into the WebView, so you’d basically get a dialog box showing the HTML contents. Which would let you do some very pretty formatting. Now… that’s totally beyond the scope of what I can show you how to do here (although I might add it to the book in the future), but I wanted to let you know the possibilities.

The problem with your textbox is likely that PowerShell is generating a CR but not a CRLF at the end of each line. Windows GUI apps are a little picky about that.

I’m not totally certain what your goal is, but another option might be to not output text to a text box. I mean, if the goal is to create a little GUI display for a user, why not do it the right way? GUIs aren’t about text. Put little Image controls on the GUI form, and set them to be a green checkmark, yellow “!” or red “X” based on the status. You can use Label controls to put in text like the free space, RAM, and CPU utilization. Your GUI would look a lot more like a typical monitoring tool that way.

Anyway… just trying to offer you some options. You can decide what’s best for you.
by chrisuk11 at 2013-02-03 08:01:17
Thanks Don.
Appreciate the time taken to respond in such a detailed manner :slight_smile:

I am going to take a look at the book you have linked to.

Just FYI, I am trying to create a tool that can be used by the IT HelpDesk, so it basically queries PCs for disk, cpu, processes, services, event logs etc :slight_smile:
by DonJ at 2013-02-03 08:19:10
I think half the industry is creating that tool for themselves :). Eventually one of you will post it someplace so everyone else can stop reinventing it <grin>.
by chrisuk11 at 2013-02-03 10:00:04
Can you embed a HTML browser window or anything into a powershell GUI? As looking at the link you provided, I like the idea or formatting it using HTML, however not so keen on it opening a separate window to display the data.

I can’t seem to find an option in powerstudio
by DonJ at 2013-02-03 10:18:12
Yes, you can embed an HTML browser window. There’s a WebView control in WinForms. I don’t know if SAPIEN’s product offers it in the default toolbox or not - you’d need to ask them.