Tag: Automation

Automate and Deploy Microsoft Defender Advanced Threat Protection (MDATP) via PowerShell

A few days ago, I needed to on-board Azure Windows Server VMs with Microsoft Windows Defender Advanced Threat Protection, or in short, MDATP. Sometimes Azure Security Center (ASC) has issues with on-boarding VMs and deploying the MDATP agent. As a result, I wrote the following PowerShell script that will download the MDATP.cmd file from my Azure Blob container and install it locally to the VM. This script allows you to automate it for many VMs to the scope of a Resource Group.

Now there are a few assumptions here…

  1. Download the MDATP.cmd file from the Defender Security Center portal
  2. Remove the requirement for user consent for the MDATP execution
  3. Upload the modified MDATP file to an Azure Blob container
  4. Generated a SAS URI for the MDATP file

There are many examples on the Internet on how to go step #4. Maybe in time I will do another post.

To remove the requirement of the MDATP agent to execute based on user interaction/consent can be done by removing, or commenting out the following lines of code. Launch the MDATP.cmd file within Notepad, and add a “:” before each line of code from lines 9 through 19, except line 14. Should look something like this.

Now, update and run the following PowerShell code. You can validate the VM is calling back to the Defender Security Center portal or by running the MDATPClientAnalyzer on the VM.

#update resource as needed
$resourcegroup = "YOUR_RESOURCE_GROUP"
#get only Windows Server VMs
$vms = Get-AzVM -ResourceGroupName $resourcegroup | Where-Object {$_.StorageProfile.OSDisk.OSType -eq "Windows"} | Select-Object Name
foreach ($vm in $vms)
{
    #friendly start message to indicate which server has started
    Write-Host "Server $vm has started..."
    #create folder, do not display error if folder already exists
    New-Item -Path "C:\" -Name "MDATP" -ItemType "directory" -ErrorAction SilentlyContinue
    #download MDATP.cmd file from Storage Account with SAS URI. Execute the cmd file. Passing "Y" to continue with installation.
    Invoke-WebRequest -Uri "YOUR_URI_SAS" -OutFile WindowsDefenderATPLocalOnboardingScript.cmd; Start-Process -FilePath "C:\MDATP\WindowsDefenderATPLocalOnboardingScript.cmd" -Verb RunAs
    #sleep for 5 seconds
    Start-Sleep -Seconds 5
    #restart-server
    Restart-Computer -ComputerName $vm
    #friendly finished message to indicate which server has completed and will now reboot
    Write-Host "Server $vm has completed, reboot initiated..."
}

Monitoring Domain Controllers in SCOM 2016 – Script Automation

Not too long ago, I wrote about how SCOM 2016 has some workarounds for monitoring domain controllers, find that post here. We learned the HSLockdown tool needs to be configured to allow the Local System account to be run under.

I was in an environment were 100+ domain controllers needed this done.. No way was I going to do this manually 100+ times… So, I wrote the following script. Unfortunately, do some PowerShell switch limitations, I had to resort to using a batch command line script.

How it works. Save the list of servers affected to a text file. Using this file/script, and PSExec, we can execute the script against the servers affected. To get that script, please visit the Microsoft TechNet Gallery.

Cheers!

Creating Easy Tier (Multi-tier) Pool with IBM Storwize

Creating an Easy Tier (aka Multi-tier) pool within IBM’s Storwize is pretty simple, just it cannot be done via its GUI. The GUI definitely lacks this functionality, and thus I had to resort to learning some IBM CLI for the Storwize(V5000). I have been told (from IBM) the command(s) are the same for both the Storwize v7000 and v3700 series as well.

The benefits of IBM’s Easy Tier is rather impressive, and I am sure (please correct me if I am wrong) this exists within other SAN vendors as well. In my pool, there are three types of disk drives, SSD and SAS (both enterprise grade and nearline). The benefits of the multi-tiered (easy tier) pool allows data to be (seamlessly) migrated to higher-IO drives/pools that provide higher performance, ie. SSD pools.

In my case this is great, as I will have heavy-hitting IOPS SQL virtual machines that will probably require the higher performing SAS if not SSD drives. And whereas low-IOPS hitting data such as Quorums on nearline drives.

As IBM states, “Easy Tier can automatically migrate data at the sub-LUN/sub-volume level to the most appropriate storage tier. This includes the ability to automatically and non-disruptively relocate logical volume extents with high activity to storage media with higher performance characteristics, while extents with low activity are migrated to storage media with lower performance characteristics.

So how is this all done?

I am going to assume you have already created your mdisk/RAID groups. In my case my SSD drives are a RAID-5 likewise with my SAS (enterprise) drives. RAID-6 for my SAS nearline drives.

Within the CLI, you will need to get the IDs of all your drives, you can do this by running the following command, “lsdrive“. Now you can see all your drives, and their disk types, IDs, etc.

1

Now you need to create your Easy Tier pool with the mkarray command. (More syntax info can be found HERE)

“mkarray -level <raidType> -drive <IDrangeOfDrivesPerDiskTypeGroupSepeartedByColon(s)> <YourPoolName>”

mkarray -level raid5 -drive 0:1:2:3 EasyTier-Pool
*Do not forget to leave 1 drive behind as a spare within your MDisk pool, otherwise you will have no hot-spare, and will have to rebuild*
4 5

Once you have created your pool, and assoicated all the drives to the Easy Tier pool, you can now see all the mdiskX groups, using the lsmdisk command.

2

For more details, use the lsmdiskgrp command.

3

We can now also confirm the Easy Tier pool within the GUI.

image004

Now we can start building/migrating or whatever it is your SAN was designed for! 🙂

 

For more literature on IBM’s Easy Tier, please visit the LINK.

Load Balancing SCOM Agents

So you have multiple SCOM Management Servers, yet you just happen to have all of your SCOM agents reporting to one server, or maybe two if you half tried to load balance your agents. There are several reasons why you would want to have multiple Management Servers, ie. off-load workflows, reduce stress on servers, etc., etc. Well what is the point of having multiple Management Servers yet nearly all of your agents are reporting to one, or maybe two at best Management Servers, while the others are collecting dust. Load balance those agents! You could manually move an agent by right clicking and moving to a new server, or you could let our friend PowerShell automate this for you.

In my experience I have seen many SCOM environments where load balancing is either done manually, or not done at all. And usually manually implies the SCOM administrator takes a look which of the servers has the least agents, and deploys away. That works, but why not deploy to any server then let PowerShell load balance for you.

In the solution below, I am using PowerShell along with Orchestrator 2012R2. The runbook can be setup to run ad-hoc, or run regularly, ie. monthly, weekly, etc. Of course if you do not Orchestrator deployed in your environment, you could very well take the script and schedule it to run via Windows Scheduled tasks.

ce63742c-85d7-402e-b114-c3979b7ce32b

Here I have created a Runbook to execute the script, and then send back a warning notification if the Runbook failed, or an informational notification that the Runbook executed successfully.

See below for the PowerShell script. Please note, you will need to change the Line 5 with a SCOM Management server applicable to your environment, duh. This script can also be modified, and you can load balance between two gateway servers.

The script can be found HERE!

Happy SCOM’ing!

SCOM 2012R2 IIS Prerequisites

If you’re like me, a System Center Operations Manager consultant, then I am sure you have already ‘googled’ this a few times by now. I constantly find myself looking this up, so I figured I would write my very own blog post on this.

It should be noted, the following code below was found on various sites, and I have now pieced it together to suite my own needs.

For starters, when installing SCOM 2012R2 and its Web Console, you are required to meet certain IIS prerequisites. You can either do Option 1, the manual way, or Option 2, the PowerShell way.

If you go with Option 1, you will need to install the following IIS features:

  • Static Content
  • Default Document
  • Directory Browsing
  • HTTP Errors
  • HTTP Logging
  • Request Monitor
  • Request Filtering
  • Static Content Compression
  • Web Server (IIS) Support
  • IIS 6 Metabase Compatibility
  • ASP.NET
  • Windows Authentication

Or, Option 2, you can use PowerShell to automate this for you…. (Note, you will need to launch PowerShell console as an Administrator)

Import-Module ServerManager
Add-WindowsFeature NET-Framework-Core,AS-HTTP-Activation,Web-Static-Content,Web-Default-Doc,Web-Dir-Browsing,Web-Http-Errors,Web-Http-Logging,Web-Request-Monitor,Web-Filtering,Web-Stat-Compression,AS-Web-Support,Web-Metabase,Web-Asp-Net,Web-Windows-Auth –restart

scom preq PS capture RT

Automating Start and Stop Times for Azure VMs

So you have set up an Azure lab, but you are now starting to see your billing costs are higher than you anticipated, or maybe you are getting tired of logging in to the Azure portal, every morning and every evening to start and shutdown your lab/Virtual Machine(s). Unfortunately there is no UI in the Azure portal that allows you to input a start and stop time for your Virtual Machines to be powered on and/or off, however there are some clever workarounds! Below are the steps I have taken to automate this problem.

Of course you will need an Azure environment, at least one Virtual Machine and some (very) basic PowerShell knowledge.

For starters, I have already built my VM, and I have already created an account that is a member of the domain administrators.


  • Log into the Azure portal and expand the Browse All icon, located on the left pane.

1

  • Select Automation Accounts and create a new Automation Account. I called mine “MachineStartStopAutomation”.

2

  • Next under the new account, select Assets

3

  • Here we will assign credentials associated to this Automation account. Within Assets, select Credentials

4

5

  • Once you have created the Credentials, next we will need to create the Runbook
  • Go back to the Automation Account, and this time select Runbooks

6

  • Provide some descriptive name for the Runbook. I used “Start<hostname>VM”. Also, I had some issues creating/editing the Runbook script when using the Graphical Runbook type, so I used the PowerShell Workflow. I would advise using the PowerShell Workflow option.

7

  • Within the script, use the code similar here. Note, your workflow will be name of your Runbook name. Also, in line 5, the -Name <hostname> will be your VM you are interested in automating the PowerOn. To be safe, I specified the FQDN.

8

  • Once complete, you can test and/or publish the Runbook. (You will need to Publish the Runbook in order to make use of it)
  • Next you will need to create a schedule. Go back to the Runbook, and select Schedules

9

  • Since I would like to start this VM daily, I set it for daily Recurrence.

10

You will now need to repeat all the steps above (starting at step 7) to create an automated shutdown Runbook. The PowerShell code will be almost exactly the same, but you will make use of the “Stop-VM -Name <hostname>” Cmdlets.

Once complete, your new Automation Runbook should look similar to this. Hopefully this will keep your Azure billing costs down, and hopefully no more daily/manual starting and shutting down your lab/Virtual Machine(s). =)

11

Management Pack Backup Automation

Backup, backup, backup. It is never a bad idea to be safe and back up your data, or in this case your Management Packs. I recently created an automated, scheduled task that runs every Monday morning that backs up all the Management Packs within the environment. Please note, all sealed and un-sealed Management Packs will be backed up in a un-sealed format.

The following PowerShell code I have used:


$a = get-date
$a = $a.ToString("yyyy-MM-dd")
$rootMS = gc env:computername

Import-Module OperationsManager
New-SCOMManagementGroupConnection -ComputerName $rootMS

$path = New-Item -ItemType directory -Path "\\somepath\MPBackup\$a"

Get-SCOMManagementPack | Export-SCOMManagementPack -Path $path.FullName

Wintel Gray Agents Runbook Automation

This Orchestrator Runbook, “SCOM2012R2_Check_HealthService” is setup to capture a “Health Service Heartbeat Failure” for Windows machines, and restart the HealthService and/or delete the corrupted HealthService cache folder and restart the service.

The Runbook will capture the alert from SCOM, once captured, it will wait 60 seconds, it will then ping the machine, and if the ping is successful then it will then wait for 180 seconds, then check to see if the HealthService on the machine is running. If the ping is unsuccessful, it will send an email indicating the machine is actually offline.

If the HealthService is running, then it is possibly a corrupted cache folder. It will then stop the HealthService, delete the cache folder, and restart the service.

If the HealthService is not running, it will then start the service.

In both events, an email will be sent out as an information alert, to indicate that the Runbook resolved the issue.

1

Details of Configuration

Monitor Alert Properties:

2

Link from Monitor Alert to Run Program:

3

Link from Run Program to Get HealthService Status:

4

Link from Get HealthService Status.

If Not running:

5

 Start HealthService Properties:

6

Since the Stop HealthService Properties are almost the same as Start HealthService, we have omitted this.

Delete Folder Properties

This pertains to SCOM 2012R2. There is a duplicate run book with the same configuration that checks against the old folder structure:

7

8

SCOM Wintel Gray Agents Health State and Cache Flush – Part II Automation

In the previous post, we learned we can clear the agents cache, recycle the health service, and this will (hopefully) resolve our gray agent issue. But, what happens when we have to do this for hundreds of agents? One word, PowerShell. PowerShell allows us to automate this task over hundreds of servers to make this very tedious task, actually very quick!Here is the code I use.

Just make sure all of your servers are within the list you are providing, and of course the account you are running as has Local Administrative rights on each server.

$list = gc “.\list.txt”
foreach ($server in $list)
{
       Write-Host $server Check Service: “ -NonewLine
if ((gwmi win32_service -computer $server -filter “name=’HealthService'” | %{$_.State}) -eq “Running”)
{
       gwmi win32_service -computer $server -filter “name=’HealthService'” | %{$_.StopService()}  | findstr ReturnValue | Tee-Object -var service | out-null
       $serviceResult = $service.split(“:”)
       if ($serviceResult[1] -eq ” 0″)
              { Write-Host “Successful” -f Green}
       else
{Write-Host “Failed” -f Red}
start-sleep 5
$a = gwmi win32_Directory -computer $server -filter “Name=’C:\\PROGRA~1\\SYSTEM~1\\Agent\\HEALTH~1\\HEALTH~1′”
                           $a.DeleteEx() | findstr ReturnValue Tee-Object -var status out-null
                           $statusresult $status.split(“:”)
                                  if ($statusResult[1] -eq ” 0″)
                                         {Write-Host “Successful”}
                                  else {Write-Host “Failed”}
       gwmi win32_service -computer $server -filter “name=’HealthService'” | %{$_.StartService()}  | findstr ReturnValue | Tee-Object -var service | out-null
       $serviceResult = $service.split(“:”)
       if ($serviceResult[1] -eq ” 0″)
              { Write-Host “Successful” -f Green}
       else
{Write-Host “Failed” -f Red}
       }
else
{Write-Host Stopped}
}

SCOM Wintel Gray Agents Health State and Cache Flush

Problem, you launch your SCOM console, and your server is in the following state. You browse the server, and check out the health service, and it is clearly running… So now what?

1 (1)

A Windows based machine appears in a “Not monitored” state. While SCOM thinks the machine is un-responsive, we can confirm this is not the case, as we can ping to the machine; in addition we are able to login to the machine.

2 (1)

This is a result of the SCOM health service needing its cache to be cleared.

SCOM has a built in task to do exactly what we want; however, since SCOM believes the machine is in an offline state, it will not be able to trigger the task to the “Not monitored” machine.

3 (1)

SOLUTION – MANUAL PROCESS

  1. Remote into the machine, and launch the services (services.msc). Locate the Microsoft Monitoring Agent service, and stop the service.

4 (1)

  1. Once the service has stopped, browse the following folder, “C:\Program Files\Microsoft Monitoring Agent\Agent\

5 (1)

Delete the entire (Health Service State) folder.

  1. Go back to the Windows Services (services.msc) and start the Microsoft Monitoring Agent service. This will rebuild the folder we just deleted.

Give SCOM a few seconds, maybe a few minutes, and the Health State of our machine will turn back to healthy!