Use sqlcmd in Powershell-less memory utilization

Mario2286 441 Reputation points
2021-06-18T07:41:34.277+00:00

Below is the scripts I m using to loop the servers and databases in multiple servers. One server will have more than 10 databases and I m using this PS scripts to generate the information and output to CSV but I m having high memory utilization when using this PS scripts. Did anyone know how to use sqlcmd include in this PS scripts because I believe generate data using sqlcmd and output to csv will have less memory utilization

 $InstanceList = "DESKTOP-6U9IKQD", "DESKTOP-6U9IKQD\BM"
 $filepath = "C:\b1\script1.sql" 
 $Path = "C:\b1\Server"
 $InstanceList | ForEach-Object{

     $databases = invoke-sqlcmd -ServerInstance $_ -Database "master" -Query "select name from sys.databases where name like 'adventureworks%'"       
     foreach ($database in $databases) {
         $outfile = $Path,$_.replace("\","_")+"txt" -join "."
         "Database name: $($database.name)" | Out-File -FilePath $outfile -Append
         Invoke-Sqlcmd -ServerInstance  $_ -Database $database.name -InputFIle $filepath | Out-File -FilePath $outfile -Append       
     }
 }
Windows for business | Windows Server | User experience | PowerShell
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. AmeliaGu-MSFT 14,011 Reputation points Microsoft External Staff
    2021-06-18T08:50:59.703+00:00

    Hi Mario2286-5314,

    Invoke-Sqlcmd -ServerInstance $_ -Database $database.name -InputFIle $filepath | Out-File -FilePath $outfile -Append

    It seems you have use sqlcmd in the Powershell SQLPS module. Please refer to Invoke-Sqlcmd which might help. And it seems it is a known issue that memory usage is high when using invoke-sqlcmd in the Powershell. Please refer to PowerShell Invoke-SqlCmd and memory usage and Creating large CSVs -- running into issue with RAM usage which might help.

    You also can try to use command Invoke-DbaQuery in the Powershell dbatools.

    Best Regards,
    Amelia


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  2. Mario2286 441 Reputation points
    2021-06-19T14:26:36.43+00:00

    @Anonymous are you able to help on this

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.