title: Combining a SQL database backup script/query with powershell
body: <p>I am trying to combine this SQL backup script/query that I have with my power shell script and I'm not sure how to convert it as I don't know much about SQL only Powershell. I have been trying to use <code>invoke-sqlcmd</code> before every line in the script, but I don't think that's how you do it. I don't fully understand the syntax of <code>invoke-sqlcmd</code>Micrsoft was not helpful. This is the SQL database backup script I need to use: </p>
  
  <pre><code>DECLARE @name VARCHAR(50) -- database name  
  
  DECLARE @path VARCHAR(256) -- path for backup files  
  DECLARE @fileName VARCHAR(256) -- filename for backup  
  DECLARE @fileDate VARCHAR(20) -- used for file name
  
  
  -- specify database backup directory
  SET @path = 'F:\Backups\'  
  
  
  -- specify filename format
  SELECT @fileDate = CONVERT(VARCHAR(20),GETDATE(),112) 
  
  
  DECLARE db_cursor CURSOR FOR  
  SELECT name 
  FROM master.dbo.sysdatabases 
  WHERE name IN ('dbname','dbname','dbname','dbname','dbname','dbname')  -- exclude these databases
  
  
  OPEN db_cursor   
  FETCH NEXT FROM db_cursor INTO @name   
  
  
  WHILE @@FETCH_STATUS = 0   
  BEGIN   
         SET @fileName = @path + @name + '_' + @fileDate + '.BAK'  
         BACKUP DATABASE @name TO DISK = @fileName
         WITH COMPRESSION
  
  
         FETCH NEXT FROM db_cursor INTO @name   
  END   
  
  
  CLOSE db_cursor   
  DEALLOCATE db_cursor
  </code></pre>
  
  <p>Is it correct to just add <code>invoke-sqlcmd</code> in the front of every line of sql query? Also whatever solution there is to this needs to be compatible with Windows Server 2008 and up. I thought it might be as easy as just putting the whole script in quotes with <code>invoke-sqlcmd</code>, but I doubt it. Whenever I google this the answers are way too complex and don't really explain exactly how the SQL ties into Powershell. They just kind of assume you know. The only field in this script that needs to change is the path when you run it on SQL studio.</p>