Can we display the sql result filled in $dataset on the ISE console or do we need a GUI? - sql

I want to display sql results in powershell console
I have a query that list documents based on the customer code, I was able to output them to a CSV, but I am thinking if I could display them on the console and then do operations like Copy, delete etc.
Or do I need .net web UI to display the results?

cls
$SQLserver = "YourSQLserverName"
$SQLDB = "YourDbName"
$SQLQuery = "SELECT * from [DBName].[dbo].[YourTableName]" # Whatever is your query
$Result = SQLCMD -S $SQLserver -d $SQLDB -Q $SQLQuery -s "~" -W
Write-Host "Display SQL Dataset in the console"
Write-Output $Result # Display the dataset in console

Related

Get-Disk values are different in powershell and in sql database

Hi i'm completely new to this ,i want to store capacity in particular format. Mycode showing correct format but in SQL database its value is getting changed to default.
My code:
$SSDCapacity= Get-Disk | select Size
foreach($size in $SSDCapacity)
{
$variable = $size.Size.ToString()
}
$result = $variable.SubString(0,3)
$result
Above code shows output as 512 in powershell.
But when i store it in database its showing in default form #{Size=512110190590}
I have a insert query for SQL Part
$InsertQuery="INSERT INTO [$($Database)].[dbo].[$($name)]
([ComputerName],[Model],[SSDCapacity])
VALUES('$ComputerNameValue','$ModelValue','$result')
"
then i'm just calling above query for insert
#Insert into Table
$SqlCmd.CommandText = $InsertQuery
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
#Creating Dataset
$Datatable = New-Object "System.Data.Datatable"
$result = $SqlCmd.ExecuteNonQuery()
$conn.Close()
So how can i store in format powershell shows.
I might be missing out some silly things here.
Any help will be thankfull.
You could do that in one line using DBATOOLS
Install-Module dbatools -Scope CurrentUser #only once
Get-DbaDiskSpace|select ComputerName, Name, Capacity, Free|Write-DbaDataTable -SqlInstance $sql -Database TEMPDB -Table disk -AutoCreateTable

Using PS to query SQL for list of users, then disable Active Directory accounts?

I'm trying to use Powershell to query SQL database for a list of suspended users, pipe into a variable, then use that to loop through and disable those AD accounts. Here's the code I'm using... note I'm just trying to write the output now instead of making a change so I don't do anything I regret.
Import-Module ActiveDirectory
$Users = Invoke-Sqlcmd -ServerInstance 'SERVER' -Database 'NAME' -Query "SELECT EmployeeID,
EmployeeStatus FROM [NAME].[dbo].[employee] WHERE EmployeeStatus = 'S'"
foreach ($user in $users)
{
Get-ADUser -Filter "EmployeeID -eq '$($user.EmployeeID)'" `
-SearchBase "OU=Logins,DC=domain,DC=com" |
#Set-ADUser -Identity $Name -Enabled $False
Write-Verbose $User
}
The SQL query is working fine, but when I run the loop it's giving this error:
Write-Verbose : The input object cannot be bound to any parameters for
the command either because the
command does not take pipeline input or the input and its properties do not match any of the parameters that take pipeline
input.
Am I just formatting this incorrectly? Or is there another way I should be thinking of this?
Thanks in advance!
If you would like to find inactive user accounts in Active Directory, you can use the Search-ADAccount cmdlet. You need to do this use the “-AccountInActive” parameter with Search-ADAccount.
PowerShell command below:
Search-ADAccount –AccountInActive –TimeSpan 120:00:00:00 –ResultPageSize 2000 –ResultSetSize $null | ?{$_.Enabled –eq $True} | Select-Object Name, SamAccountName, DistinguishedName | Export-CSV “C:\Temp\InActiveADUsers.CSV” –NoTypeInformation
I have given timespan for 120days and export the list into csv file.

Is there a possibility to send a telnet command or start a bat file when I get a result in a SQL View?

I would like to send a Telnet command or start a *.bat file when I get a result in a SQL view.
I am using SQL Express and so don't have the SQL Server Agent.
I am trying to launch a cue in a lighting software, 30 minutes before one of our shows starts.
The software listens to Telnet commands or bat files.
Could anyone suggest a free software of a way to do this from within SQL Express Server thru SSMS?
Thanks in advance,
I think the best option you have is to use Windows Task Scheduler. Create a PowerShell script that selects the records from your View and if the count is greater than 0 launch the .bat file .
Example :
$query = "SELECT * FROM MY_VIEW"
$results = Invoke-Sqlcmd -ServerInstance "yourserver\instance" -Database "yourdatabase" -Username "username" -Password "password" -Query $query
if ($results.Count() -gt 0){
C:/path_to_bat_file.bat
}
Links :
https://learn.microsoft.com/en-us/powershell/module/sqlserver/invoke-sqlcmd?view=sqlserver-ps
https://learn.microsoft.com/en-us/powershell/module/nettcpip/test-netconnection?view=win10-ps

T-SQL file into powershell script

I have a txt file(load_check_run_bmu.sql) that contains the following sql code.
RESTORE DATABASE Address from disk='C:\dir\path\address.bmu'
Use Client
GO
Select f_name
From
cst.name
USE wage
GO
Exec sp_salary
Use Client
GO
Select f_name
From
cst.name
I then have a batch file that contains:
sqlcmd -S .\NorthWind -i"C:\scripts\load_check_run_bmu.sql"
What I need to do is be able to execute all of necessary SQL commands in a powershell script and eliminate the sql txt file and the sqlcmd batch file
I'm aware I would need the following code, but I am struggling on how to convert the T-SQL script into something usable for the $SqlCmd.CommandText variable
$sqlServer = "."
$sqlDBName = "NorthWind"
$sqlConnectionString ="Server = $sqlServer; Database = $sqlDBName; Integrated Security = True"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = $sqlConnectionString
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
**$SqlCmd.CommandText = [SQL Command(s)]<====( Need assistance populating this)**
$SqlCmd.Connection = $SqlConnection
$SqlCmd.Connection.Open()
$ReturnValue = $SqlCmd.ExecuteNonQuery()
$SqlCmd.Connection.Close()
Put the T-SQL .txt file into a string using double quotes " and take out the GO statements. You can also end each statement with ; to ensure queries do not get mixed up and the queries should run without failure:
$TSQLString = "RESTORE DATABASE Address from disk='C:\dir\path\address.bmu';
Use Client;
Select f_name
From
cst.name;
USE wage;
Exec sp_salary;
Use Client;
Select f_name
From
cst.name;"
Then use the string for your variable:
$SqlCmd.CommandText = $TSQLString
It also looks like you using multiple databases in the query above. If this is the case this approach might not work has you are connecting to a single database with the statement below.
$sqlConnectionString ="Server = $sqlServer; Database = $sqlDBName; Integrated Security=True"
To get round this you will need to open up a connection for each statement. So you might want to make a function that connects to a server\database and runs a given query e.g (Run-Sql would be the function you need to create).
$SQLQuery1 = "RESTORE DATABASE Address from disk='C:\dir\path\address.bmu';"
$SQLQuery2 = "Select f_name From cst.name;"
$SQLQuery3= "Exec sp_salary;"
$SQLQuery4 = "Select f_name From cst.name;"
# Run all statments
Run-SQL -query $SQLQuery1 -DB "NorthWind" -Server "."
Run-SQL -query $SQLQuery2 -DB "Client" -Server "."
Run-SQL -query $SQLQuery3 -DB "wage" -Server "."
Run-SQL -query $SQLQuery4 -DB "Client" -Server "."
Use invoke-SQLCMD
Whick is part of sqlps module

Powershell Job within SQL Server Agent

I am having trouble with a powershell job returning a result set when it runs, it runs successfully but no results. I am running it against a list of servers. If I run the script against a specific server that I know I can connect to, it runs fine and gives results.
This is a script within the sql server agent running powershell. Am I using the SMO object right? Ive tried to use a try/catch (job fails), ive tried to add -ErrorAction "Continue" to the script (job fails), using smo to resolve a server name in order to use the if statement (job succeeds) but no results. Here is the script:
$ErrorActionPreference = "Continue";
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
$instanceNameList = Get-Content "c:\Scripts\InPutFiles\servers.txt";
$results = #()
foreach($instanceName in $instanceNameList)
{
$serverObject = New-Object Microsoft.SqlServer.Management.Smo.Server($instanceName)
$serverName = $serverObject.ComputerNamePhysicalNetBIOS;
if($serverName -ne $null) {
$results += Invoke-Sqlcmd -Query "
(My Query is in here!)
" -ServerInstance $instanceName.Name}
$instanceName| Where-Object {$_} | Export-csv 'C:\scripts\HungJobs_UnabletoConnect.csv' -NoTypeInformation
}
$results| Where-Object {$_} | Export-csv 'C:\scripts\HungJobs.csv' -NoTypeInformation
Mid-way through your script, is the $scripts variable being populated properly by the Invoke-Sqlcmd?
If so, I'm thinking that you should be able to do away with Where-Object {$_} on your last two commands. Where-Object is used as a filter, and in these two cases it doesn't seem to be filtering anything. You should just be able to directly export the $instanceName and $results directly to csv.