Chapter 14
Activity
Because PowerShell is very forgiving about file path separators, the only bit of code that needs to be different depending on the platform is how we get the name of the machine. Everything else is straightforward. Here’s my solution; yours could be very different and still achieve the task:
if ($IsWindows) { $computername = $env:COMPUTERNAME } elseif ($IsLinux) { $computername = (hostname) } Get-Process | Sort-Object -Property CPU -Descending | Select-Object -First 5 | Out-File "$($computername)_processes.txt"
Because we need to use different ways to get the machine name, those two lines are within if
statements. Everything else works the same on Linux and Windows, so it’s very straightforward. This is how it looks running on my CentOS box:
Figure A.15 – Running a cross-platform script on CentOS
As we can see, it works just fine. The script would be better for some error checking; for instance...