Now that PowerShell is available on various Linux distributions (such as CentOS, Red Hat, and Ubuntu), it is natural for Windows sysadmins to begin tinkering on Linux machines. One of the first thoughts I had after hearing the news that PowerShell was cross-platform was "I wonder what I can script with PowerShell on Linux?"

The answer to this question is: quite a lot! In this article I will show you two very simple PowerShell scripts you can use on CentOS.

PowerShell Core does not have the fancy cmdlets Windows users are familiar with, such as manipulating the firewall, services, or storage since these are native only to Windows. In fact, at the time of this article there are only 352 commands in PowerShell Core as Get-Command shows.

So how can we use PowerShell to create scripts on Linux like we are used to on Windows? We have to use native Linux commands like crontab, df, and systemctl that perform tasks for which PowerShell does not have cmdlets. Since PowerShell is just another shell on Linux, it can run these Linux commands within PowerShell.

Adding a PowerShell module in Linux ^

While you can create PowerShell functions in a .ps1 file on Linux and run them within the console, I prefer to create modules. Currently, PowerShell Core on CentOS has three directories in which to store modules:

To make a module available to all users on my computer, I will store it in the /opt/microsoft/powershell/6.0.0-beta.4/Modules directory. To create a module for Get-DiskSpace, I will store the function in the Get-DiskSpace.psm1 file under the Get-DiskSpace directory, just as I would on Windows. This is the minimum needed to create a PowerShell module.

Now I just need to add the actual code for the Get-DiskSpace module. To do this from the Linux command line, we use the vi editor to run this command:

Tip: For those new to vi, the "i" key lets you insert text into the editor, the escape key brings you out of insert mode, and finally, typing ":wq" exits the editor and saves your file.

Now if we run Get-Module -ListAvailable, we see this lists the Get-DiskSpace module:

Get-Module ListAvailable

Get-Module ListAvailable

Going forward, my Get-DiskSpace module will load after launching PowerShell each time on my computer. Note that if you want to create more professional modules in production scenarios, you should use New-ModuleManifest just as you would in Windows.

Monitoring disk space ^

Now that we know how to create a simple module, I will show two examples of scripts I have written in Linux. In this first example, I wanted to write a PowerShell script that will monitor the boot partition on a CentOS server for usage, and if it is over a certain amount, send an email alert.

This is a perfect example of how we need to combine native Linux commands and PowerShell to accomplish a task. To see the disk usage on your local disks in Linux, you can use df -h. The -h argument means outputting the results into a human readable format.

Obviously, /boot is the boot partition on Linux, so I will try to parse this with PowerShell to grab the "Use%" value, in this case 25%.

To grab the 25% value, I will use df -h, pipe it to Select-String, split that line at the percentage character, and split it again at the last empty space.

I have parsed the output of df to get the percentage used for /boot. Now I will compare that to a threshold value in this function and use Send-MailMessage (yes, this cmdlet is available now in PowerShell Core). This will alert me if that value is over the threshold.

Here, I run Get-DiskSpace while specifying the maximum size threshold of 10 GB of the boot partition. As you can see, the output states it is sending a mail alert since it is over that threshold.

Get-Disk example

Get-Disk example

Checking the status of a service ^

Unfortunately, Get-Service is not a cmdlet in PowerShell core, and neither are the other service-oriented cmdlets. Thus, we cannot use it to start, stop, or restart services on a Linux computer. To do this on current Red Hat and CentOS distributions, for instance, we must use the systemctl command.

For example, if we would like to check whether the sshd service is running, we can run systemctl with is-active:

systemctl command

systemctl command

As you can see, the status is "active," which means the service is currently running. So to combine PowerShell Core and native Linux again, we can write another simple function. Get-ServiceStatus will check the status of a specified service, and if it is not active, send an email with Send-MailMessage.

Note that it is also possible to show whether the service is enabled or has failed. We can do this by using systemctl --is-enabled and systemctl --is-failed. For the sake of simplicity, I have left these out of the script.

In this function we will also use the hostname command. The hostname command simply prints the hostname of the local computer; we will use it in the $HostName variable shown in the email alert.

hostname command

hostname command



Below, I ran Get-ServiceStatus against the service "foo." The "foo" service obviously does not exist on the system ja warning message.

Get ServiceStatus on foo

Get ServiceStatus on foo

Next, I will try the Get-ServiceStatus function on the "nfs-service" service. Since it exists but is not running, the function sends an email.

Get ServiceStatus on nfs service

Get ServiceStatus on nfs service

Note that in the Get-ServiceStatus function, we combine the use of an "if" statement with systemctl to verify the service is "active." If it is active, the function will do nothing, so it continues to the next value in the $ServiceName array. As you can see, PowerShell and Linux commands integrate gracefully.

I hope these examples give the average Windows system administrator a little jump-start to dive into using PowerShell with Linux. We now live in a cross-platform, hybrid cloud world where having knowledge of one platform just isn't going to cut it anymore. If you use PowerShell on your Windows systems, there is no excuse not to learn Linux as well!

Join the 4sysops PowerShell group!

Your question was not answered? Ask in the forum!

1+

Users who have LIKED this post:

  • avatar
Share
11 Comments
  1. Brice 2 years ago

    Hello,
    I have a problem when I want to use the "Send-MailMessage" command if you have the same problem?

    error message "Send-MailMessage : The term 'Send-MailMessage' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again."

    Thank you
    Regards,

    Brice

    0

  2. Brice 2 years ago

    Hello,

    I install version 6 of this link "https://developers.redhat.com/blog/2017/02/09/powershell-on-rhel-in-one-minute/",
    but I did not find any more version above.

    Thank you
    Regards,

    Brice

    1+

  3. Brice 2 years ago

    Hello,

    I find a new version on this site "https://github.com/PowerShell/PowerShell/releases/",
    Thanks for your help

    Regards,

    Brice

    1+

  4. Akshata 11 months ago

    Hello Dan,

    I am trying to install OperationsManager module in powershell (on linux machine) but I receive the following errors. I have copied the required files from the server with SCOM console installed. Not sure what I am missing here or maybe I am doing this in a wrong way.

    Thank you,

    Akshata
    PS /opt/microsoft/powershell/6/Modules> Get-Module -ListAvailable -name "OperationsManager"

    Directory: /opt/microsoft/powershell/6/Modules

    ModuleType Version Name PSEdition ExportedCommands
    ---------- ------- ---- --------- ----------------
    Script 1.0 OperationsManager Desk {Get-SCRelationshipInstance, Remove-SCManagementGroupConnection, Get-SCDiscovery, Expor…
    PS /opt/microsoft/powershell/6/Modules> Install-Module OperationsManager
    PackageManagementInstall-Package : No match was found for the specified search criteria and module name 'OperationsManager'. Try Get-PSRepository to see all available registered module repositories.
    At /opt/microsoft/powershell/6/Modules/PowerShellGet/PSModule.psm1:9349 char:21
    + ... $null = PackageManagementInstall-Package @PSBoundParameters
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : ObjectNotFound: (Microsoft.PowerShelu2026lets.InstallPackage:InstallPackage) [Install-Package], Exception
    + FullyQualifiedErrorId : NoMatchFoundForCriteria,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage

    0

    • @Akshata

      The OperationManager module is already installed.
      Thus you must use the Import-Module cmdlet (which is importing the module to your current host) instead of the Install-Module (which is downloading the module from the repository to your computer).

      0

  5. Akshata 11 months ago

    Hi Luc,

    I imported the module. following is the output.  The OperationsManager file that I copied from the SCOM console server has Microsoft.EnterpriseManagement.Core.Cmdlets.resources.dll, OM10.CoreCommands.psd1.

    PS /opt/microsoft/powershell/6/Modules> Import-module -Name "OperationsManager"
    Import-Module : Could not load file or assembly 'Microsoft.EnterpriseManagement.Core, Version=7.0.5000.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.
    At /opt/microsoft/powershell/6/Modules/OperationsManager/OperationsManager.psm1:1261 char:1
    + Import-Module $psScriptRoot\OM10.CoreCommands\OM10.CoreCommands.psd1
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.ImportModuleCommand

    Import-Module : Could not load file or assembly 'Microsoft.EnterpriseManagement.Core, Version=7.0.5000.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'. The system cannot find the file specified.
    At /opt/microsoft/powershell/6/Modules/OperationsManager/OperationsManager.psm1:1262 char:1
    + Import-Module $psScriptRoot\OM10.Commands\OM10.Commands.psd1
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.PowerShell.Commands.ImportModuleCommand

    Import-Module : Could not load type 'System.Management.Automation.CustomPSSnapIn' from assembly 'System.Management.Automation, Version=6.2.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.
    At /opt/microsoft/powershell/6/Modules/OperationsManager/OM10.CrossPlatform.Start.ps1:12 char:43
    + ... sion.Major -ge [int]3) {Import-Module $scriptPath\OM10.CrossPlatform}
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : NotSpecified: (:) [Import-Module], TypeLoadException
    + FullyQualifiedErrorId : System.TypeLoadException,Microsoft.PowerShell.Commands.ImportModuleCommand

    PS /opt/microsoft/powershell/6/Modules> Import-module -Name OperationsManager
    PS /opt/microsoft/powershell/6/Modules> Import-module -Name OperationsManager

    ****************************************************************************************

    PS /opt/microsoft/powershell/6/Modules> Get-SCOM
    Get-SCOMClass Get-SCOMManagementGroupConnection Get-SCOMRelationship Get-SCOMRunAsDistribution
    Get-SCOMCommand Get-SCOMManagementPack Get-SCOMRelationshipInstance Get-SCOMTierConnector
    Get-SCOMDiscovery Get-SCOMMonitoringObject Get-SCOMRunAsAccount Get-SCOMTieredManagementGroup

    ************************************************************************************

    PS /opt/microsoft/powershell/6/Modules> Get-SCOMClass
    Get-SCOMClass : The term 'Get-SCClass' is not recognized as the name of a cmdlet, function, script file, or operable program.
    Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    At line:1 char:1
    + Get-SCOMClass
    + ~~~~~~~~~~~~~
    + CategoryInfo : ObjectNotFound: (Get-SCClass:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

    **************************************************************************************

    PS /opt/microsoft/powershell/6/Modules> Get-SCOMManagementGroupConnection
    Get-SCOMManagementGroupConnection : The term 'Get-SCManagementGroupConnection' is not recognized as the name of a cmdlet, function, script file, or operable program.
    Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    At line:1 char:1
    + Get-SCOMManagementGroupConnection
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo : ObjectNotFound: (Get-SCManagementGroupConnection:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

    Thank you,

    Akshata

    0

  6. Akshata 11 months ago

    I copied the entire OperationManager directory from the windows machine to linux path: /opt/microsoft/powershell/6/Modules/

    When I fire Get-Module -ListAvailable, its shows me :

    Script 1.0 OperationsManager Desk {Get-ErrorInfo, Write-WarningMessage, New-DefaultManagementGroupConnection, Add-SCOMRun…

    Is this the right way ? I am unable to use any SCOM commands without importing OperationManager.

    0

    • @Akshata
      The error "Could not load file or assembly" means that the underlying binaries are not present.

      The Microsoft.EnterpriseManagement.Core.dll file is available on Windows computers in one of the SCOM folders. But if you copy it from a Windows computer to a Linux computer:

      • I am not sure it is compatible with Linux computers
      • I don't know where to copy it on a Linux computer

      I would first try to install the SCOM agent for Linux. Maybe it will install the needed assemblies for you and at the right place...

      1+

  7. Akshatakamath 11 months ago

    Thanks Luc!! I will try this and let you know.

    0

  8. Harshvardhan Gupta 5 months ago

    I'm getting error xdg-open: no method available for opening '/opt/microsoft/powershell/6/Modules/get-diskspace.psml'

    0

Leave a reply

Your email address will not be published. Required fields are marked *

*

© 4sysops 2006 - 2020

CONTACT US

Please ask IT administration questions in the forums. Any other messages are welcome.

Sending

Log in with your credentials

or    

Forgot your details?

Create Account