Home Forums Programming Powershell Need a way to script out LinkedServers on a SQL 2005\2008 boxes but place the script in seperate files. RE: Need a way to script out LinkedServers on a SQL 2005\2008 boxes but place the script in seperate files.

  • Works on Windows 8 with SQL 2012 or 2008 R2:

    <# SYNOPSIS

    Generates create scripts for all LinkedServers.

    DESCRIPTION

    PowerShell script using SQL Provider to script out all LinkedServers.

    NOTES

    Requires: PowerShell Version 2.0, SMO assembly

    #>

    param ($server, $serverinstance, $database, $folder)

    # Import SQL 2012 module:

    Import-Module sqlps

    #if you're still using SQL 2008/R2, comment the above call to Import-Module and load the 2008 provider instead:

    #Add-PSSnapin SqlServerProviderSnapin100 -ErrorAction SilentlyContinue

    # Configuration data

    #[string] $server = "SERVERNAME"; # SQL Server Name

    #[string] $serverinstance = "SERVERNAME\DEV"; # SQL Server Instance Database with the tables to script out.

    #[string] $database = "DBNAME"; # Database with the tables to script out.

    #[string] $folder = "S:\DBA"; # Path to export to

    Write-Output ((Get-Date -format yyyy-MM-dd_HH-mm-ss) + ": *** LinkedServers Started ***");

    $folder=(Join-Path (Join-Path (Join-Path $folder $server) $serverinstance) "_ServerObjects")

    if(!(Test-Path $folder)) {New-Item -ItemType directory -Path $folder}

    foreach($linkedServer in (Get-ChildItem SQLSERVER:\SQL\$server\$Serverinstance\LinkedServers))

    {

    $linkedServer.Script() | Out-File (Join-Path $folder ($linkedServer.Name.Replace(".","_").Replace("\","$") + ".sql"))

    }

    Write-Output ((Get-Date -format yyyy-MM-dd_HH-mm-ss) + ": !!! LinkedServers Finished !!!");

    Write-Output " "

    There are no special teachers of virtue, because virtue is taught by the whole community.
    --Plato