How to pass the parameter in SQL query from PowerShell - sql

I have this code in PowerShell, that executes SQL query to UPDATE my table:
$Connection=new-object data.sqlclient.sqlconnection "server=server;database=mydb;trusted_connection=true;"
$Connection.open()
For ( $i = 0; $i -le $ActID.Length; $i ++ ) {
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.Connection = $Connection
$cmd.CommandText =
"
update Table
set Note = #PATH
"
$cmd.Parameters.Add("#PATH", $ActID[$i].Values) | Out-Null
$cmd.ExecuteNonQuery()
}
I tried to update the table with the variable defined in this string:
$cmd.Parameters.Add("#PATH", $ActID[$i].Values) | Out-Null
But when I execute the script the error log says that there is no value passed in $ActID[$i]
Are there other methods to pass parameters (variables) in powershell queries?

What could be the mistake:
$i -le $ActID.Length;
it should be probably
$i -lt $ActID.Length;
You could also use piping which simplifies the code:
$actId | % { ..... $cmd.Parameters.Add("#PATH", $_.Values) | Out-Null .... }
Besides that the property you use is Values - is it really what you wanted? Values looks like a collection of something. Maybe you wanted to use a single value.

Related

Increment variable in Foreach-Object

I want insert some AD attributes with PowerShell into a SQL table. So far so good:
$insert = #'
INSERT INTO [mdb].[dbo].[import](id,userid)
VALUES ('{0}','{1}')
'#
Try {
$connectionString = 'Data Source=serverdb;Initial Catalog=mdb;Integrated Security=SSPI'
$conn = New-Object System.Data.SqlClient.SqlConnection($connectionString)
$conn.Open()
$cmd = $conn.CreateCommand()
$counter = 0
Get-ADUser -Filter * -SearchBase "OU=company,DC=company,DC=state,DC=de" | Select #{Name="ID";Expression={ $global:counter; $global:counter++ }},SamAccountName |`
ForEach-Object {
$cmd.CommandText = $insert -f $counter,$_.SamAccountName
$cmd.ExecuteNonQuery()
}
$conn.Close()
}
Catch {
Throw $_
}
The output from get-ADUser is right, but the insert throws an error, that the primary key has duplicates. The incrementing must be wrong.
Can anybody help? THANKS!
ID is starting from 1 and not 0, is this normal ?
Furthermore, why are you creating an user defined property (ID) and don't use it ?
You can avoid the ugly global scope too (starting counter from 0 here) :
#### $counter = 0 <--- No more usefull
Get-ADUser -Filter * -SearchBase "OU=company,DC=company,DC=state,DC=de" | Select SamAccountName |`
ForEach-Object -Begin { $counter = 0 } -Process {
$cmd.CommandText = $insert -f $counter,$_.SamAccountName
$cmd.ExecuteNonQuery()
$counter++
}
I am not an SQL specialist, so this is probably not an anwser. But, you have here a nicer code ;)
You should always use parameters when inserting data with SQL. (Why?) In short: It's more secure, more performant, more robust and easier to use.
Put parentheses around the operation (++$counter) to return the value after increasing it. (Use $counter++ if you want zero-based ids, ++$counter if you want 1-based ids.)
$cmd.CommandText = "
INSERT INTO [mdb].[dbo].[import](id,userid)
VALUES (#id, #userId)
"
$counter = 0
Get-ADUser -Filter * -SearchBase "OU=company,DC=company,DC=state,DC=de" | foreach {
$cmd.Parameters.Clear()
$cmd.Parameters.AddWithValue("id", (++$counter))
$cmd.Parameters.AddWithValue("userId", $_.SamAccountName)
$cmd.ExecuteNonQuery()
}

PowerShell Script that Queries SQL Table to CSV File using Loop

I have a basic SQL table of Employees. Using a powershell script I want to export all the employees who have made over 1000 sales to a .csv file and the rest into a different .csv file. I want to accomplish this task by using a loop. I am new to powershell and want to learn the foundations. Can anyone help?
SQL Table (not real employees)
This is what I have so far:
$connection.Open()
[System.Data.SqlClient.SqlDataReader]$result = $cmd.ExecuteReader()
$highDestFile = "C:\high-sales.csv"
$lowDestFile = "C:\low-sales.csv"
while($result.Read()) {
$ename = $result.GetValue(3);
$job = $result.GetValue(4);
$sales = $result.GetValue(7);
$tableArray = New-Object System.Collections.ArrayList
$tableArray.Add($ename)
$tableArray.Add($job)
$tableArray.Add($sales)
if($sales -ge 1000) {
Out-File -FilePath $highDestFile -InputObject $tableArray -Encoding ASCII -Append
} else {
Out-File -FilePath $lowDestFile -InputObject $tableArray -Encoding ASCII -Append
}
}
$connection.Close()
I'm not real familiar with the method you're using to get your results, but I think I have something similar that might be easier to work with for you. It will get all results into PS, and you can filter things from there, rather than getting one result at a time. You obviously know how to make your own SqlConnection and SqlCommand, I'm just including them for future readers to reference.
# Define SQL query
$sqlQuery = #"
SELECT *
FROM MyTable
"#
# Create a SqlConnection to connect to the SQL DB
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server = $SqlServer; Database =$SqlCatalog; User Id = $User; Password = $Password"
# Create a SqlCommand object to define the query
$sqlCmd = New-Object System.Data.SqlClient.SqlCommand
$sqlCmd.CommandText = $sqlQuery
$sqlCmd.Connection = $sqlConnection
# Create a SqlAdapter that actually does the work and manages everything
$sqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$sqlAdapter.SelectCommand = $sqlCmd
# Create an empty DataSet for the query to fill with its results
$dataSet = New-Object System.Data.DataSet
# Execute the query and fill the DataSet (then disconnect)
$sqlAdapter.Fill($dataSet)
$sqlConnection.Close()
# Convert DataSet table to array for ease of use
[Array]$Results = $dataSet.Tables[0]
Beyond that you could just use a pair of Where statements to filter your results, and output to files.
$Results | ?{[int]$_.Sales -ge 1000} | Set-Content $highDestFile
$Results | ?{[int]$_.Sales -lt 1000} | Set-Content $lowDestFile

Oracle Sql and Powershell : Execute query, print/output results

I need a way to execute a SQL (by importing a .SQL script) on a remote Oracle DB using PowerShell. In addition to this I am also trying to output the results in an .xls format in a desired folder location. To add to the fun, I would also want to run this task on an automatic schedule. Please help !
I have gotten so far :
[System.Reflection.Assembly]::LoadWithPartialName ("System.Data.OracleClient") | Out-Null
$connection = "my TNS entry"
$queryString = "my SQL query"
$command = new-Object System.Data.OracleClient.OracleCommand($queryString, $connection)
$connection.Open()
$reader = $command.ExecuteReader()
$tempArr = #()
#read all rows into a hash table
while ($reader.Read())
{
$row = #{}
for ($i = 0; $i -lt $reader.FieldCount; $i++)
{
$row[$reader.GetName($i)] = $reader.GetValue($i)
}
#convert hashtable into an array of PSObjects
$tempArr+= new-object psobject -property $row
}
$connection.Close()
write-host "Conn State--> " $connection.State
$tmpArr | Export-Csv "my File Path" -NoTypeInformation
$Error[0] | fl -Force
The easiest way is to drive sqlplus.exe via powershell. To execute the sql and get the output you do this:
$result = sqlplus.exe #file.sql [credentials/server]
#parse result into CSV here which can be loaded into excel
You can schedule this script with something like:
schtasks.exe /create /TN sqlplus /TR "Powershell -File script.ps1" /ST 10 ...
For this you need to have sqlplus installed (it comes with oracle express and you could install it without it). This obviously introduces dependency that is not needed but sqlplus could be used to examine the database and do any kind of thing which might be good thing to have around.

Insert Microsoft Updates into Database

I'm trying to modify this script so that it inserts the installed updates into an SQL Server database table.
$conn = New-Object System.Data.SqlClient.SqlConnection
$conn.ConnectionString = "Data Source=sqlserver; Initial Catalog=updates; Integrated Security=SSPI;"
$conn.Open()
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.Connection = $conn
$cmd = $conn.CreateCommand()
$wu = new-object -com “Microsoft.Update.Searcher”
$totalupdates = $wu.GetTotalHistoryCount()
$all = $wu.QueryHistory(0,$totalupdates)
$OutputCollection= #()
Foreach ($update in $all){
$Regex = “KB\d*”
$KB = $string | Select-String -Pattern $regex | Select-Object { $_.Matches }
$output = New-Object -TypeName PSobject
$output | add-member NoteProperty “HotFix ID” -value $KB.‘ $_.Matches ‘.Value
$output | add-member NoteProperty “Title” -value $string
$OutputCollection += $output
$cmd.CommandText += "INSERT INTO dbo.updates (hotfixid, hotfixdescription) VALUES ('$($kb.'$_.Matches'.Value)', ('$($string)'))"
}
$cmd.ExecuteNonQuery()
$conn.close()
At the moment, I'm getting correct number of rows for updates in sql server but it isn't showing hotfixid and in hotfix descriptien columns there is a only one update in all rows.
Thanks!
Do the INSERTs inside the loop. I would, however, recommend that you use prepared statements instead of building the SQL statements via string concatenation. Also, there's no need to build $OutputCollection objects when you're not using it anywhere.
Something like this should work:
...
$wu.QueryHistory(0, $totalupdates) | % {
$KB = $_.Title | ? { $_ -match '(KB\d+)' } | % { $matches[1] }
$cmd = $conn.CreateCommand()
$cmd.CommandText = "INSERT INTO dbo.updates (hotfixid, hotfixdescription) " +
"VALUES (#id, #descr)"
$cmd.Parameters.AddWithValue("#id", $KB)
$cmd.Parameters.AddWithValue("#descr", $_.Title)
$cmd.Prepare()
$cmd.ExecuteNonQuery()
}
...
Untested, though, since I don't have an SQL Server at hand. I also suspect that there's a more efficient way to handle the prepared statements, but I'm not that familiar with SQL Server.

Powershell How to query multiple classes and write in to SQL Table

Not knowing Powershell very well and indeed sql it's taken me all week to piece together a script thatkind of works but I need help expanding on it. It works for retrieving more than 1 value from the same class and inserts the values. What I need to do is to be able to retrieve values from other classes and insert the result in to the appropriate column. Any help / advice would be so appreciated.
$servernames = Get-WmiObject -computername Anycompname -class win32_ComputerSystem | Select Name, Manufacturer
# Open Connection
$conn = New-Object System.Data.SqlClient.SqlConnection
$connectionString = "Server=;Database=;user=;pwd=;"
$conn.ConnectionString = $connectionString
$conn.Open()
# Create the Command object to execute the queries
$cmd = New-Object System.Data.SqlClient.SqlCommand
$cmd.Connection = $conn
$cmd.CommandType = [System.Data.CommandType]::Text
# Write Data
foreach ($servername in $servernames)
{
# Compose Query for this $servername - watch the single quotes for string values!!
$query = "INSERT INTO dbo.U_Server (ServerName, OSVersion) VALUES ('" + $servername.Name + "', '" + $servername.Manufacturer + "')"
# Uncomment next line to display query for checking
$query
# Setup Command
$cmd.CommandText = $query
# Execute Command to insert data for this $drive
$result = $cmd.ExecuteNonQuery()
}
# Tidy Up
$conn.Close()
Just get the other WMI object(s) in the foreach loop and keep adding to your insert string as needed.
foreach ($servername in $servernames)
{
## Get other WMI info as needed here.
$os = Get-WmiObject -class win32_operatingsystem –computername $servername.Name
$processors = Get-WmiObject Win32_Processor -computername $servername.Name
# Compose Query for this $servername
$query = "Insert Into dbo.U_Server (ServerName, OSVersion, OSName, OSServicePack) Values
('$($servername.Name)', '$($servername.Manufacurer)', ‘$($os.Caption)’, ‘$($os.ServicePackMajorVersion)’ )"
## The rest of your foreach loop follows
} ## End of foreach