Connect to SQL Server with different user - sql-server

I want to connect with PowerShell to SQL Server with a different user.
My code:
$SQLServer = "Server"
$SQLDBName = "DB"
$uid = "User"
$pwd = "PWD"
$SqlQuery = "select * from tblCalc where field_id = 367;"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID = $uid; Password = $pwd;"
$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
$SqlAdapter.Fill($DataSet)
I get this error:
Exception calling "Fill" with "1" argument(s): "Login failed for user 'User'."
At line:14 char:1
+ $SqlAdapter.Fill($DataSet)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : SqlException

Related

How do I retrieve returned value from sql function in Powershell?

Hi I am using Powershell script to call a function which returns me table name and I am unable to understand how to retrieve the value. Below is the code that I am using
$SqlQuery = "select dbo.abc_import_create_table_for_file('$fileFullName', '$(gc $fileFullName | select -first 1)');"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; User ID = $uid; Password = $pwd;"
$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
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()

Strange linebreaks occur when exporting to csv from Datatable

I have a strange issue when I export my DataTable to CSV with Powershell: I get some line breaks and I am also not sure why I get the
#TYPE System.Data.DataRow
$query = "use [ISTABLocalDB]
SELECT
Item.[ID] as PartIdDB
,car.Kilometrage
FROM [ISTABLocalDB].[file].[Item] as Item
INNER JOIN [ISTABLocalDB].[file].[ItemPart] as ItemPart ON Item.ID = ItemPart.
LEFT JOIN [ISTABLocalDB].[file].[ItemResourceFile] as ImageFile ON Car.ID = ImageFile.Item_ID
where
Item.Type = 'P' -- means parts
and ItemType.[Code] Not like '9001' -- car saved
and ItemType.[Code] in ('5000','5001','5002','5003','5003','5005','5006','9000');"
$extractFile = "$path $date.csv"
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};"
$connection = New-Object System.Data.SqlClient.SqlConnection
$connection.ConnectionString = $connectionString
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = $query
$command.Connection = $connection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $command
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$connection.Close()
$DataSet.Tables[0] | Export-Csv $extractFile -encoding "unicode" -Delimiter ";"
$file= $extractFile
(Get-Content $file) | Foreach-Object {$_ -replace '"', ''}|Out-File $file

Exporting powershell script output to local SQLtable

I am trying to export the output of the below script to a local sql table directly instead of using CSV as a mediator. Is there a way to export the output of the below script directly to the local sql table.
Get-Content "C:\test\computers.txt" | Where-Object { $_.Trim() -ne "" } |
ForEach-Object {
Invoke-Command -Computer $_ -ScriptBlock {
Param($computer)
$Database = "secaudit"
$AttachmentPath = "C:\test\SQLData.csv"
$SqlQuery = "xp_fixeddrives"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Data Source=$computer;Initial Catalog=$Database;Integrated Security = True"
$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
$nRecs = $SqlAdapter.Fill($DataSet)
$nRecs | Out-Null
$objTable = $DataSet.Tables[0]
$DataSet.Tables[0]
} -ArgumentList $_ -Credential $cred
} | Select-Object PSComputerName, Drive, "MB Free" |
Export-Csv -Path "C:\test\output_space.csv" -NoTypeInformation
$query = #"
BULK INSERT [Test1].[dbo].[table_1] FROM "C:\test\output_space.csv" WITH (FIRSTROW = 2, FIELDTERMINATOR = ",", ROWTERMINATOR = "\n")
"#
sqlcmd -S "CSCINDAE680687" -E -Q $query
Here's an example function that takes a connection string, target table name, and a data table of the rows to be loaded. By default, columns are mapped by ordinal but you can use SQlBulkCopyColumnMappings to specify different mappings, if needed.
Function Insert-TargetTable
{
param(
[Parameter(Mandatory=$True)]
[string]$TargetDatabaseConnectionString
, [Parameter(Mandatory=$True)]
[string]$TargetTableName
, [Parameter(Mandatory=$True)]
[System.Data.DataTable]$DataTable
)
$bcp = New-Object System.Data.SqlClient.SqlBulkCopy($TargetDatabaseConnectionString);
$bcp.DestinationTableName = $TargetTableName;
$bcp.WriteToServer($DataTable);
$bcp.Close();
}

Using += in scriptblock for a switch statement in a foreach loop

Firstly, thank you for taking the time to read this, thank you for your help in advance.
Here is my code:
<#
SCCM Request Alert Script
#>
Import-Module ActiveDirectory
$WMIObjects = Get-WmiObject -Namespace 'ROOT\SMS\Site_EUR' -Class SMS_UserApplicationRequest -ComputerName "EUR-SCCM"
$FileStore = "c:\export\SCCMRequestfile.txt"
foreach ($Obj in $WMIObjects)
{
[String]$RequestValue = $Obj.CurrentState
$Application = $Obj.Application
$User = $Obj.User -replace 'MYDOMAIN\\',""
$ADUser = Get-ADUser -Identity $User
$PendingRequest = #()
$CancelledRequest = #()
$DeniedRequest = #()
$ApprovedRequest = #()
$Unknown = #()
$Args = #{ 'User' = $ADUser.Name; 'Application' = $Obj.Application }
$PR = New-Object -TypeName PSObject -Property $Args
$CR = New-Object -TypeName PSObject -Property $Args
$DR = New-Object -TypeName PSObject -Property $Args
$AR = New-Object -TypeName PSObject -Property $Args
$UR = New-Object -TypeName PSObject -Property $Args
switch ($RequestValue) {
1 { $PendingRequest += $PR }
2 { $CancelledRequest += $CR }
3 { $DeniedRequest += $DR }
4 { $ApprovedRequest += $AR }
default { $Unknown += $UK }
}
}
Write-Host -ForegroundColor 'yellow' "Pending Requests "
$PendingRequest
Write-Host -ForegroundColor 'DarkYellow' "Cancelled Requests "
$CancelledRequest
Write-Host -ForegroundColor 'DarkRed' "Denied Requests "
$DeniedRequest
Write-Host -ForegroundColor 'Green' "Approved Requests "
$ApprovedRequest
Write-Host -ForegroundColor 'White' "Unknown Approval Type "
$Unknown
At them moment it only returns the last object in the foreach loop.
I've tested a foreach loop manually using;
foreach ($Obj in $Objects) {
$array = #()
$array += $Obj
}
$Array
And this places each object in the the array.
So I was wondering if this was an issue with the switch statement or something I haven't done like casting it as an array?
Any help would be appreciate, Thank you.
Nigel Tatschner
You're re-initializing your arrays on each iteration of the loop. Move the following lines so they're before your foreach loop:
$PendingRequest = #();
$CancelledRequest = #();
$DeniedRequest = #();
$ApprovedRequest = #();
$Unknown = #();

Unable to query [Get-QADComputer] info in Remote PS Sessions (Powershell)

When i run the below script to extract the OU info using quest ad commandlets it gives me an error as below
Object reference not set to an instance of an object.
+ CategoryInfo : NotSpecified: (:) [Get-QADComputer], NullReferenceException
+ FullyQualifiedErrorId : System.NullReferenceException,Quest.ActiveRoles.ArsPowerShellSnapIn.Powershell.Cmdlets.GetComputerCmdlet
Below is The Script which is use
$password = convertTo-secureString -string "123" -asPlainText -force
$credential = new-object System.Management.automation.Pscredential ("test.com\sh" , $password)
$session = New-PSSession -computername CI -credential $credential -port 5985 -Authentication Default
Invoke-Command -Session $session -ScriptBlock {
Add-PSSnapin Quest.ActiveRoles.ADManagement
$ou = get-qadcomputer QUAG | select -ExpandProperty canonicalname
}
$adou= (Invoke-Command -Session $session -ScriptBlock { $ou })
Get-PSSession | Remove-PSSession
$adou
Can Some one please help me with this?
Thanks!
You don't need to run QAD from within a remote session, you can try it from your admin station:
Add-PSSnapin Quest.ActiveRoles.ADManagement
$pw = read-host "Enter password" -AsSecureString
Connect-QADService -Service 'server.company.com' -ConnectionAccount 'company\administrator' -ConnectionPassword $pw
Get-QADComputer QUAG | Select-Object -ExpandProperty CanonicalName
I think the problem is with the way you're declaring and then invoking that script block. Not tested, but I think this might work better:
Invoke-Command -Session $session -ScriptBlock {
Add-PSSnapin Quest.ActiveRoles.ADManagement
}
$ou = {get-qadcomputer QUAG | select -ExpandProperty canonicalname}
$adou= (Invoke-Command -Session $session -ScriptBlock $ou)

Resources