PowerShell writing to console out of order

Ask your Windows PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
jvierra
Posts: 13882
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: PowerShell writing to console out of order

Post by jvierra » Fri Jan 11, 2019 4:15 pm

The following function is s utility function. It does not want to be made to look like a CmdLet. We don't need to add the parameter statements and we don't want it to be complicated.

Code: Select all

function Get-Index {
	param(
		[psobject[]]$Services
	)
    Write-Host 'Returned services:'
    $Services | ForEach-Object{ Write-Host $_.Index $_.Status $_.Name -ForegroundColor green }
    Read-Host "Which service would you like to restart? (0 - $($Services.Count))"
}
It is also bad coding form to use return to exit a function. This should be reserved for special circumstances. PowerShell always returns all output to the pipeline.

Here is a good set of articles on style, formatting, comment usage and basic overall design of a PS script.

PowerShell Style Guide]

PowerShell Best Practices

D.Leaman
Posts: 18
Joined: Thu Jan 10, 2019 4:21 pm

Re: PowerShell writing to console out of order

Post by D.Leaman » Mon Jan 14, 2019 8:20 am

Awesome! Thank you so much for the pointers, I'll be sure to read through those resources.

Thanks again.
J.B. Hunt
Devin Leaman
Devin.Leaman@jbhunt.com

jvierra
Posts: 13882
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: PowerShell writing to console out of order

Post by jvierra » Mon Jan 14, 2019 9:07 am

The links can help you to acquire a consistent style that is generally acceptable across the industry and will help you to sort through much of the, at time, frustrating behavior of the PowerShell scripting system. It is not anything like any programming language. PowerShell is designed to solve many issues of scripting languages and systems and, without a deep understanding, PS can be an uphill battle. Just learning to do things form "recipes" will not teach you the internals of PS and may cause you to make incorrect assumptions. Unfortunately most blogs, articles and simple tutorials do little to actually teach the internals of PS.

"PowerShell in Action - Second Edition" by Bruce Payette is an excellent baseline for PowerShell.

There is also this video tutorial: Getting Started With Microsoft Powershell which is presented by Jefferey Snover who designed the PowerShell language and system.

Locked