Need to connect to DB2 database with PowerShell - powershell

I couldn't get the output for my query which I am trying to run thru PowerShell.
$connection = New-Object System.Data.OleDb.OleDbConnection("Provider=IBMDADB2;DSN=;User Id=;Password=");
$ds = New-Object "System.Data.DataSet"
$QuerySQL = "select * from omaa.status"
$da = New-Object System.Data.OleDb.OleDbDataAdapter($QuerySQL, $connection)
$da.Fill($ds)
I am getting this exception
Exception calling "Fill" with "1" argument(s): "Unspecified error"
At line:6 char:9
+ $da.Fill <<<< ($ds)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException

I know this is an aging thread, but maybe this will help someone. I'm using this, and it works for Oracle and DB2 connections. (Not with acceleration for DB2 though). Exports CSV, but this can be modified to convert to xlsx afterwards.
function Get-OLEDBData ($connectstring, $sql) {
$OLEDBConn = New-Object System.Data.OleDb.OleDbConnection($connectstring)
$OLEDBConn.open()
$readcmd = New-Object system.Data.OleDb.OleDbCommand($sql,$OLEDBConn)
$readcmd.CommandTimeout = '300'
$da = New-Object system.Data.OleDb.OleDbDataAdapter($readcmd)
$dt = New-Object system.Data.datatable
[void]$da.fill($dt)
$OLEDBConn.close()
return $dt
}
#For Oracle
$connString = "password=yourPassword;User ID=YourID;Data Source=YourServer;Provider=OraOLEDB.Oracle"
#For DB2
$connString = "Provider=DB2OLEDB.1;Network Transport Library=TCPIP;Network Address=YourIPHere;Network Port=YourPortHere;Initial Catalog=YourDatabaseHere;Package Collection=NULLID;Default Schema=SameAsYourDatabaseHere;User ID=YourID;Password=YourPassword;"
$qry= "select something from somewhere"
Get-OLEDBData $connString $qry | Export-Csv -Path C:\TargetFolder\Results.csv -Delimiter ";" -NoTypeInformation

Related

Upload file to SharePoint

I would like to create a program in PowerShell to upload files to Sharepoint on schedule (using Task Scheduler)
I was looking for solution and I found this interesting article.
Based on this I wrote this script below:
Import-Module Microsoft.Online.Sharepoint.Powershell -DisableNameChecking;
(System.Reflection.Assembly)::LoadWithPartialName("System.IO.MemoryStream")
Clear-Host
$cred = Get-Credential "emailaddress#domain.com"
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($cred.Username, $cred.Password)
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext("https://")
$clientCOntext.Credentials = $credentials
if (!$clientContext.ServerObjectIsNull.Value) {Write-host "Connected to site" -ForegroundColor Green}
Function UploadFileToLibrary(){
$docLib - $clientContext.Web.Lists.GetByTitle("IT Documents");
$clientContext.Load($docLib);
$clientContext.ExecuteQuery();
$rootFolder = $docLib.RootFolder
$Folder = "\\10.x.x.x\xpbuild$\IT\Level0\scresult\Upload";
$FilesInRoot = Get-ChildItem - Path $Folder | ? {$_.psIsContainer -eq $False}
Foreach ($File in ($FilesInRoot))
{
$startDTM = (Get-Date)
}Write-Host "Uploading File" $File.Name "to" $docLib.Title -ForegroundColor Blue
UploadFile $rootFolder $File $false
$endDTM = (Get-Date)
Write-Host "Total Elapsed Time : $(($endDTM-$startDTM).totalseconds) seconds"
}
Function UploadFile ($SPListFolder, $File, $CheckInRequired){
$FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $True
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.Url = $File
$UploadedFile = $SPListFolder.Files.Add($FileCreationInfo)
If($CheckInRequired){
$clientContext.Load($UploadedFile)
$clientContext.ExecuteQuery()
If($uploadedFile.CheckOutType -ne "none"){
$UploadedFile.CheckIn("Checked in by Administrator", [Microsoft.SharePoint.Client.CheckinType]::MajorCheckIn)
}
}
$clientContext.Load($UploadedFile)
$clientContext.ExecuteQuery()
}
UploadFileToLibrary
When I tried to execute this I see that connection is active but I got an error:
Method invocation failed because [Microsoft.SharePoint.Client.List] does not contain a method named 'op_Subtraction'.
At C:\PowerShell\UploadSharepoint.ps1:11 char:1
+ $docLib - $clientContext.Web.Lists.GetByTitle("IT Documents");
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (op_Subtraction:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
Cannot find an overload for "Load" and the argument count: "1".
At C:\PowerShell\UploadSharepoint.ps1:12 char:1
+ $clientContext.Load($docLib);
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodCountCouldNotFindBest
Exception calling "ExecuteQuery" with "0" argument(s): "List 'IT Documents' does not exist at site with URL 'https://'."
At C:\PowerShell\UploadSharepoint.ps1:13 char:1
+ $clientContext.ExecuteQuery();
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ServerException
I cannot tell if any new problem occur once you fix that one, but given that the 2nd and 3rd error is caused by incorrect assignment of $docLib variable, changing - to =should resolve these three:
HERE |
$docLib = $clientContext.Web.Lists.GetByTitle("IT Documents");
# Below uses $docLib so it cannot be executed properly unless $docLib is assigned correct value
$clientContext.Load($docLib);
# And below fails as the above is not executed successfully
$clientContext.ExecuteQuery();

Trying to save values to an Access DB, but I'm getting an error when I try ExecuteNonQuery

I'm trying to use Powershell to pull a list of PC Names from an MS Access database, pull their drive size stats (WMI-Object), then save them back to Access. I keep getting the following error:
Exception calling "ExecuteNonQuery" with "0" argument(s): "No value given
for one or more required parameters."
At C:\Users\*******\Desktop\Scripts\AccessUpdate\HDDUpdate.ps1:75 char:5
+ $WriteFreeSpaceCmd.ExecuteNonQuery()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : OleDbException
This is running on Windows 10, Access 2016 x64, debugging with Visual Studio Code, PowerShell 5.1, NET Framework 4.8, ADE 2016 x64.
I've checked all the field names, but I have no idea what to check past that. My Google-fu wasn't effective either.
$connstr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\jharold\Desktop\Scripts\AccessUpdate\WinHDDTest.accdb;Persist Security Info=False;" #Change Source to DB location
[reflection.assembly]::LoadWithPartialName("System.Data") | Out-Null
$Conn = New-Object System.Data.OleDb.OleDbConnection
$Conn.ConnectionString = $connstr
$Conn.Open() | Out-Null
#
# Pull PC names from db and gather HDD info code works fine
#
foreach ($PC in $HDDInfo) {
$WriteFreeSpaceCmd = New-Object System.Data.OleDb.OleDbCommand
$WriteFreeSpaceCmd.Connection = $Conn
$WriteTotalSpaceCmd = New-Object System.Data.OleDb.OleDbCommand
$WriteTotalSpaceCmd.Connection = $Conn
$temp1 = "UPDATE Status SET ImportFreeSpace = " + $PC.FreeSpace + " WHERE NetBios_Name = " + $PC.NetBiosInfo
$WriteFreeSpaceCmd.CommandText = $temp1
$temp2 = "UPDATE Status SET ImportTotalSpace = " + $PC.TotalSpace + " WHERE NetBios_Name = " + $PC.NetBiosInfo
$WriteTotalSpaceCmd.CommandText = $temp2
$WriteFreeSpaceCmd.ExecuteNonQuery()
$WriteTotalSpaceCmd.ExecuteNonQuery()
}
I expect $PC.FreeSpace and $PC.TotalSpace to save to the corresponding PC's ImportFreeSpace and ImportTotalSpace as text. Instead, it errors out as soon as it runs ExecuteNonQuery().
The values in your UPDATE command should have quotes around them. Like:
$temp1 = "UPDATE Status SET ImportFreeSpace = '{0}' WHERE NetBios_Name = '{1}' " -f $PC.FreeSpace, $PC.NetBiosInfo

Powershell parameter will not provide OleDbdataAdapter.fill valid SQL statement

I has been trying to figure out why I am not able to use a parameter in the powershell script to fill in a datatable via OleDBDataAdapter. Here a snippet of the code and the error I am getting.
Function DBF_FileImport
{
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$tblTemp,
[Parameter(Mandatory=$True,Position=2)]
[string]$strSQL = $(throw "Please specify a query.")
)
### ConnectionString to pull data from DBF file ###
$ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=$filepath;Extended Properties=dBASE IV;User ID=;Password=;"
$Conn = new-object System.Data.OleDb.OleDbConnection($connString)
$Conn.open()
#Create the new recordset
$cmd = new-object System.Data.OleDb.OleDbCommand
$cmd.Connection = $Conn
$cmd.CommandText = "$strSQL"
#create the datatable
$da = new-object System.Data.OleDb.OleDbDataAdapter($cmd)
$dt = new-object System.Data.dataTable
$da.fill($dt)
$Conn.close()
The error I receive every time I run the function is:
Exception calling "Fill" with "1" argument(s): "Invalid SQL statement;
expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'."
At userpath.ps char:1
+ $da.fill($dt)
+ ~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : OleDbException
If I put the SQL statement inside the function then it works fine. I dont know why it is behaving like this. I searched the internet and was not able to find anything that will help me to solve the error. Any info you can provide will help greatly. Thank you

In PowerShell how to troubleshoot exception in DataSet.Fill?

I'm using a function I found on SO to retrieve data from SQL server and generate XML.
function Invoke-SQL {
param(
[string] $sqlCommand = $(throw "Please specify a query.")
)
$connectionString = "Data Source=$server;Initial Catalog=$database;user id=$uid;password=$pwd"
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$dataset = New-Object System.Data.DataSet
$adapter.Fill($dataSet) | Out-Null
$connection.Close()
$tableOutput = $dataSet.Tables
foreach($row in $tableOutput) {
$xml = $row | ConvertTo-Xml -NoTypeInformation -Depth 1
$xml.InnerXML
}
}
It works most of the time but, occasionally, exactly the same SELECT (except for the range) from the same database and table would throw the following exception:
Exception calling "Fill" with "1" argument(s): "Incorrect syntax near '>'."
At DBTest.ps1:22 char:18
+ $adapter.Fill <<<< ($dataSet) | Out-Null
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
How to debug what rows and/or what data gets the Fill method to break?
As per comments, it was the SQL command itself. When you generate SQL commands make sure every variable goes through validation and sanity checks. As some comments suggested, logging queries can help with troubleshooting.

Creation of audit via powershell fails with "SetParent Failed"

I'm trying to create a new server audit on a WinServer 2008 R2 with the following PowerShell Script.
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
$server = "SM1111" #change to desired instance
$instance = "S111"
$auditName = "$instance"+"TestAudit"
$auditDir = 'F:\Microsoft SQL Server\'+$instance+'AuditTestLogsNew\'
$srv = new-Object ('Microsoft.SqlServer.Management.Smo.Server') -argumentlist $instance
$newAudit = New-Object Microsoft.SqlServer.Management.Smo.Audit($srv, "$auditName")
$newAudit.DestinationType = [Microsoft.SqlServer.Management.Smo.AuditDestinationType]::File
$newAudit.FilePath = $auditDir
$newAudit.MaximumRolloverFiles = 10
$newAudit.MaximumFileSize = 100
$newAudit.QueueDelay = 1000
$newAudit.Create()
$newAudit.Enable()
However the following line always fails:
$newAudit = New-Object Microsoft.SqlServer.Management.Smo.Audit($srv, "$auditName")
I get the following error message:
New-Object : Exception calling ".ctor" with "2" argument(s): "SetParent failed for Audit 'S111TestAudit'. "
At MYFOLDER\Documents\Auditing_Test\CreateAudit.ps1:9 char:13
+ $newAudit = New-Object Microsoft.SqlServer.Management.Smo.Audit($srv, "$auditNam ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [New-Object], MethodInvocationException
+ FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand
I've been googling a lot, but still haven't found anything that might solve the problem, since I don't quite understand what raises the error to begin with.
I have full administrator privileges.
Any help would be appreciated!
You are missing the server name for your instance. Your variable $srv is not pointing to an actual server instance.
$server = "SM1111" #change to desired instance <- This isn't doing anything
$instance = "S111"
$srv = New-Object Microsoft.SqlServer.Management.Smo.Server -argumentlist "$server\$instance"