Dynamic Conditions with Invoke-Expression . PowerShell Rocks !!!


I am working in a old script to check and report the index fragmentation and in my test I have a SQL Server 2000 box.

The property in the SMO before SQL Server 2005 is called LogicalFragmentation and after SQL Server 2005 is Average Fragmentation. I had to figure out how to dynamic change the condition , to no have to create 2 blocks of test.

Also the SMO in the pipeline does not have the property properties to check if the property exists or not. 

I have a variable to check what SQL Server version are in the currently process and then I create the condition. To check, Invoke-expression evaluates for me.

If ($SQLServerVersion -gt 8) {
$ConditionIf = '($_.AverageFragmentation -ge 1 -and $_.AverageFragmentation -le 30 -and $_.Pages -ge 1000)'
$ConditionElseIf ='($_.AverageFragmentation -gt 30 -and $_.Pages -ge 1000)'
} else {
$ConditionIf = '($_.LogicalFragmentation -ge 1 -and $_.LogicalFragmentation -le 30 -and $_.Pages -ge 1000)'
$ConditionElseIf = '($_.LogicalFragmentation -gt 30 -and $_.Pages -ge 1000)'
}
if (invoke-expression -Command $ConditionIf) {
###do what you need to do
} elseif ( invoke-expression -Command $ConditionElseIf) {
###do what you need to do
}

Nice uhh !!!

About Laerte Junior

Laerte Junior Laerte Junior is a SQL Server specialist and an active member of WW SQL Server and the Windows PowerShell community. He also is a huge Star Wars fan (yes, he has the Darth Vader´s Helmet with the voice changer). He has a passion for DC comics and living the simple life. "May The Force be with all of us"
This entry was posted in Algo que Esqueci de Categorizar. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s