I am trying to use PowerShell and Windows Search to get some statistics of my disk usage. This is what I came up for so now:
$sql = "SELECT System.FileExtension, System.Size FROM SYSTEMINDEX WHERE DIRECTORY = 'C:\Users\...\Documents' AND System.FileExtension = '.docx'"
$provider = "provider=search.collatordso;extended properties=’application=windows’;"
$connector = New-Object System.Data.OleDb.OleDbDataAdapter -Argument $sql, $provider
$dataset = New-Object System.Data.DataSet
if ($connector.fill($dataset)) {
$res = $dataset.Tables[0]
$res | Group-Object System.FileExtension |
Select-Object System.FileExtension,
#{Name='Total';Expression={($_.Group | Measure-Object SYSTEM.Size -Sum).Sum}} |
Format-Table
}
This works, but it looks kind of ugly. I also found and tried this:
$sql = "SELECT System.Size FROM SYSTEMINDEX WHERE DIRECTORY = 'C:\Users\...\Documents' AND System.FileExtension = '.docx'"
$provider = "provider=search.collatordso;extended properties=’application=windows’;"
$connector = New-Object System.Data.OleDb.OleDbDataAdapter -Argument $sql, $provider
$dataset = New-Object System.Data.DataSet
if ($connector.fill($dataset)) {
$dataset.Tables[0].Compute("Sum(SYSTEM.Size)")
}
which looks a lot nicer, but throws an error:
Cannot find an overload for "Compute" and the argument count: "1"
Related
I'm building a simple GUI where support staff can look up basic user information. The GUI is supposed to pull this data from an SQL DB, but nothing happens when the button is pressed.
function SQLquery {
param (
[Parameter(Mandatory = $true)]
[ValidateSet('NemOrgDB')]
[string]
$System,
[string]
$Query
)
switch ($System) {
NemOrgDB { $ConnectionString = 'Place holder for Stack Overflow' }
}
#New SqlConnection object
$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = $ConnectionString
$sqlConnection.Open()
#New Sqlcommand object
$sqlCommand = New-Object System.Data.SqlClient.SqlCommand
$sqlCommand.Connection = $sqlConnection
$sqlCommand.CommandText = $Query
#Create new sqldataadapter object
$sqlDataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$sqlDataAdapter.SelectCommand = $sqlCommand
#Create new dataset object
$DataSet = New-Object System.Data.DataSet
#Fill dataset with dataadapter input
try {
$sqlDataAdapter.Fill($DataSet) | Out-Null
$output = $DataSet.Tables
}
catch {
$output = $null
}
#Close sql connection
$sqlConnection.close()
$null = $sqlConnection
$output
}
Here is the Function in use:
#Søgnigns criteria
$EmployeeID = Read-Host -Prompt "What user to find?"
#SQL Query
SQLquery -System NemOrgDB -Query "Select [medarbejder_wnr]
,[navn]
,[stilling]
,[stilling_nr]
,[firmakode_txt]
FROM [PersonData_NemOrg].[dbo].[Personale]
WHERE medarbejder_wnr ='$EmployeeID';"
The 2 pieces of code work as they should in a console environment with no Gui attached, they return the following results:
EmployeeID: EmployeeID
Name: Name
Role: IT support
Role number : Number
fimakode_txt : Company
When the same code is run inside the GUI nothing happens, here is the GUI code:
#ButtonSearch
#
$ButtonSearch.BackColor = [System.Drawing.SystemColors]::ActiveBorder
$ButtonSearch.FlatStyle = [System.Windows.Forms.FlatStyle]::System
$ButtonSearch.Font = (New-Object -TypeName System.Drawing.Font -ArgumentList #([System.String]'Tahoma',[System.Single]9,[System.Drawing.FontStyle]::Bold,[System.Drawing.GraphicsUnit]::Point,([System.Byte][System.Byte]0)))
$ButtonSearch.Location = (New-Object -TypeName System.Drawing.Point -ArgumentList #([System.Int32]12,[System.Int32]118))
$ButtonSearch.Name = [System.String]'ButtonSearch'
$ButtonSearch.Size = (New-Object -TypeName System.Drawing.Size -ArgumentList #([System.Int32]150,[System.Int32]23))
$ButtonSearch.TabIndex = [System.Int32]24
$ButtonSearch.Text = [System.String]'Search'
$ButtonSearch.UseCompatibleTextRendering = $true
$ButtonSearch.UseVisualStyleBackColor = $false
$ButtonSearch.add_Click($ButtonSearch_Click)
#
AND
$ButtonSearch_Click = {
$Wnummer = $TextBoxWnummer1.Text
SQLquery -System NemOrgDB -Query "Select [medarbejder_wnr]
,[navn]
,[stilling]
,[stilling_nr]
,[firmakode_txt]
FROM [PersonData_NemOrg].[dbo].[Personale]
WHERE medarbejder_wnr ='$Wnummer';"
}
It simply returns nothing.
Can someone help me and point out why my script isn't looping through my server list and not inserting all the data to my sql table?
$SQLserverDB = #()
$SQLserverDB = get-content "D:\Temp\servers.txt"
foreach ($SQLserver in $SQLserverDB) {
$server = New-Object Microsoft.sqlserver.management.smo.server($SQLserver)
Write-Host "--Server List:"$server"---" -ForegroundColor Yellow
foreach ($db in $Server.Databases) {
$dbobj = New-Object PSObject -Property ([ordered]#{
Instance_Name = $db.Parent
Database_Name = $db.Name
Database_ID = $db.id
Active = $db.Status
DateStamp = $db.CreateDate
Owner = $db.Owner
Compatibility_Level = $db.compatibilitylevel
Recovery_Model = $db.recoverymodel
DB_Size_MB = [Math]::round($db.size, 2)
}
)
}
}
$dt = Out-DbaDataTable -InputObject $dbobj
Write-SqlTableData -ServerInstance localhost -DatabaseName DBA_Central -SchemaName dbo -TableName database_masters2 -InputData $dt
How can i display the output of a postgresql in powershell. Here is an example:
$query = "SELECT * FROM test where first_name='test'"
function Get-ODBC-Data{
param([string]$query=$(throw 'query is required.'))
$conn = New-Object System.Data.Odbc.OdbcConnection
$conn.ConnectionString = "Driver={PostgreSQL Unicode(x64)};Server=localhost;Port=5432;Database=Test;Uid=test;Pwd=test;"
$conn.open()
$cmd = New-object System.Data.Odbc.OdbcCommand($query,$conn)
$ds = New-Object system.Data.DataSet
(New-Object system.Data.odbc.odbcDataAdapter($cmd)).fill($ds) | out-null
$conn.close()
$ds.Tables[0]
}
function Set-ODBC-Data{
param([string]$query=$(throw 'query is required.'))
$conn = New-Object System.Data.Odbc.OdbcConnection
$conn.ConnectionString= "Driver={PostgreSQL Unicode(x64)};Server=localhost;Port=5432;Database=test;Uid=test;Pwd=test;"
$cmd = new-object System.Data.Odbc.OdbcCommand($query,$conn)
$conn.open()
$cmd.ExecuteNonQuery()
$conn.close()
}
$result = Get-ODBC-Data -query $query
$db = set-odbc-data -query $query
How can i display or fetch values present in the output in a format shown in the screenshot?
How can i export the output to a csv in a proper format?
I didn't test it but try to use below commands as the output from powershell script
C:\Get-Query | Out-GridView
C:\Get-Query | Export-CSV Info.csv
C:\Get-Query | Format-Table -autosize
assuming the script in the file named Get-Query
The solution from this URL
I have the following code which returns what I need but I am struggling to output this to a table from which I can further query.
$instances = invoke-sqlcmd –ServerInstance "myserver" –Database "my db" –query "select instanceconnectname from [dbo].[smytable] WHERE InstanceConnectName LIKE '%CLU%' and connect = 1"
Write-Host $instances.instanceconnectname
foreach ($svr in $instances.instanceconnectname){
$dt = new-object "System.Data.DataTable"
$cn = new-object System.Data.SqlClient.SqlConnection "server=$svr;database=master;Integrated Security=sspi"
$cn.Open()
$sql = $cn.CreateCommand()
$sql.CommandText = "SELECT ##SERVERNAME AS ServerName, SERVERPROPERTY('ComputerNamePhysicalNetBIOS') As ActiveNode"
$rdr = $sql.ExecuteReader()
$dt.Load($rdr)
$cn.Close()
$dt | Format-Table -autosize
}
I have been reading about some custom functions out there is that the only way to do this really? I had thought I could just do some kind of SQL Insert but not figured out how to do it.
Instead of outputting to a DataTable, I would output to a DataSet, which you can then further query. e.g.:
$cn = new-object System.Data.SqlClient.SqlConnection "server=$svr;database=master;Integrated Security=sspi"
#Create the SQL Command from a connection string
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "SELECT ##SERVERNAME AS ServerName, SERVERPROPERTY('ComputerNamePhysicalNetBIOS') As ActiveNode"
$SqlCmd.Connection = $cn
#Create the SQL DataAdapter
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
#Fill the DataSet
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
Now with it in a DataSet, you can query it, like this:
$DataSet.tables[0].select("ServerName like 'Bob%'")
Hopefully that is enough to get you started...
I have a pretty straight-forward function for grabbing SQL results:
function RunSqlCommand($sql)
{
$connection = $null
$command = $null
try
{
$connectionString = "data source=localhost; integrated security=true"
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
$command = $connection.CreateCommand()
$command.CommandText = $sql
$adapter = New-Object System.Data.SqlClient.SqlDataAdapter($command)
$dataSet = New-Object System.Data.DataSet
$adapter.Fill($dataSet)
$results = $dataSet.Tables | Select-Object -ExpandProperty "Rows"
return $results
}
finally
{
if ($command -ne $null) { $command.Dispose() }
if ($connection -ne $null) { $connection.Dispose() }
}
}
Whenever there are no results, the $results variable is $null. However, when I inspect the return value in the calling method, it magically becomes 0.
Is PowerShell doing something behind the scenes? I really do want to return $null to represent "no results".
$adapter.Fill() returns the number of rows added or refreshed in the dataset.
To fix, you can do this:
[void]$adapter.Fill($dataSet)
or
$adapter.Fill($dataset) | out-null