Here’s another item I see in some submisstions of the 2010 Scripting Games that I felt I should address: the use of legacy console redirection. While technically not illegal or wrong, an example like this demonstrates (at least in my opinion) that the scripter hasn’t fully adopted the PowerShell paradigm.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
$computers=get-content "computers.txt" $data=foreach ($computer in $computers) { get-service spooler -ComputerName $computer | Select Machinename,DisplayName,Status } $data > $env:temp\svclog.txt
While this will work and create a text file, it is not fully written in the PowerShell spirit. At the very least, you should use the cmdlets Out-File, Add-Content or Set-Content in place of the legacy console redirection operators, > and >>. I’ll admit that 99 times out of 100 you’ll have no issues with the resulting text file. However, there is the potential for encoding issues. The cmdlets are better designed to handle encoding as well as a few other PowerShell bells and whistles like –noclobber.
Another reason I suggest using cmdlets is that the > and >> operators are actually part of the underlying command session that PowerShell.exe is running on. It’s conceivable that some future version of PowerShell or some PowerShell hosted application won’t support these operators which means your script will fail and need revision. Stick with cmdlets from the beginning to protect your scripting investment.
Here’s a better PowerShell implementation that uses cmdlets and takes better advantage of the pipeline.
get-content -path "computers.txt" | foreach { get-service -Name spooler -ComputerName $_} | Select MachineName,DisplayName,Status | Tee-Object -FilePath $env:temp\svclog.txt
In this example I’m using Tee-Object which not only displays the properties in the console but also redirects to the text file. I’m sure you’ll agree this is better than using > and >>. Or am I making too much out of this?
I fully agree. I see > $null a lot when you should use | Out-Null. Powershell is beautiful and expressive and should be used to its fullest. thanks for the port and informing the younger scripters to take the pure path.