SQL Query not accepting variable [duplicate] - sql

This question already has answers here:
How can you use an object's property in a double-quoted string?
(5 answers)
PowerShell string interpolation syntax
(3 answers)
Closed 2 months ago.
I am trying to pass a variable into a SQL update statement to update a table column. I run the following commands and do not receive any errors. However, the table column was not updated.
$SQLserver = 'servername'
$Database = 'databasename'
$variable = (Get-Content -path \\share\test\testfile.json | ConvertFrom-Json)
$vm = Invoke-SQLCMD -ServerInstance $SQLServer -Database $Database -Query "Update (tablename) set (columnname) = 1 where vmid IN ('$variable.attribute')"
I see that all the data is being passed into the variable. But, the update statement is not updating my column. Also, I do not receive any error messages when running my code.

you were too close, only "$" missing, here's the correct code
$SQLserver = 'servername'
$Database = 'databasename'
$variable = (Get-Content -path \\share\test\testfile.json | ConvertFrom-Json)
$vm = Invoke-SQLCMD -ServerInstance $SQLServer -Database $Database - Query "Update $tablename set $columnname = 1 where vmid IN ('$variable.vmid')"

Related

How do I compare users from SQL query to AD then insert them?

Import-Module ActiveDirectory
$ADUSER = Get-Aduser -Filter * -Properties SamAccountName | Select-Object SamAccountName
$SQLQUERY = Invoke-Sqlcmd -Query "SELECT username AS SamAccountName FROM test.dbo.ad" -Database "TEST" -Server "DB-1"
$Compare = Compare-Object $ADUSER $SQLQUERY -Property 'SamAccountName' -passthru | ?{.SideIndicator -Eq '=>'} | SELECT SamAccountName
$Insert = "INSERT INTO TEST.dbo.ad SELECT $user" -Database "TEST" -Server "DB-1"
Foreach ($user in $Compare){
Invoke-Sqlcmd -Query $Insert
}
I am using Powershell 5.0 and when I run this I get an error ".SideIndicator : The term '.SideIndicator' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again." What am I doing wrong? I am trying to pull AD users then a query and then compare AD to SQL and insert in.
As Olaf pointed out, you are missing the $_ from your Where statement on the fourth line. It should read:
$Compare = Compare-Object $ADUSER $SQLQUERY -Property 'SamAccountName' -passthru | ?{$_.SideIndicator -Eq '=>'} | SELECT SamAccountName

Connecting to SQL with PS, Drive Not Found

I am attempting to pipe the results of a SQL query into a .txt file on the local server.
Not sure what the command is missing.
$sqlpeeps = Invoke-Sqlcmd -ServerInstance '192.168.1.1' -Database 'DATABASE' -Query "SELECT 'FILE#' AS
'EmployeeID' FROM [DATABASE].[dbo].[employee] WHERE 'v_employee.Status' in ('A', 'S', 'L')"
$sqlpeeps | out-file {"C:\Users\<my username>\Desktop\here.txt"}

keyword 'like' in my SQL statement in Poweshell is getting treated like an '=' sign

The like statement in my SQL query in powershell isn't producing the intended results. My 'like' statement is getting treated like an '=' sign.
for example
I have a table with the following values:
FieldNames
1. George Bush;George Foreman;Mary jones;
2. George Foreman;
3. George Foreman; Michael Smith;
4. Mary Jones;George Foreman
Variable:
$Expression = "George Foreman"
Three options I tried:
1.
Select FieldNames from table where FieldNames like '%$Expression%'
2.
Select FieldNames from table where FieldNames like '%$($Expression)%'
3.
Select FieldNames from table where FieldNames like '%George Foreman%'
I receive the same results for all three options (only row 2 returns). I would expect all the rows to return.
I can run this same query in SSMS and all rows return.
Has anyone ran across this problem or have any suggestions on how I can modify my select query to get all the rows using 'like'?
Formatted Powershell expression:
#Variables:
$Expression = "George Foreman"
$UserName = "UserName"
$password = "Password"
$Database = "Database"
$Server = "Server"
$Query="Select FieldNames from table where FieldNames like '%$Expression%' "
$ConnectionString = "Server=$Server ;User ID=$UserName; password=$password;
Integrated Security=True; database=$Database;"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connection
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = $Query
$result = $command.ExecuteReader()
$connection.Close()

How to display only the word "Running" in a Get-Service cmdlet

I have a script in Powershell that inserts data into a SQL table but I am having trouble figuring out how to return the status of the service as only the word "Running".
Right now it is returning #{Status=Running} under the status column of my database table and I just want it to return the word "Running". How do I go about this?
foreach($status in $serviceStatus)
{
if ($status.status -eq "Running")
{
$SQL = "INSERT INTO [DatabaseName].[dbo].[TableName]([ServerName], [ServiceName], [Status], [Date])
VALUES ('$serverName', '$service', '$status', '$Date')
GO"
Invoke-sqlcmd -ServerInstance 'ServerName' -Database 'DatabaseName' -query $SQL
Write-Host "***Running: $($serverName)***"
}
}
If you install dbatools, you could do that in one line:
Instal-Module dbatools -Scope CurrentUser # only once
Get-Service | Where-Object Status -eq 'Running'| Select #{n='Server';e={if($_.MachineName -eq '.'){$env:COMPUTERNAME}else{$_.MachineName}}}, Name, Status,#{n='Date'; e={Get-Date}} | Write-DbaDataTable -SqlInstance $sql -Database TEMPDB -Table abc -AutoCreateTable

Powershell Get-QADUser results to SQL table

I'm querying Active Directory with a string which loops through each domain controller in our system and returns a set of results. The script works great with export-csv but because we wish to retain all data in the custom info field (it contains carriage-returns) I'd like to export this directly into an SQL table.
The error reported by Powershell reads:
Exception calling "ExecuteNonQuery" with "0" argument(s): "Insert Error: Column name or >number of supplied values does not match table definition."
Which is a pretty verbose response, I've created and named the columns of each table to exactly match the output of the get-object.
Here's the output from the pipe:
SamAccountName : testuser
DisplayName : Test User (COMPANY)
info : Test Entry 1234567890
Test for output.
Entering
Multiple lines.
whenCreated : 09/11/2004 09:08:42
whenChanged : 19/07/2012 09:25:21
AccountExpires :
pwdLastSet : 13/06/2012 07:43:43
LastLogonTimestamp : 18/07/2012 15:38:35
userAccountControl : 512
Name : Test User
LastLogon :
DC : DCNAME1
And here's the code:
##--AD data output to SQL script, you need the Quest plugin!
$SamAccountName = Read-Host "Enter the username to query for last logon"
##--Query domain for all domain controllers and funnel into a forEach loop
Get-QADComputer -ComputerRole DomainController | Foreach-Object{
$dc = $_.Name
##--Query each domain controller for the user object and retrieve the LastLogon timestamp
$user = Get-QADUser -Service $dc -SamAccountName $SamAccountName -IncludedProperties info,pwdLastSet,AccountExpires,userAccountControl | Select-Object SamAccountName,displayName,info,whenCreated,whenChanged,accountExpires,pwdLastSet,lastLogonTimestamp,userAccountControl,name,LastLogon,#{n='DC';e={$dc}} |
out-host
##--Open database connection
$conn = New-Object System.Data.SqlClient.SqlConnection("Data Source=SQLSERVER; Initial Catalog=ADomain; Integrated Security=SSPI")
$conn.Open()
##--AAGH! How to grab the results of the Select-Object above?
$cmd = $conn.CreateCommand()
$cmd.CommandText ="INSERT extract VALUES ('$user')"
$cmd.ExecuteNonQuery()
##--Don't forget to close it!
$conn.Close()
Now I'm messing something up which is probably plainly obvious, any help much appreciated.
Assume the following test object:
$exampleObject = New-Object PSObject -Property #{SamAccountName="TestSAN";DisplayName="TestDN"}
$user = $exampleObject | Select-Object SamAccountName, DisplayName
##--AAGH! How to grab the results of the Select-Object above?
$commandText = "INSERT extract VALUES ('$($user.SamAccountName)','$($user.DisplayName)'"
I would also move the sql connect and close to outside of a loop and place it in a try/finally block, so it is only done once instead of for each DC entry and the Close is still called when there is an Exception during the execution of the try block. See here for reference on using a try/catch/finally block with Powershell.
here I'm using SqlServerCmdletSnapin and it's Invoke-sqlcmd. This script is using MSSQL database EMPLOYEE and table EMPLOYEE_DOMAIN. Hope it helps. Works fine for me..
Add-PSSnapin Quest.ActiveRoles.ADManagement
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
$db_server = "10.3.18.55"
$db = "EMPLOYEE"
$table = "EMPLOYEE_DOMAIN"
$username = "import"
$pwd = "Okinawa84561"
# First, clear existing table
$sql_query_del = "DELETE FROM $table"
Invoke-Sqlcmd -ServerInstance $db_server -Database $db -Username $username -Password $pwd -Query $sql_query_del
# Get users with employeeID only and write their accountname and employeeID to DB
Get-QADUser -IncludeAllProperties | ? {$_.employeeID} | select sAMAccountName, employeeID | foreach {
$an = $_.sAMAccountName
$eid = $_.employeeID
Write-Host " sAMAccountName : $an employeeID : $eid"
$sql_query = "INSERT INTO $table (employeeID, domainName) VALUES ('$eid', '$an')"
Invoke-Sqlcmd -ServerInstance $db_server -Database $db -Username $username -Password $pwd -Query $sql_query
}