<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:taxo="http://purl.org/rss/1.0/modules/taxonomy/" version="2.0">
  <channel>
    <title>topic Re: Morpheus Windows Agent - Useful Powershell Functions in HPE Morpheus Enterprise Software</title>
    <link>https://community.hpe.com/t5/hpe-morpheus-enterprise-software/morpheus-windows-agent-useful-powershell-functions/m-p/7249826#M3000</link>
    <description />
    <pubDate>Wed, 06 Sep 2023 12:40:53 GMT</pubDate>
    <dc:creator />
    <dc:date>2023-09-06T12:40:53Z</dc:date>
    <item>
      <title>Morpheus Windows Agent - Useful Powershell Functions</title>
      <link>https://community.hpe.com/t5/hpe-morpheus-enterprise-software/morpheus-windows-agent-useful-powershell-functions/m-p/7249822#M2996</link>
      <description>&lt;H1&gt;
&lt;A name="morpheus-windows-agent-configuration-1" class="anchor" href="#morpheus-windows-agent-configuration-1"&gt;&lt;/A&gt;Morpheus Windows Agent Configuration&lt;/H1&gt;
&lt;H2&gt;
&lt;A name="powershell-functions-for-managing-the-morpheus-agent-config-files-2" class="anchor" href="#powershell-functions-for-managing-the-morpheus-agent-config-files-2"&gt;&lt;/A&gt;Powershell Functions for managing the Morpheus Agent config files&lt;/H2&gt;
&lt;P&gt;In this post want to share some Powershell functions that can be used in Morpheus Tasks to obtain information about the &lt;STRONG&gt;Morpheus Windows Agent&lt;/STRONG&gt; and allow tasks to view and make updates to the  Windows Agent config file.&lt;/P&gt;
&lt;H2&gt;
&lt;A name="powershell-functions-3" class="anchor" href="#powershell-functions-3"&gt;&lt;/A&gt;Powershell Functions&lt;/H2&gt;
&lt;PRE style="background : #f0f1f2;"&gt;&lt;CODE class="lang-auto"&gt;Function Get-MorpheusAgentConfig {
    &amp;lt;#
    .SYNOPSIS
        Returns the current contents of the Morpheus Windows Agent config file

    .OUTPUTS
        if successful the contents of the MorpheusAgent.exe.config file are returned

    #&amp;gt;     
    if (IsElevated) {
        $Agent = Get-CIMInstance -Class win32_Service -Filter "Name like 'Morpheus Windows Agent'"
        if ($Agent) {
            $AgentFolder = Split-Path -Path ($Agent.PathName -replace '"','') -Parent
            $ConfigFile = Join-Path -Path $AgentFolder -ChildPath "MorpheusAgent.exe.config"
            if (Test-Path -Path $ConfigFile) {
                # Config file exists
                $CF = Get-Content -Path $ConfigFile -Raw
                return $CF
            }
            else {
                Write-Warning "Agent Config file $($ConfigFile) Not Found"
            }
        }
        else {
            Write-Warning "Morpheus Windows Agent Not Found"
        }
    }
    else {
        Write-Warning "This function must have Administrator privilege"
    }
}

Function Set-MorpheusAgentConfig {
    &amp;lt;#
    .SYNOPSIS
        Optionally Sets the values of LogLevel, Host and ApiKey in the Morpheus Windows Agent config file

    .PARAMETER LogLevel
        Sets the LogLevel 0 = debug; 1 = info; 2 = warn; 3 = error; 4 = off
        Default value is 1

    .PARAMETER ApplianceUrl
        Optionally sets the appliance Host. There is no Default value.
        Only specify if you need to change the Host name

        Format is "https://ApplianceNameOrIp/"

    .PARAMETER ApiKey
        Optionally sets the Instance ApiKey. There is no Default value.
        Only specify if you need to change the ApiKey

        The ApiKey MUST match exactly the ApiKey on the Compute Server details page

    .PARAMETER RestartAgent
        Specify this parameter to schedule a delayed restart (60 seconds) of the Morpheus Windows Agent Service

    .OUTPUTS
        if successful the updated contents of the MorpheusAgent.exe.config file are returned

    #&amp;gt; 
    [CmdletBinding()]
    param (
        [ValidateRange(0,4)]
        [Int32]$LogLevel=1,
        [String]$ApplianceUrl=$null,
        [String]$ApiKey=$null,
        [Switch]$RestartAgent
    )
    
    if (IsElevated) {
        $Agent = Get-CIMInstance -Class win32_Service -Filter "Name like 'Morpheus Windows Agent'"
        if ($Agent) {
            $AgentFolder = Split-Path -Path ($Agent.PathName -replace '"','') -Parent
            $ConfigFile = Join-Path -Path $AgentFolder -ChildPath "MorpheusAgent.exe.config"
            if (Test-Path -Path $ConfigFile) {
                # Config file exists - load the file as XML - Fail and exit if not valid
                try {
                    [Xml]$Config = Get-Content -Path $ConfigFile -Raw
                }
                Catch {
                    Write-Warning "Failed to Parse XML Agent Config file"
                    $Config = $null
                }
                if ($Config) {
                    #Navigate the XML - run through the app settings modifying the attributes as required
                    foreach ($node in $Config.SelectNodes("/configuration/appSettings/add")) {
                        if (($LogLevel -ge 0 -AND $LogLevel -lt 5) -AND $node.GetAttribute("key") -eq "LogLevel") {$node.SetAttribute("value",$LogLevel.toString())}
                        if ($ApplianceUrl -AND $node.GetAttribute("key") -eq "Host") {$node.SetAttribute("value",$ApplianceUrl)}
                        if ($ApiKey -AND $node.GetAttribute("key") -eq "ApiKey") {$node.SetAttribute("value",$ApiKey)}
                    }
                    $Config.Save($ConfigFile)
                    # Restart Service - use Delay-AgentRestart to detach a process to do the restart otherwise it kills this job
                    if ($RestartAgent) {
                        $RestartPid = Delay-AgentRestart -Delay 60
                        Write-Host "Delaying Agent Service Restart - detaching process $($RestartPid)"
                    }
                    else {
                        Write-Warning "Agent Service must be restarted to use new configuration"
                    }
                    Write-Host "Returning Updated Agent Config ..."
                    # Return the updated Config File (as a String)
                    return (Get-MorpheusAgentConfig)
                }
            }
            elget-se {
                Write-Warning "Agent Config file $($ConfigFile) Not Found"
            }
        }
        else {
            Write-Warning "Morpheus Windows Agent Not Found"
        }
    }
    else {
        Write-Warning "This function must have Administrator privilege"
    }
}  
  
Function Get-MorpheusAgentSocketStatus {
    &amp;lt;#
    .SYNOPSIS
        Returns the Morpheus Windows Agent Service Status and associated TCP Socket details 

    .PARAMETER AsJson
        Specify this parameter to return output as a json string

    .OUTPUTS
        PSCustom object, or optionally json string containing the Agent and Socket status 

    #&amp;gt; 
    [CmdletBinding()]
    param (
        [Switch]$AsJson
    )

    $Status = [PSCustomObject]@{
        adminAccess=IsElevated;
        machineName=[Environment]::MachineName;
        agentStatus="";
        agentState=""
        agentPid=$null;
        agentSockets=$null
    }

    if (IsElevated) {
        $Agent = Get-CIMInstance -Class win32_Service -Filter "Name like 'Morpheus Windows Agent'"
        if ($Agent) {
            $Status.agentStatus = $Agent.Status
            $Status.agentState = $Agent.State
            # We have an agent - Does it have a Pid
            if ($Agent.ProcessId -Ne 0) {
                $Status.agentPid = $Agent.ProcessId
                try {
                    $Sockets = @(Get-NetTCPConnection -RemotePort 443 -OwningProcess $Agent.ProcessId)
                }
                catch {
                    $Sockets = @()
                    Write-Warning "Agent ProcessId Owns no Sockets on port 443"
                }
                $Status.agentSockets = foreach ($Socket in $Sockets) {
                    [PSCustomObject]@{
                        state = $Socket.State.ToString();
                        creationTime = $Socket.CreationTime.ToString("s");
                        localAddress = $Socket.LocalAddress;
                        localPort = $Socket.LocalPort;
                        remoteAddress = $Socket.RemoteAddress;
                        remotePort = $Socket.RemotePort
                    } 
                }
            }
            else {
                Write-Warning "Morpheus Windows Agent Installed but Not Running on  $($Status.machineName)"
                $Status.agentStatus="NotRunning"                
            }
        }
        else {
            Write-Warning "Morpheus Windows Agent Not Installed on  $($Status.machineName)"
            $Status.agentStatus="NoAgent"
        }         
    }
    else {
        Write-Warning "You need to be an Administrator to run this Function"
    }
    if ($AsJson) {
        return $Status | ConvertTo-Json -Depth 5
    }
    else {
        return $Status
    }
}

Function IsElevated {
    &amp;lt;#
    .SYNOPSIS
        Helper function.
        Determines if the current user has Administrator Privilege

    .OUTPUTS
        $true - Current user has Administrator role
        $false = Curent User does not have Administrator Role

    #&amp;gt;     
    $userIdentity =  [System.Security.Principal.WindowsIdentity]::GetCurrent()
    $userPrincipal = [System.Security.Principal.WindowsPrincipal]$userIdentity
    $adminElevated=$userPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
    return $adminElevated
}


Function Delay-AgentRestart {
    &amp;lt;#
    .SYNOPSIS
        Helper Tool used to detach a process to delay a restart of the Morpheus Windows Agent service.
        This way you can restart the Agent from a command bus session without affecting the runnign job 

    .PARAMETER Delay
        Number of seconds to Wait before the Agent is restarted. Default is 30

    .OUTPUTS
        Returns the Process Id of the detached process responsible for restarting the Morpheus Windows Agent service.
        Returns 0 if the Detached process failed to start successfully

    #&amp;gt;     
    [CmdletBinding()]
    param (
        [Int32]$Delay=30
    )

        $ArgString = " -noprofile -command ""&amp;amp; {start-sleep -seconds $($Delay); Restart-Service 'Morpheus Windows Agent' }"" "
        $RestartProcess = Start-Process -FilePath "powershell.exe" -ArgumentList $ArgString -Verb "RunAs" -WindowStyle "Hidden" -Passthru
        if ($RestartProcess) {
            return $RestartProcess.Id
        }
        else {
            return 0
        }
} 
&lt;/CODE&gt;&lt;/PRE&gt;
&lt;H2&gt;
&lt;A name="examples-4" class="anchor" href="#examples-4"&gt;&lt;/A&gt;Examples&lt;/H2&gt;
&lt;H3&gt;
&lt;A name="get-the-morpheus-windows-agent-service-status-and-tcp-socket-details-5" class="anchor" href="#get-the-morpheus-windows-agent-service-status-and-tcp-socket-details-5"&gt;&lt;/A&gt;Get the Morpheus Windows Agent service status and TCP Socket details&lt;/H3&gt;
&lt;P&gt;To get the current status of the Morpheus Agent Service along with the associated TCP Socket details returning the output as a json string use&lt;/P&gt;
&lt;PRE style="background : #f0f1f2;"&gt;&lt;CODE class="lang-auto"&gt;$info = Get-MorpheusAgentSocketStatus -AsJson
$info
{
    "adminAccess":  true,
    "machineName":  "SP54-W-1047",
    "agentStatus":  "OK",
    "agentState":  "Running",
    "agentPid":  8104,
    "agentSockets":  {
                         "state":  "Established",
                         "creationTime":  "2023-03-10T17:39:03",
                         "localAddress":  "10.32.23.116",
                         "localPort":  51409,
                         "remoteAddress":  "10.32.23.194",
                         "remotePort":  443
                     }
}
&lt;/CODE&gt;&lt;/PRE&gt;
&lt;H3&gt;
&lt;A name="get-the-current-agent-config-file-6" class="anchor" href="#get-the-current-agent-config-file-6"&gt;&lt;/A&gt;Get the current Agent config file&lt;/H3&gt;
&lt;P&gt;To See the current Morpheus Windows Agent config file (WindowsAgent.exe.config) use the following function.&lt;/P&gt;
&lt;PRE style="background : #f0f1f2;"&gt;&lt;CODE class="lang-auto"&gt;Get-MorpheusAgentConfig

&amp;lt;?xml version="1.0" encoding="utf-8"?&amp;gt;
&amp;lt;configuration&amp;gt;
  &amp;lt;appSettings&amp;gt;
    &amp;lt;add key="ServiceName" value="Morpheus Windows Agent" /&amp;gt;
    &amp;lt;add key="ApiKey" value="708dbe73-9509-4858-aca5-38f1f276abdb" /&amp;gt;
    &amp;lt;add key="Host" value="https://sp-morpheus.mymorpheusappliance.somewhere/" /&amp;gt;
    &amp;lt;add key="VmMode" value="true" /&amp;gt;
    &amp;lt;add key="LogLevel" value="0" /&amp;gt;
    &amp;lt;!-- 0 = debug; 1 = info; 2 = warn; 3 = error; 4 = off;--&amp;gt;
    &amp;lt;add key="ClientSettingsProvider.ServiceUri" value="" /&amp;gt;
  &amp;lt;/appSettings&amp;gt;
  &amp;lt;startup&amp;gt;
    &amp;lt;supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /&amp;gt;
  &amp;lt;/startup&amp;gt;
  &amp;lt;system.web&amp;gt;
    &amp;lt;membership defaultProvider="ClientAuthenticationMembershipProvider"&amp;gt;
      &amp;lt;providers&amp;gt;
        &amp;lt;add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" /&amp;gt;
      &amp;lt;/providers&amp;gt;
    &amp;lt;/membership&amp;gt;
    &amp;lt;roleManager defaultProvider="ClientRoleProvider" enabled="true"&amp;gt;
      &amp;lt;providers&amp;gt;
        &amp;lt;add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" /&amp;gt;
      &amp;lt;/providers&amp;gt;
    &amp;lt;/roleManager&amp;gt;
  &amp;lt;/system.web&amp;gt;
&amp;lt;/configuration&amp;gt;
&lt;/CODE&gt;&lt;/PRE&gt;
&lt;H3&gt;
&lt;A name="set-the-agent-logging-level-to-1-info-and-delay-a-restart-of-the-morpheus-windows-agent-service-7" class="anchor" href="#set-the-agent-logging-level-to-1-info-and-delay-a-restart-of-the-morpheus-windows-agent-service-7"&gt;&lt;/A&gt;Set the Agent Logging Level to 1 (Info) and delay a restart of the Morpheus Windows Agent service&lt;/H3&gt;
&lt;P&gt;And finally, to set the Morpheus Windows Agent Logging level to Info ($LogLevel=1) , performing a 60 second delayed restart of the Morpheus Windows Agent service use the example below.&lt;BR /&gt;
&lt;STRONG&gt;$newConfig&lt;/STRONG&gt; is the contents of the updated MorpheusAgent.exe.config.&lt;BR /&gt;
The function has detached a process with pid &lt;STRONG&gt;4760&lt;/STRONG&gt; which will restart the Morpheus Windows Agent service in 60 seconds.&lt;/P&gt;
&lt;PRE style="background : #f0f1f2;"&gt;&lt;CODE class="lang-auto"&gt;$newConfig = Set-MorpheusAgentConfig -LogLevel 1 -RestartAgent
Delaying Agent Service Restart - detaching process 4760
Returning Updated Agent Config ...

$newConfig
&amp;lt;?xml version="1.0" encoding="utf-8"?&amp;gt;
&amp;lt;configuration&amp;gt;
  &amp;lt;appSettings&amp;gt;
    &amp;lt;add key="ServiceName" value="Morpheus Windows Agent" /&amp;gt;
    &amp;lt;add key="ApiKey" value="708dbe73-9509-4858-aca5-38f1f276abdb" /&amp;gt;
    &amp;lt;add key="Host" value="https://sp-morpheus.mymorpheusappliance.somewhere/" /&amp;gt;
    &amp;lt;add key="VmMode" value="true" /&amp;gt;
    &amp;lt;add key="LogLevel" value="1" /&amp;gt;
    &amp;lt;!-- 0 = debug; 1 = info; 2 = warn; 3 = error; 4 = off;--&amp;gt;
    &amp;lt;add key="ClientSettingsProvider.ServiceUri" value="" /&amp;gt;
  &amp;lt;/appSettings&amp;gt;
  &amp;lt;startup&amp;gt;
    &amp;lt;supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /&amp;gt;
  &amp;lt;/startup&amp;gt;
  &amp;lt;system.web&amp;gt;
    &amp;lt;membership defaultProvider="ClientAuthenticationMembershipProvider"&amp;gt;
      &amp;lt;providers&amp;gt;
        &amp;lt;add name="ClientAuthenticationMembershipProvider" type="System.Web.ClientServices.Providers.ClientFormsAuthenticationMembershipProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" /&amp;gt;
      &amp;lt;/providers&amp;gt;
    &amp;lt;/membership&amp;gt;
    &amp;lt;roleManager defaultProvider="ClientRoleProvider" enabled="true"&amp;gt;
      &amp;lt;providers&amp;gt;
        &amp;lt;add name="ClientRoleProvider" type="System.Web.ClientServices.Providers.ClientRoleProvider, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" serviceUri="" cacheTimeout="86400" /&amp;gt;
      &amp;lt;/providers&amp;gt;
    &amp;lt;/roleManager&amp;gt;
  &amp;lt;/system.web&amp;gt;
&amp;lt;/configuration&amp;gt;

&lt;/CODE&gt;&lt;/PRE&gt;</description>
      <pubDate>Fri, 10 Mar 2023 14:20:54 GMT</pubDate>
      <guid>https://community.hpe.com/t5/hpe-morpheus-enterprise-software/morpheus-windows-agent-useful-powershell-functions/m-p/7249822#M2996</guid>
      <dc:creator />
      <dc:date>2023-03-10T14:20:54Z</dc:date>
    </item>
    <item>
      <title>Re: Morpheus Windows Agent - Useful Powershell Functions</title>
      <link>https://community.hpe.com/t5/hpe-morpheus-enterprise-software/morpheus-windows-agent-useful-powershell-functions/m-p/7249823#M2997</link>
      <description>&lt;P&gt;Thank you&lt;/P&gt;</description>
      <pubDate>Tue, 04 Apr 2023 08:51:16 GMT</pubDate>
      <guid>https://community.hpe.com/t5/hpe-morpheus-enterprise-software/morpheus-windows-agent-useful-powershell-functions/m-p/7249823#M2997</guid>
      <dc:creator>Basharat</dc:creator>
      <dc:date>2023-04-04T08:51:16Z</dc:date>
    </item>
    <item>
      <title>Re: Morpheus Windows Agent - Useful Powershell Functions</title>
      <link>https://community.hpe.com/t5/hpe-morpheus-enterprise-software/morpheus-windows-agent-useful-powershell-functions/m-p/7249824#M2998</link>
      <description />
      <pubDate>Wed, 06 Sep 2023 12:41:43 GMT</pubDate>
      <guid>https://community.hpe.com/t5/hpe-morpheus-enterprise-software/morpheus-windows-agent-useful-powershell-functions/m-p/7249824#M2998</guid>
      <dc:creator />
      <dc:date>2023-09-06T12:41:43Z</dc:date>
    </item>
    <item>
      <title>Re: Morpheus Windows Agent - Useful Powershell Functions</title>
      <link>https://community.hpe.com/t5/hpe-morpheus-enterprise-software/morpheus-windows-agent-useful-powershell-functions/m-p/7249825#M2999</link>
      <description>&lt;P&gt;How to install Morpheus Windows Agent manually&lt;BR /&gt;
??&lt;/P&gt;</description>
      <pubDate>Fri, 31 Mar 2023 06:55:44 GMT</pubDate>
      <guid>https://community.hpe.com/t5/hpe-morpheus-enterprise-software/morpheus-windows-agent-useful-powershell-functions/m-p/7249825#M2999</guid>
      <dc:creator>Basharat</dc:creator>
      <dc:date>2023-03-31T06:55:44Z</dc:date>
    </item>
    <item>
      <title>Re: Morpheus Windows Agent - Useful Powershell Functions</title>
      <link>https://community.hpe.com/t5/hpe-morpheus-enterprise-software/morpheus-windows-agent-useful-powershell-functions/m-p/7249826#M3000</link>
      <description />
      <pubDate>Wed, 06 Sep 2023 12:40:53 GMT</pubDate>
      <guid>https://community.hpe.com/t5/hpe-morpheus-enterprise-software/morpheus-windows-agent-useful-powershell-functions/m-p/7249826#M3000</guid>
      <dc:creator />
      <dc:date>2023-09-06T12:40:53Z</dc:date>
    </item>
    <item>
      <title>Re: Morpheus Windows Agent - Useful Powershell Functions</title>
      <link>https://community.hpe.com/t5/hpe-morpheus-enterprise-software/morpheus-windows-agent-useful-powershell-functions/m-p/7249827#M3001</link>
      <description>&lt;P&gt;Hi Hussain,&lt;BR /&gt;
you need to download the agent install script and run manually on target host.&lt;BR /&gt;
Here is a link to the docs for manually installing the agent.&lt;A href="https://docs.morpheusdata.com/en/latest/troubleshooting/Morpheus_Agent.html#agent-install-methods" class="inline-onebox"&gt;Morpheus Agent Install Troubleshooting — Morpheus Docs documentation&lt;/A&gt;&lt;BR /&gt;
Thanks&lt;BR /&gt;
Mousami&lt;/P&gt;</description>
      <pubDate>Tue, 04 Apr 2023 08:48:18 GMT</pubDate>
      <guid>https://community.hpe.com/t5/hpe-morpheus-enterprise-software/morpheus-windows-agent-useful-powershell-functions/m-p/7249827#M3001</guid>
      <dc:creator />
      <dc:date>2023-04-04T08:48:18Z</dc:date>
    </item>
  </channel>
</rss>

