Scripting Database Objects with Advanced Scripting Options in PowerShell
>[reflection.assembly]::LoadWithPartialName(“Microsoft.SqlServer.Smo”)
>$so = new-object Microsoft.SqlServer.Management.Smo.ScriptingOptions
Now that you’ve got the assembly loaded and a variable created as a ScriptingOptions type, you can begin to use your new variable and set its properties. We’ll start by simply inspecting the properties. You can do this by simply typing the name of the variable to print its contents to the screen.
>$so
The results will look like the screenshot below, and you’ll notice the same options from the screenshot of the wizard above.
>$so.IncludeDatabaseContext = 1
>$so.ScriptDrops = 1
>$so = NoFilegroup = 1
Those options are pretty easy to understand, so I won't go into detail here about them. And now that we’ve got the options set that we want, we can use them in our scripting command from the last article like this:
>dir | %{$_.Script($so) | out-file c:\Tables.txt -append}
Notice that all I did was put the ‘$so’ inside the () for the script method call. For that portion of it, there’s really nothing more to it than that. The process isn’t perfect though. SMO itself doesn’t handle the commands perfectly, so some properties don’t seem to have any effect on the outcome of your script. A good example is the ‘ScriptBatchTerminator’ property. Setting this property to true is supposed to script a ‘GO’ statement between each of the objects, but it doesn’t. In fact, it doesn’t do anything that I can see. So what you end up doing is writing the GO statement yourself. Remember the script for the StoredProcedures from the last article? Well it actually won’t run. See, a create statement has to be the first statement in a batch which means that without the GO statement, everything after the first object will cause an error. This is an easy problem to solve. Now, we shouldn’t have to do this, but it is what it is, right? Here’s how you fix this issue:
>dir | %{$_.Script() | out-file c:\Tables.txt –append; “GO” | out-file c:\Tables.txt -append}
Did you see what I did there? After the first ‘-append’ I put a semi-colon, which terminated the line. It allows me to put multiple commands on the same line. We use this same trick in T-SQL all the time. Then I hardcoded the text “GO” and piped it to the same Tables.txt file with another ‘-append’ flag. So all I’m doing is after each script, I’m printing a GO statement on its own line. This is what SMO was supposed to do for us, but didn’t. So you have to be careful sometimes and test that the SMO provider is doing what you expect it to do. Most of the time it’ll serve you well though.
No comments:
Post a Comment