Here’s a quick script to script out all database objects using powershell. This was adapted (heavily) from the Hey Scripting Guy! blog script here. This also stores the password credential in a file on the server. You’ll need to generate the file before running the script. Remember to generate the file under the account that will be executing the script, as the contents of the file will be encrypted using the account that generated it. Use this script to create the file:

Ensure you have 7-zip installed, obviously. I adapted this from some other code I found on the internets, but unfortunately I can’t find the original post, so apologies for not giving the original author props.

If you see an error like this when you execute a powershell job in sql server, it is due to an errant cls in your powershell script. Remove the cls and it should execute correctly. There is no screen to clear, hence it errors out.

A job step received an error at line 3 in a PowerShell script. The corresponding line is ‘$space.ForegroundColor = $host.ui.rawui.ForegroundColor’. Correct the script and reschedule the job. The error information returned by PowerShell is: ‘Exception setting "ForegroundColor": "Cannot convert null to type "System.ConsoleColor" due to invalid enumeration values. Specify one of the following enumeration values and try again. The possible enumeration values are "Black, DarkBlue, DarkGreen, DarkCyan, DarkRed, DarkMagenta, DarkYellow, Gray, DarkGray, Blue, Green, Cyan, Red, Magenta, Yellow, White"." ‘.