How to script server level objects in sql server?
One way to script server-level objects is with SMO and PowerShell. Below is a PS example that uses the SMO assembly included with SSMS to script server endpoints and triggers. SMO is also available on NuGet to avoid the dependency on an SSMS install.
# generate scripts for server-scoped object collection
Function Create-ServerObjectScripts($serverCollection, $rootFolder, $typeName) {

    # exclude system objects
    $serverCollection = $serverCollection | Where-Object {
        $_.IsSystemObject -eq $false -or $_.IsSystemObject -eq $null
    }

    if($serverCollection.Count -eq 0) {
        return
    }

    Write-Host &quot;Scripting $typeName for server $($server.Name)...&quot;

    $scriptingOptions = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions
    $scriptingOptions.IncludeIfNotExists = $true
    # specify desired SQL version below
    $scriptingOptions.TargetServerVersion = [Microsoft.SqlServer.Management.Smo.SqlServerVersion]::Version130
    $scriptingOptions.AppendToFile = $true
    $scriptingOptions.ToFileOnly = $true

    foreach ($serverObject in $serverCollection) {
        $scriptingOptions.FileName = &quot;$rootFolder/$typeName.sql&quot;
        [void](New-Item -Path &quot;$($scriptingOptions.FileName)&quot; -ItemType &quot;file&quot; -Force)
        $serverObject.Script($scriptingOptions)
    }

}

# ############
# ### MAIN ###
# ############

try {

    $serverName = &quot;YourServer&quot;
    $scriptRootFolder = &quot;C:\Scripts\YourServer&quot;

    $smoAssemblyDirectory = &quot;C:\Program Files (x86)\Microsoft SQL Server Management Studio 18\Common7\IDE&quot;
    Add-Type -Path &quot;$smoAssemblyDirectory/Microsoft.SqlServer.SMO.dll&quot;

    $server = New-Object Microsoft.SqlServer.Management.Smo.Server($ServerName)
    if ($server.ServerType -eq $null) {
        throw &quot;Unable to connect to server '$ServerName' &quot;
    }

    Create-ServerObjectScripts -serverCollection $server.Endpoints -rootFolder &quot;$scriptRootFolder&quot; -typeName &quot;Endpoints&quot;
    Create-ServerObjectScripts -serverCollection $server.Triggers -rootFolder &quot;$scriptRootFolder&quot; -typeName &quot;Triggers&quot;

    Write-Host &quot;Scripting completed&quot;

}
catch {
    throw
}