sql server – Issue with Scripting out Subscriptions using Powershell


I am trying to script out the replication objects via Powershell using Microsoft.SqlServer.Rmo.dll. The replication type is transactional with push subscriptions.

I have been able to script out publication, articles, PALs but not able to script out publisher side subscriptions.

$scriptargs =(Microsoft.SqlServer.Replication.ScriptOptions)::Creation `
-bor  (Microsoft.SqlServer.Replication.ScriptOptions)::IncludeCreateLogreaderAgent `
-bor  (Microsoft.SqlServer.Replication.ScriptOptions)::IncludeCreateMergeAgent `
-bor  (Microsoft.SqlServer.Replication.ScriptOptions)::IncludeCreateQueuereaderAgent `
-bor  (Microsoft.SqlServer.Replication.ScriptOptions)::IncludePublicationAccesses `
-bor  (Microsoft.SqlServer.Replication.ScriptOptions)::IncludeArticles `
-bor  (Microsoft.SqlServer.Replication.ScriptOptions)::IncludePublisherSideSubscriptions`   #one way tried to get the subscriptions
-bor  (Microsoft.SqlServer.Replication.ScriptOptions)::IncludeGo

foreach($replicateddatabase in $repsvr.ReplicationDatabases)
{
    if ($replicateddatabase.TransPublications.Count -gt 0)
    {
        foreach($tranpub in $replicateddatabase.TransPublications)
        {
            **(string) $myscript=$tranpub.script($scriptargs)**   #Errors out here
            writetofile $myscript $filename 0
        }
    }
}

enter image description here

The other way I tried is exclude IncludePublisherSideSubscriptions from Scriptoptions and tried to script out directly using the following statement

foreach($replicateddatabase in $repsvr.ReplicationDatabases)
{
    if ($replicateddatabase.TransPublications.Count -gt 0)
    {
        foreach($tranpub in $replicateddatabase.TransPublications)
        { 
            (string) $subs=$tranpub.TransSubscriptions.script($scriptargs)   #another way but same error
            writetofile $subs $filename 0
        }
    }
}

The third way I tried:

$repsvr.ReplicationDatabases.TransPublications.TransSubscriptions.Script($scriptargs)

Of all, I found the following link to be very helpful where my code is mostly based on but just got stuck in the scripting out of publisher side subscriptions. I appreciate your help.

Script SQL Server Replication With PowerShell