My output, will always contain the information from the second item (database), it seems that it is overwriting any values returned for the initial items? I can change the order of the items in to prove this. Please help...
$databaselist = Get-Content D:\AdvancedDB\Server2.txt
$servername = get-content D:\AdvancedDB\Server.txt
$dataSource = $servername
$myuserID = 'userid'
$mypassword = 'password'
$DatabaseIndexInfo =
"SELECT dbschemas.[name] as 'Schema',
dbtables.[name] as 'Table',
dbindexes.[name] as 'Index',
indexstats.avg_fragmentation_in_percent,
indexstats.page_count
FROM sys.dm_db_index_physical_stats (DB_ID(), NULL, NULL, NULL, NULL) AS indexstats
INNER JOIN sys.tables dbtables on dbtables.[object_id] = indexstats.[object_id]
INNER JOIN sys.schemas dbschemas on dbtables.[schema_id] = dbschemas.[schema_id]
INNER JOIN sys.indexes AS dbindexes ON dbindexes.[object_id] = indexstats.[object_id]
AND indexstats.index_id = dbindexes.index_id
WHERE indexstats.database_id = DB_ID()
ORDER BY indexstats.avg_fragmentation_in_percent desc"
$connectionDetails = "Provider=sqloledb; " + "Server=$dataSource; " + "Database=$database; " +
"User
ID=$myuserID; " + " Password=$mypassword; "
$frag16 = #()
foreach ($database in $databaselist) {
##Connect to the data source using the connection details and T-SQL command we provided above, and
open the connection
$connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails
$command16 = New-Object System.Data.OleDb.OleDbCommand $DatabaseIndexInfo,$connection
$connection.Open()
##Get the results of our command into a DataSet object, and close the connection
$dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command16
$dataSet16 = New-Object System.Data.DataSet
$dataAdapter.Fill($dataSet16)
$connection.Close()
}
$frag16 += $dataset16.Tables | Out-File 'd:\advanceddb\test5.txt'
You will need to move your connection details within the foreach loop. If you need to work with different databases, then you need to update your connection string as well.
foreach ($database in $databaselist) {
$connectionDetails = "Provider=sqloledb; " + "Server=$dataSource; " + "Database=$database; " +
"User ID=$myuserID; " + " Password=$mypassword; "
...
Since connectionDetails is not updated within your loop, you keep seeing the same data.
Related
I'm trying to run a sql query via PowerShell and return the results in a table-like format.
It's putting multiple results in one field. I suspect there's something wrong with the 'foreach' loops. What am I missing, please?
To use the code below, just change the server names from 'server1'/'server2' for your sql server instances.
$query = "
SELECT ##SERVERNAME AS ServerName
, (SELECT DB_NAME ()) AS DBName
, s.name AS SchemaName
, st.name AS TableName
, RIGHT(st.name, 8) AS Rgt8
, TRY_CONVERT(DATE, RIGHT(st.name, 8), 103) AS Rgt8Date
FROM sys.tables AS st
INNER JOIN sys.objects AS so ON so.object_id = st.object_id
INNER JOIN sys.schemas AS s ON s.schema_id = st.schema_id
"
$instanceNameList = #('server1', 'server2')
$report = #()
foreach ($instanceName in $instanceNameList) {
write-host "Executing query against SERVER/INSTANCE: " $instanceName
$dbNames = Invoke-DbaQuery -SqlInstance $InstanceName -Database "master" -Query "select name from sys.databases where database_id > 4 and name <> 'TEST'"
foreach ($database in $dbNames.Name ) {
Write-host -Activity "Current DATABASE $database" -Status "Querying: $database"
$results = Invoke-DbaQuery -SqlInstance $InstanceName -Database $database -Query $query
# <#
if ($results -is [array]) {
$CustomObject = [pscustomobject] #{
ServerName = $results.ServerName
DBName = $results.DBName
SchemaName = $results.SchemaName
TableName = $results.TableName
Rgt8 = $results.Rgt8
Rgt8Date = $results.Rgt8Date
OverOneYearOld = $results.OverOneYearOld
Drop_Table = $results.Drop_Table
}
## ADDING EACH ROW/JOB OBJECT THAT HAS BEEN REPORTED, TO THE REPORT ARRAY
$report += $CustomObject
}
}
}
$report | Select-Object ServerName, DbName, TableName | Out-GridView
Basically, you're doing the opposite of what you wanted to do, if $results -is [array] you want to iterate over it instead of add it as is to to your $report array.
On the other hand, adding elements to a fixed collection (+=) is a terrible idea.
$dbquery = #'
select name from
sys.databases
where database_id > 4 and name <> 'TEST'"
'#
$result = foreach ($instanceName in $instanceNameList) {
$params = #{
SqlInstance = $InstanceName
Database = "master"
Query = $dbquery
}
$dbNames = Invoke-DbaQuery #params
foreach ($database in $dbNames.Name) {
$params.Database = $database
$params.Query = $query
Invoke-DbaQuery #params | Select-Object #(
'ServerName'
'DBName'
'SchemaName'
'TableName'
'Rgt8'
'Rgt8Date'
'OverOneYearOld'
'Drop_Table'
)
}
}
$result | Format-Table
I am writing a script to query a SQL server to aggregate data that I can use to search through various directories. If the folder does not exist it should write the path that does not exist to a text file at the end of the code.
I created an array to prefill the strings of the paths which are completed by using the SQL data. I'm coming into the issue of input sting was not in a correct format and the issue of it not correctly filling the text document. It will fill the text document with folders that both do and do not exist.
I have tried various configurations. I believe the array could be my issue but I am currently unsure.
Error is as follows:
Cannot convert value "Walker" to type "System.Int32". Error: "Input string was not in a correct format."
At \\cottonwood\users\C.B\My Documents\Untitled1.ps1:36 char:115
+ ... Address)#> + $($Row.'Last Name') + $array[$i]
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvalidCastFromStringToInteger
Code is as follows:
$SQLServer = "REDWOOD" #use Server\Instance for named SQL instances!
$SQLDBName = "MARS"
$SqlQuery = "select Account, IsActive, [Last Name] FROM vw_loans WHERE ( Account NOT IN ('100040A','100041A','100044A','100044B','100044C','100079A','100040A','100041A','100044A','100044B','100044C','100079A','100153B','100413B')) AND LEFT(Account,1)<>'_' AND (Account NOT like '%B%') AND (LoanStatus != 'PRELIM') ORDER BY Account"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; 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
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
clear
$DataSet.Tables[0]
$array = "\I. Originations\Final Originations Package","\II. Servicing\A. Communications", "\II. Servicing\B. Foreclosure Documents","\II. Servicing\C. Bankruptcy Documents", "\II. Servicing\D. Amendments & Extensions", "\II. Servicing\E. Property", "\II. Servicing\F. Previous Servicer Data", "\III. Loan Documents", "\IV. Taxes, Insurance, HOA\HOA", "\IV. Taxes, Insurance, HOA\Insurance","\IV. Taxes, Insurance, HOA\Insurance\PMI","\IV. Taxes, Insurance, HOA\Taxes"
foreach ($Row in $dataset.Tables[0].Rows)
{
for($i=0;$i -lt $array.Length; $i++)
{
if($Row.IsActive -eq $True)
{
$CorrPath = "U:\Shared\Loan Documents - Active\" + $($Row.Account) + " - " + <#$(Row.Address)#> + $($Row.'Last Name') + $array[$i]
}
if($Row.IsActive -eq $False)
{
$CorrPath = "U:\Shared\Loan Documents - Inactive\" + $($Row.Account) + " - " + <#$(Row.Address)#> + $($Row.'Last Name') + $array[$i]
}
$FileExist = Test-Path $CorrPath
If($FileExist -eq $False)
{Add-Content $Corrpath -Path "\\cottonwood\users\IT\Missing Folder Location\MissingSubFolders.txt"}
}
}
Looks to me like the parser is confused by what the + operator is supposed to be doing. It's trying to add when it should be concatenating. Try forcing everything to a string:
if($Row.IsActive) {
$CorrPath = "U:\Shared\Loan Documents - Active\" + $($Row.Account.ToString()) + " - " + <#$(Row.Address)#> + $($Row.'Last Name'.ToString()) + $array[$i].ToString()
} else {
$CorrPath = "U:\Shared\Loan Documents - Inactive\" + $($Row.Account.ToString()) + " - " + <#$(Row.Address)#> + $($Row.'Last Name'.ToString()) + $array[$i].ToString()
}
Or else try formatting the filename differently:
$CorrPath = "U:\Shared\Loan Documents - Active\{0} - {1}{2}" -f $Row.Account,$Row.'Last Name',$array[$i]
I am attempting to query a CSV file using the Microsoft ACE OLEDB provider. When I add "PrctBusy > 60" to the where clause I receive the Error "Data type mismatch in criteria expression." I have searched StackOverFlow and used google to search for solutions, I see this is not an uncommon issue. From my readings it looks to be datatype issue. The data in the column PrctBusy is all numeric. I think I need to force it to be number but I have not found a solution.
Below is the code I am currently working with:
$ArrayNameUtil = "000198701258"
$CatNameUtil = "FE_DIR"
$sdLocalPath = "D:\Logs\SANData\Perf"
$InputCSV = "VMaxSANReportUtilFile.csv"
$csv = Join-Path $sdLocalPath $InputCSV
$provider = (New-Object System.Data.OleDb.OleDbEnumerator).GetElements() | Where-Object { $_.SOURCES_NAME -like "Microsoft.ACE.OLEDB.*" }
if ($provider -is [system.array]) { $provider = $provider[0].SOURCES_NAME } else { $provider = $provider.SOURCES_NAME }
$connstring = "Provider=$provider;Data Source=$(Split-Path $csv);Extended Properties='text;HDR=$firstRowColumnNames;';"
$firstRowColumnNames = "Yes"
$delimiter = ","
$tablename = (Split-Path $csv -leaf).Replace(".","#")
$conn = New-Object System.Data.OleDb.OleDbconnection
$conn.ConnectionString = $connstring
$provider = (New-Object System.Data.OleDb.OleDbEnumerator).GetElements() | Where-Object { $_.SOURCES_NAME -like "Microsoft.ACE.OLEDB.*" }
if ($provider -is [system.array]) { $provider = $provider[0].SOURCES_NAME } else { $provider = $provider.SOURCES_NAME }
$connstring = "Provider=$provider;Data Source=$(Split-Path $csv);Extended Properties='text;HDR=$firstRowColumnNames;';"
$firstRowColumnNames = "Yes"
$delimiter = ","
$tablename = (Split-Path $csv -leaf).Replace(".","#")
$conn = New-Object System.Data.OleDb.OleDbconnection
$conn.ConnectionString = $connstring
$conn.Open()
#
$sql = "SELECT TimeStamp, count(PrctBusy) AS Above60 FROM [$tablename] WHERE array = '$ArrayNameUtil' and Category like '$CatNameUtil' and PrctBusy > 60 Group by TimeStamp "
$cmd = New-Object System.Data.OleDB.OleDBCommand
$cmd.Connection = $conn
$cmd.CommandText = $sql
$dtp = New-Object System.Data.DataTable
$dtp.Load($cmd.ExecuteReader())
Because of the pointer from TessellatingHeckler to Codeproject and some follow on queries, I was lead to http://aspdotnetcodes.com/Importing_CSV_Database_Schema.ini.aspx. I found that a schema.ini file in the same directory as the CSV file could specify the data type.
The schema.ini file ended up in the following format:
[VMaxSANReportUtilFile.csv]
ColNameHeader=True
Format=CSVDelimited
Col1=Array Text Width 20
Col2=TimeStamp Text Width 20
Col3=Category Text Width 20
Col4=Instance Text Width 20
Col5=PrctBusy Short
Col6=QueUtil Short
I went through several revisions to get the data type correct for an ACE OLE DB provider. If the columns are named the names need to be in the schema.ini file.
This has no issue with SQL. it's when creating the rtf object.
I am connecting to a sql database and pulling information. Some of the information is html,rtf, and plain text. After about 10 mins of running I get this:
Exception setting "Rtf": "Error creating window handle."
At line:24 char:76
+ ... Name System.Windows.Forms.RichTextBox; $rtf.Rtf = $convo.Body; $body ...
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], SetValueInvocationException
+ FullyQualifiedErrorId : ExceptionWhenSetting
Has anyone else ran into this issue?
Here is the script itself.
#Who are you searching for?
#Example User ID: user#domain.com
$Subject = "changeme#domain.com"
#Set the date to search from
#Example date format: 2016-08-16.
#Leave it blank if you don't want to search for just dates.
$Date = ""
#Blank array to store the conversation history
$arr = #()
#Lync Archive Server
$SQLSvr = "ServerName Goes Here"
#Lync Archive Database
$Database = "LcsLog"
#Get the UserId's
$UserUri = Invoke-Sqlcmd -Query "Select UserUri,UserId From dbo.Users u;" -ServerInstance $SQLSvr -Database $Database
#Build the Select Statement
$select = "Select * from dbo.Users d left join dbo.Messages m on FromId = d.UserId or ToId = d.UserId Where d.UserUri = '$Subject' "
if($Date)
{
$select = $select +"and m.MessageIdTime >= '$Date 00:00:01.550' order by m.MessageIdTime asc;"
}
else
{
$select = $select + "order by m.MessageIdTime asc;"
}
#Get the conversation history
$ConvoData = Invoke-Sqlcmd -Query ($select) -ServerInstance $SQLSvr -Database $Database;
#Loop through each conversation
foreach($convo in $ConvoData)
{
#Loop through each user.
foreach($user in $UserUri)
{
#Verify the FromId
if($convo.FromId -eq $user.UserId)
{
$FromID = $user.UserUri
}
#Verify the ToId
if($convo.ToId -eq $user.UserId)
{
$ToId = $user.UserUri
}
}
#Parse the body for legible reading
switch ($convo.ContentTypeId)
{
'1' {$html = New-Object -ComObject "HTMLFile"; $html.IHTMLDocument2_write($convo.Body);$body = $html.IHTMLDocument2_body.innerText; $html.close();}
'2' {$rtf = New-Object -TypeName System.Windows.Forms.RichTextBox; $rtf.Rtf = $convo.Body; $body = $rtf.Text; $rtf.Clear();}
'3' {$body = $convo.Body}
}
#Build the Message Output
$obj = New-Object -TypeName psobject -Property #{User = $Subject; "Message Time" = $convo.MessageIdTime; From = $FromID; To = $ToId; Body = $body}
#Add data to the array
$arr += $obj
}
$arr | Select User,"Message Time",From,To,Body | Export-csv "$env:userprofile\desktop\$Subject - conversation report.csv"
Not really an answer, but a recommendation that you should turn your parameters into a Param block. It would be more useful if you wanted to call the script from the command line or turn it into a function.
Param (
# Parameter Subject
[Parameter(Mandatory = $true,
HelpMessage = 'Who are you searching for? e.g. User ID: user#domain.com')]
$Subject = 'changeme#domain.com',
# Parameter Date
[Parameter(HelpMessage = 'Set the date to search from. e.g. "2016-08-16"')]
[String]
$Date,
# Parameter SQLSvr
[Parameter(Mandatory = $true,
HelpMessage = 'ServerName Goes Here')]
$SQLSvr,
# Parameter Database
[Parameter(Mandatory = $true,
HelpMessage = 'Lync Archive Database')]
$Database = 'LcsLog'
)
I figured it out. By creating one instance of my RTF object at the beginning it corrected my error.
#Who are you searching for?
#Example User ID: user#domain.com
$Subject = "changeme#domain.com"
#Set the date to search from
#Example date format: 2016-08-16.
#Leave it blank if you don't want to search for just dates.
$Date = ""
#Blank array to store the conversation history
$arr = #()
#Create RTF and HTML Objects
$html = New-Object -ComObject "HTMLFile";
$rtf = New-Object -TypeName System.Windows.Forms.RichTextBox;
#Lync Archive Server
$SQLSvr = "Server Name goes here"
#Lync Archive Database
$Database = "LcsLog"
#Get the UserId's
$UserUri = Invoke-Sqlcmd -Query "Select UserUri,UserId From dbo.Users u;" -ServerInstance $SQLSvr -Database $Database
#Build the Select Statement
$select = "Select * from dbo.Users d left join dbo.Messages m on FromId = d.UserId or ToId = d.UserId Where d.UserUri = '$Subject' "
if($Date)
{
$select = $select +"and m.MessageIdTime >= '$Date 00:00:01.550' order by m.MessageIdTime asc;"
}
else
{
$select = $select + "order by m.MessageIdTime asc;"
}
#Get the conversation history
$ConvoData = Invoke-Sqlcmd -Query ($select) -ServerInstance $SQLSvr -Database $Database;
#Loop through each conversation
foreach($convo in $ConvoData)
{
#Loop through each user.
foreach($user in $UserUri)
{
#Verify the FromId
if($convo.FromId -eq $user.UserId)
{
$FromID = $user.UserUri
}
#Verify the ToId
if($convo.ToId -eq $user.UserId)
{
$ToId = $user.UserUri
}
}
#Parse the body for legible reading
switch ($convo.ContentTypeId)
{
'1' {$html.IHTMLDocument2_write($convo.Body);$body = $html.IHTMLDocument2_body.innerText; $html.close();}
'2' {$rtf.Rtf = $convo.Body; $body = $rtf.Text; $rtf.Clear();}
'3' {$body = $convo.Body}
}
#Build the Message Output
$obj = New-Object -TypeName psobject -Property #{User = $Subject; "Message Time" = $convo.MessageIdTime; From = $FromID; To = $ToId; Body = $body}
#Add data to the array
$arr += $obj
}
$arr | Select User,"Message Time",From,To,Body | Export-csv "$env:userprofile\desktop\$Subject - conversation report.csv"
My desired result from the below PS script is to end up with the result in a CSV or XLS file, which every is the easiest..
I run the below Powershell command, which gives me the desired results - so far so good.
I'm stuck on how to get this information into Excel, so that I can then use this for reporting..
$OracleCommand = "SELECT user_info.directory_auth_id,
user_info.display_name,
chat_account.chat_system_id,
chat_account.login_id,
chat_account.account_id,
chat_account.is_deleted,
chat_system.server_address"
$OracleCommand += " FROM user_info"
$OracleCommand += " INNER JOIN chat_account ON chat_account.user_id = user_info.entity_id"
$OracleCommand += " INNER JOIN chat_system ON chat_system.system_id = chat_account.chat_system_id"
$OracleCommand += " WHERE user_info.directory_auth_id ="
$OracleCommand += "'" + $User + "'"
Invoke-OracleCommand -OracleConnectionString (Get-Content 'ConnectionString.txt') `
-QueryString $OracleCommand |
Do I need to loop through the results and export to csv....
Thanks,
boardman
I'd go ahead and export to CSV as that makes the rest of the process easier. This code will let you import the CSV:
$csv = "C:\myData.csv"
$excel = New-Object -ComObject Excel.Application
$excel.Visible = $Show
$wbObj = $excel.Workbooks.Add()
$dataSheet = $wbObj.Worksheets.Item(1)
$qryConn = ("TEXT;" + $csv)
$qryDest = $dataSheet.Range("A1")
$conn = $dataSheet.QueryTables.Add($qryConn,$qryDest)
$dataSheet.QueryTables.item($conn.name).TextFileCommaDelimiter = $true
$dataSheet.QueryTables.item($conn.name).TextFileParseType = 1
[void]$dataSheet.QueryTables.item($conn.name).Refresh()