I have my method which (unless I did something stupid) worked perfectly yesterday for exporting to csv. However, today I keep getting this erro:
Exception calling "Fill" with "1" argument(s): "ExecuteReader: CommandText property has not been initialized"
$rowCount=$SqlAdapter.Fill($dt)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : InvalidOperationException
And this is my syntax:
$server = "serverinstance"
$database = "databaseinstance"
$savefile = "C:\Test\sqlresults.csv"
$SelectQuery = "Select Top 1 * from madeuptable"
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection=New-Object System.Data.SqlClient.SqlConnection($connectionString)
$cmd=$connection.CreateCommand()
$cmd.CommandText = $SelectQuery
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
$dt = New-Object System.Data.DataTable
$rowCount=$SqlAdapter.Fill($dt)
if ($rowCount -gt 0) { $dt| Export-Csv $savefile -encoding UTF8 -NoTypeInformation }
$connection.Close()
Try creating the SqlDataAdaper using the query and the connection instead (and drop the cmd).
Example:
$SqlAdapter = new-object system.data.sqlclient.sqldataadapter ($SelectQuery, $connection)
I would check your $server and $database variables. I just ran your script against my own SQL server and it worked just fine for me.
EDIT:
Here is what I ran:
$server = "FAR-L2484\HOLDER_SQL" ## Hostname\InstanceID
$database = "MASTER"
$savefile = "C:\Test\sqlresults.csv"
$SelectQuery = "SELECT * FROM information_schema.tables"
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connectionString = [string]::Format($connectionTemplate, $server, $database)
$connection=New-Object System.Data.SqlClient.SqlConnection($connectionString)
$cmd=$connection.CreateCommand()
$cmd.CommandText = $SelectQuery
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($cmd)
$dt = New-Object System.Data.DataTable
$rowCount=$SqlAdapter.Fill($dt)
$dt| Export-Csv $savefile -encoding UTF8 -NoTypeInformation
$connection.Close()
and this is what I got in C:\test\sqlresults.csv
"TABLE_CATALOG","TABLE_SCHEMA","TABLE_NAME","TABLE_TYPE"
"master","dbo","spt_fallback_db","BASE TABLE"
"master","dbo","spt_fallback_dev","BASE TABLE"
"master","dbo","spt_fallback_usg","BASE TABLE"
"master","dbo","spt_values","VIEW"
"master","dbo","spt_monitor","BASE TABLE"
"master","dbo","MSreplication_options","BASE TABLE"
Related
while i passed the value from splunk by running this script and inserted into database, i got below error :
Exception calling "ExecuteNonQuery" with "0" argument(s): "String or binary data would be truncated. The statement has been terminated."
could you help to suggest how to fix that issue?
passing date time value from splunk is
$jsonObj.result.F10="2.312" $jsonObj.result.F11="3.212" $jsonObj.result.F15="6.412" $jsonObj.result.datetime = "2021-12-29 19:00:00" and in database table date time column value also same format "yyyy-mm-dd hh:mm:ss"
below is my code:
param ($jsonContent)
$jsonObj = $jsonContent | ConvertFrom-Json
write-host $jsonObj.result.F10
write-host $jsonObj.result.F11
write-host $jsonObj.result.F15
write-host $jsonObj.result.datetime
$serverName = "FSMSSTEST132,3067"
$databaseName = "ITReport"
$tableName = "dbo.SPK_ITMetricsChart"
$YourUserID = "MES123";
$YourPassword="Asd123";
$hostName = "$jsonObj.result.F10","$jsonObj.result.F11" ,"$jsonObj.result.F15"
$value1 = "Delivery"
$time = $jsonObj.result.datetime
$site = "F10N","F11","F15"
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$serverName';database='$databaseName';User ID= '$YourUserID'; Password= '$YourPassword'"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
for($i=0;$i -lt $hostName.Length; $i++)
{
$insertquery="
INSERT INTO $tableName
([Datetime],[Value],[Category],[Site])
VALUES
('$time','$($hostName[$i])','$value1','$($site[$i])')"
$Command.CommandText = $insertquery
$Command.ExecuteNonQuery()
}
$Connection.Close();
Working with an API, I believe I need to create a WebserviceProxy object and add the property "ExternalID" to it, but I can't seem to get the right code to do that.
This is the error I am getting...
Cannot convert argument "0", with value: "002374E4DBEC", for "LaunchClientApplication" to type "WebServiceProxy.ExternalId": "Cannot convert the "002374E4DBEC" value of type "System.String" to type "WebServiceProxy.ExternalId"."
At C:\PowerShellScripts\Crawler.ps1:72 char:50
+ $guid = $OSSNBranchWS.LaunchClientApplication <<<< ($FTCSTBExternalID.Ext_Device_ID,$applicationUri)
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
This is my code...
### Crawler
### SQL Login
$SQLUser = "USERNAME"
$SQLPassword = "PASSWORD"
$SQLServer = "SQLSERVER\DB"
$SQLDBName = "SQLDB"
$SqlQuery = "select a.externalID as Acct_Number, d.externalId as Ext_Device_ID
from bm_account a inner join
bm_device d on a.accountId = d.accountId
where a.externalId='9999999999'
order by Acct_Number,Ext_Device_ID"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID = $SQLUser; Password = $SQLPassword;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$rowCount = $SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$FTCSTBExternalIDs = $DataSet.Tables[0]
$Domain = 'DM'
$UserName = 'USERNAME'
$Password = 'PASSWORD'
$UsernameDomain = $Domain+'\'+$UserName
$SecurePassword=ConvertTo-SecureString -String $Password -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential $UsernameDomain,$SecurePassword
$OSSNBranchWS = New-WebServiceProxy -Uri "http://mediaroomserver/ossNotificationsWS/UI.asmx?wsdl" -Namespace WebServiceProxy -Credential $Credential
$applicationUri = "page:http://mediaroomserver.com/FTCPFApps/STBScrollingMessages/MediaroomPage.aspx"
ForEach ($FTCSTBExternalID in $FTCSTBExternalIDs)
{
$msg_time = Get-Date -UFormat "%Y-%m-%d %r"
$message = $msg_time+' - FTC Account Number: "'+$FTCSTBExternalID.Acct_Number+'", Device ID: "'+$FTCSTBExternalID.Ext_Device_ID+'"' | Out-File $log_file -Append
$guid = $OSSNBranchWS.LaunchClientApplication($FTCSTBExternalID.Ext_Device_ID,$applicationUri)
}
It looks like I need to change "$FTCSTBExternalID" into the WebserviceProxy object and add the property "ExternalID" to it, and add "$FTCSTBExternalID.Ext_Device_ID" to it. But I cannot seem to get that right.
Any help would be greatly appreciated.
Thanks.
I am trying to fetch count of table from SQL server by connecting using Powershell, but I am getting the below error message, but if I just do select on the table instead of count then the same code is returning results, please suggest as I am not getting a solution to this problem.
Error Message:
Exception calling "Fill" with "1" argument(s): "Execution Timeout
Expired. The timeout period elapsed prior to completion of the
operation or the server is not responding."
+ $DataAdapter.Fill($Dataset)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException
Script:
[string] $Server= "Server_nm"
[string] $Database = "DB_nm"
[string] $UserSqlQuery = $("SELECT count(1) AS cnt FROM [tbl]")
##$resultsDatatable = ExecuteSqlQuery $Server $Database $UserSqlQuery
function GenericSqlQuery ($Server, $Database, $SQLQuery) {
$Datatable = New-Object System.Data.DataTable
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $SQLQuery
$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $Command
$Dataset = new-object System.Data.Dataset
$DataAdapter.Fill($Dataset)
$Connection.Close()
return $Dataset.Tables[0]
} $resultsDatatable = GenericSqlQuery $Server $Database $UserSqlQuery
#validate we got data
Write-Host ("The table contains: " + $resultsDatatable.Rows.Count + " rows")
You can use the Invoke-Sqlcmd function instead.
# initialize Variables
[string] $Server= "Server_nm"
[string] $Database = "DB_nm"
[string] $UserSqlQuery = $("SELECT count(1) AS cnt FROM [tbl]")
# Invoke-SqlCmd
$resultsDatatable = Invoke-Sqlcmd -ServerInstance $Server -Database $Database -Query $UserSqlQuery
# validate we got data
Write-Host ("The table contains: " + $resultsDatatable.cnt + " rows")
I'm using Powershell 4 and attempting to write data into a SQL Server 2012.
Here is the script I am using
Add-Type -AssemblyName System.Data
$conn = New-Object System.Data.SqlClient.SqlConnection↵
$conn.ConnectionString = "Data Source=<SQLSERVER>;Initial Catalog=SYSINFO;Integrated Security=true;"
$conn.open()
$cmd = New-Object System.Data.SqlClient.SqlCommand
The error I am getting is:
New-Object : Cannot find type [System.Data.SqlClient.SqlConnection] : verify that the assembly containing this type is loaded.
I assuemd the first line (Add-Type) would load all the required assemblies under System.Data
Am I missing somethign obvious?
You can do it this way:
$Server = 'theServer'
$database = 'theDatabase'
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server=$($Server);database=$($Database);trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = 'SELECT TOP 5 * FROM yourTable ORDER BY 1 DESC'
$Reader = $Command.ExecuteReader()
$Datatable = New-Object System.Data.DataTable
$Datatable.Load($Reader)
$Datatable | Export-Csv report.csv -NoTypeInformation
$Connection.Close()
I am trying to use PowerShell and Windows Search to get some statistics of my disk usage. This is what I came up for so now:
$sql = "SELECT System.FileExtension, System.Size FROM SYSTEMINDEX WHERE DIRECTORY = 'C:\Users\...\Documents' AND System.FileExtension = '.docx'"
$provider = "provider=search.collatordso;extended properties=’application=windows’;"
$connector = New-Object System.Data.OleDb.OleDbDataAdapter -Argument $sql, $provider
$dataset = New-Object System.Data.DataSet
if ($connector.fill($dataset)) {
$res = $dataset.Tables[0]
$res | Group-Object System.FileExtension |
Select-Object System.FileExtension,
#{Name='Total';Expression={($_.Group | Measure-Object SYSTEM.Size -Sum).Sum}} |
Format-Table
}
This works, but it looks kind of ugly. I also found and tried this:
$sql = "SELECT System.Size FROM SYSTEMINDEX WHERE DIRECTORY = 'C:\Users\...\Documents' AND System.FileExtension = '.docx'"
$provider = "provider=search.collatordso;extended properties=’application=windows’;"
$connector = New-Object System.Data.OleDb.OleDbDataAdapter -Argument $sql, $provider
$dataset = New-Object System.Data.DataSet
if ($connector.fill($dataset)) {
$dataset.Tables[0].Compute("Sum(SYSTEM.Size)")
}
which looks a lot nicer, but throws an error:
Cannot find an overload for "Compute" and the argument count: "1"