Connecting to SQL with PS, Drive Not Found - sql

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"}

Related

SQL Query not accepting variable [duplicate]

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')"

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

Powershell CSV output - cant delete rows and special charaters

I'm having trouble with a csv file. My script is collecting data from a SQL Table, then it should write result as a csv file. My problem is that the csv file my code currently creates has speech marks and two rows of header that i don't want.
Right now my file looks like this:
TYPE System.Data.DataRow
code,"order","price"
product1,"1","207,75"
product2,"1","95,24"
I would like it to look like this:
product1;1;207,7
product2;1;95,24
My code:
$VAR1 = "select [product], [order], [price] from TABLE1
$VAR2 = Invoke-Sqlcmd -Query $VAR1 -serverinstance SERVER1
$Result | Export-Csv -path C:\test55.csv
You can remove the TYPE header line by using the -NoTypeInformation switch on Export-CSV.
I don't think you can switch off the speech marks, but they are useful in case one of your data values includes a comma in it. If you open the CSV in Excel the speech marks won't be visible, so they are honoured by things that read CSV. If you wanted to remove them you could do a -replace to do so but it would risk removing them where they are part of the data.
If you want to remove the header line, you could use ConvertTo-CSV and then use Select-Object to skip the first line of the output.
So for example:
$VAR1 = "select [product], [order], [price] from TABLE1"
$VAR2 = Invoke-Sqlcmd -Query $VAR1 -serverinstance SERVER1
($Result | ConvertTo-Csv -NoTypeInformation |
Select-Object -Skip 1) -Replace '"' |
Out-File C:\test55.csv

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
}