I use a T-SQL command which I found here to get the fragmentation of my database tables. When I execute the T-SQL in the Management Studio, everything works. If I use it inside PowerShell, I get the following error (translated from German):
Exception when calling "ExecuteReader" with 0 Argument(s):
"Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'."
In Zeile:17 Zeichen:6
+ $Result = $cmd.ExecuteReader()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
This is the part of my script which throws the error
foreach ($table in $tables)
{
$Data = New-Object System.Data.DataTable
$cmd = New-Object System.Data.SqlClient.SqlCommand
$getFragRate = "
-- SQL Command von Microsoft um die Index Fragmentation zu überprüfen
USE Logik;
GO
SELECT a.index_id, name, avg_fragmentation_in_percent
FROM sys.dm_db_index_physical_stats (DB_ID(N'Logik'), OBJECT_ID(N'$($table)'), NULL, NULL, NULL) AS a
JOIN sys.indexes AS b ON a.object_id = b.object_id AND a.index_id = b.index_id;
GO
"
$cmd.CommandText = $getFragRate
$cmd.Connection = $con
$Result = $cmd.ExecuteReader()
$Data.Load($Result)
$Data
}
Why does this error occur?
The User I use to do this has sysadmin, db_ddladmin and db_owner permission.
Edit: Another T-SQL Command to get all tables of my database worked without a problem from PowerShell.
GO is NOT a T-SQL command - therefore you cannot have it in T-SQL statements being executed from PowerShell.
GO is a batch separator used by SQL Server Management Studio.
You need to break up that statement into several individual statements yourself and execute them one by one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With