Good day
Iam looking way how to run sql command only if exist file/s in specific folder ? I read lot of staff but i cant not fit my skript . I do not want do make SSIS I want do to in Powershell.
Then I will put into MSQL Job Agent powershell script wchich will run every hour . If this Job find .csv file /s then will start other Job.
Thank you for opinion.
$SourceFile = "C:\Import\FOLDER\report\Old\test\*.csv"
Action = "Invoke-Sqlcmd -ServerInstance "100.000.000.001" -Query "USE msdb ; EXEC dbo.sp_start_job N'MSSQLJOBNAME' ;"
if(Test-Path -Path $SourceFile)
{
"Invoke-Sqlcmd -ServerInstance "100.000.000.001" -Query "USE msdb ; EXEC dbo.sp_start_job N'MSSQLJOBNAME' ;"
}
specifying the folder and *.csv in a variable is not enough; you have to get the filelist.
for running the sql command in the database msdb I added the parameter -Database
$SourceFilesArray = Get-ChildItem -Path "C:\Import\FOLDER\report\Old\test\" -Filter "*.csv"
if($SourceFilesArray) {
# $SourceFilesArray is not empty/contains list of specified files
Invoke-Sqlcmd -ServerInstance "100.000.000.001" -Database "msdb" -Query "EXEC dbo.sp_start_job 'MSSQLJOBNAME'"
} else {
# run this if $SourceFilesArray is empty/no files found
Invoke-Sqlcmd -ServerInstance "100.000.000.001" -Database "msdb" -Query "EXEC dbo.sp_start_job 'MSSQLJOBNAME'"
}
Related
I want to invoke a sql query/SP on sql job in a ssis server using a powershell script but I don't know how to do that. I've used powershell to run sql queries on sql database but not jobs on ssis. Here is what I have till now-
$ssisServer = New-Object -TypeName Microsoft.SQLServer.Management.Smo.Server($name_of_server)
$IntegrationServices = New-Object "Microsoft.SqlServer.Management.IntegrationServices.IntegrationServices" $ssisServer
$catalog = $IntegrationServices.Catalogs[$catalog]
$folder = $catalog.Folders[$folder]
$project = $folder.Projects[$project]
$sqlJob = $ssisServer.JobServer.Jobs[$existing_job_name]
query= " some sql query "
if ($sqlJob) {
$sqlJob.CurrentRunStatus()
# here I need to run a query on the job
}
The query could be to get details of the job or perform some action on it. Also is this enough as we are just giving the server name here $sqlJob = $ssisServer.JobServer.Jobs[$existing_job_name] to get the job which in a particular folder->project->job? I couldn't try this yet and haven't found much resources on it. Please give me some help to work with.
I didn't work with the SSIS server. But the principle of running SQL queries from SQL is pretty simple.
You should have proper module or you can use snapin of SQL.
I will continue from the second one.
# If you have an SQL server on your server, so this is the possible path where they can be.
$PossiblePaths = 'C:\Program Files\Microsoft SQL Server','C:\Program Files (x86)\Microsoft SQL Server'
# Lets check where we have PSProvider.dll and PSSnapins.dll
$PossiblePaths | ForEach-Object {
Test-Path -Path $_
{
$SQLPSProvider = (Get-ChildItem -Filter "Microsoft.SqlServer.Management.PSProvider.dll" -Path $_ -Recurse).FullName
$SQLPSSnapIn = (Get-ChildItem -Filter "Microsoft.SqlServer.Management.PSSnapins.dll" -Path $_ -Recurse).FullName
}
}
# Lets find Install Utility to add them with it.
$InstallUtil = (Get-ChildItem -Filter "InstallUtil.exe" -Path "$env:windir\Microsoft.NET\Framework64\v2.0*" -Recurse).FullName
if (($null -eq $SQLPSProvider) -or ($null -eq $SQLPSSnapIn))
{
Write-Host "Sorry, SQL PowerShell SnapIn or PowerShell Provider not found." -ForegroundColor Red
}
else
{
# Adding them to our system.
Start-Process -FilePath $InstallUtil -ArgumentList "-i $SQLPSProvider"
Start-Process -FilePath $InstallUtil -ArgumentList "-i $SQLPSSnapIn"
}
# Now they should be in the system and we can add them to our PowerShell session.
Add-PSSnapin -Name SqlServerCmdletSnapin100
Add-PSSnapin -Name SqlServerProviderSnapin100
# Now we should have Invoke-Sqlcmd like if we had SQLServer module.
$SQLServer = "SQL2012"
$SQLInstance = "JustForExample"
$ServerInstance = $SQLServer + '\' + $SQLInstance
# So you typing query for example like attaching DB.
$Query = "CREATE DATABASE ExamleDB ON (FILENAME = `'C:\DBs\ExamleDB.mdf`'), (FILENAME = `'C:\DBs\ExamleDB_log.ldf`') FOR ATTACH"
# And then executing it with Invoke-Sqlcmd like that.
Invoke-Sqlcmd -ServerInstance $ServerInstance -Username 'sa' -Password 'Abcde12345' -Query "Query"
This is my script...
Invoke-Sqlcmd -ServerInstance "database" -Username "QQQ" -Password "abc123$" -Database "Cars" -InputFile $PathToGamePreset"PreIn*.sql" -Verbose
Error...
Invoke-Sqlcmd : Illegal characters in path. At line:59 char:5
As #Abra mentions, the first step is to get the file name first with Get-ChildItem, and then you can run the SQL script.
If you have only a single file matching the path, you can do something like this:
$SQLFile = Get-ChildItem $PathToGamePreset"PreIn*.sql"
Invoke-Sqlcmd -ServerInstance "database" -Username "QQQ" -Password "abc123$" -Database "Cars" -InputFile $SQLFile.FullName -Verbose
I'm spinning up a SQL server ready for deployment. Using AWS userdata, everything is being configured to this stage using PowerShell. However, the database needs to have Filestream enabled at level 2, but I can't find a way to do this using PowerShell or any other command-line utility.
The script I've written for this part is this:
Import-Module SQLPS -DisableNameChecking
$instanceName = $env:COMPUTERNAME
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
$server.Configuration.FilestreamAccessLevel.ConfigValue = 2
$server.Alter()
Set-ExecutionPolicy RemoteSigned -force
Invoke-Sqlcmd "EXEC sp_configure filestream_access_level, 2"
Invoke-Sqlcmd "RECONFIGURE"
Get-Service -Name MSSQLSERVER | Restart-Service -force
$server.Properties | clip
$server.Configuration | clip
import-module SQLPS -DisableNameChecking
But it's not enabling Filestream.
Does anyone have any ideas on how I can get this working?
Posting this as an answer in case the blog goes offline.
This worked for me for SQL Server 2019:
# Enable FILESTREAM
$instance = "MSSQLSERVER"
$wmi = Get-WmiObject -Namespace "ROOT\Microsoft\SqlServer\ComputerManagement15" -Class FilestreamSettings | where {$_.InstanceName -eq $instance}
$wmi.EnableFilestream(3, $instance)
Get-Service -Name $instance | Restart-Service
Set-ExecutionPolicy RemoteSigned
Import-Module "sqlps" -DisableNameChecking
Invoke-Sqlcmd "EXEC sp_configure filestream_access_level, 2"
Invoke-Sqlcmd "RECONFIGURE"
Easiest way is to use DBATOOLS.
Install-Module dbatools -Scope CurrentUser
Enable-DbaFilestream -SqlInstance $env:COMPUTERNAME
I have a PowerShell script that would recursively loop a dir and subdir and run all SQL files inside of it and log the execution in .log files 1 for success and 1 for exceptions. The PowerShell script does what its supposed to do but in the cmd window, I see this error:
Get-Content : A parameter cannot be found that matches parameter name 'Raw'
from this line
$query = Get-Content -Path $_.FullName -Raw
This statement runs within a loop, so FullName changes per iteration. This is the version I use.
Name : Windows PowerShell ISE Host
Version : 5.0.10586.117
Sample script goes below:
Get-ChildItem $ScriptFolder -Recurse -Exclude "*Archive*" -Filter *.sql |
sort Directory |
ForEach-Object {
$query = Get-Content -Path $_.FullName -Raw
$result = SQLCMD -S $FullDBServer -E -I -Q $query -d $Database
Any thoughts?
The -Raw parameter of Get-Content was introduced in PS3.
To get file contents in one string there are several methods.
The fastest method that works in any PS version:
$text = [IO.File]::ReadAllText('c:\path\file.ext')
The 2 times slower method for PS3+:
$text = Get-Content 'c:\path\file.ext' -Raw
The 100 times slower PS2-compatible alternative:
$text = Get-Content 'c:\path\file.ext' | Out-String
The 30 times slower PS2-compatible alternative:
$text = Get-Content 'c:\path\file.ext' -ReadCount 1000 | Out-String
I've experienced this error in ps v 5 when the -path parameter wasn't actually a path.
Try adding Write-Host $_.fullname above the line throwing the error to make sure $_.fullname is actually what you think it is.
You're using PowerShell v2 or earlier. The parameter -Raw was introduced with PowerShell v3. Either upgrade PowerShell or pipe the output of Get-Content through Out-String:
$query = Get-Content -Path $_.FullName | Out-String
You should also be able to run the files directly with sqlcmd (i.e. without reading their content and passing that to the command):
$result = SQLCMD -S $FullDBServer -E -I -i $_.FullName -d $Database
I had this sqlcmd snippet working in batch but when I converted to powershell, it broke. This is what I am attempting to call using powershell
Sqlcmd -S localhost\instance -d database -U username -P password -i "sqlQuery.sql" -s "," > \sqlOutput.csv -I -W -k
I tried invoke-sqlcmd but i get the error "The term 'invoke-sqlcmd' is not recognized as the name of a cmdlet, function, script file, or operable program"
In regards to the comment below, I have loaded the snapins required. This did help but I am now getting this error. "Invoke-sqlcmd : Parameter cannot be processed because the parameter name 's' is ambiguous.
If I put it in single quotes...
invoke-Sqlcmd '-S localhost\instance -d database -U username -P password -i "sqlQuery.sql" -s "," > \sqlOutput.csv -I -W -k'
I get the error "A network-related or instance-specific error occurred while establishing a connectiong to sql server. Which doesn't make sense to me as the same credentials i am using here (on the same box) work when called from batch.
You have to first call sqlps.exe from powershell or command prompt (assuming you have the SQL Server snap-ins for Powershell installed).
Once you do that, execute get-help Invoke-Sqlcmd to find your way around.
To your question, its not -S, but -ServerInstance
PS SQLSERVER:\> Invoke-Sqlcmd -ServerInstance "srvrName" -Database "master" -Username "user123" -Password "x$34fth"
-InputFile "C:\Users\testUser\Desktop\test.sql" | Out-File "C:\Users\testUser\Desktop\out.txt"
You can also use the MSDN documentation
Goto
Windows Explorer
Right Click Computer
Properties
Advanced System Settings
Environment Variables
Make sure PSModulePath is set with following string.
C:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules