How to run sql script through powershell (Scripts/Commands) - sql-server

I am trying to run an sql script by writing powershell script(commands). I am using below Invoke-Command for running the sql script.
Invoke-Command -Session $sess -ScriptBlock {D:\000000000041906_JCWJOUYKDB\dm_sql1.sql}
But the script is not executing, but if I am running a bat script it is running perfectly.
Invoke-Command -Session $sess -ScriptBlock {D:\000000000041906_JCWJOUYKDB\dm_os1.bat}
The bat script are just making directories by connecting to remote machine, where as in sql scripts I have define connecting string for sql server and from there create tablespaces.

Related

Initialize database in SQL Server Linux container using Powershell Core

I'm running SQL Server in a Linux container. When the container starts, I'd like some initialization and create a database using Powershell Core.
My Dockerfile looks like this:
FROM mcr.microsoft.com/mssql/server:2017-latest
ENV ACCEPT_EULA="Y" `
DATA_PATH="./data" `
sa_password="MyP#ssw0rd"
VOLUME ${DATA_PATH}
WORKDIR ./init
RUN apt-get update
RUN apt-get install -y powershell
COPY SomeFolder/Initialize-Database.ps1 .
CMD pwsh ./Initialize-Database.ps1 -sa_password $env:sa_password -data_path $env:DATA_PATH -Verbose
In the Powershell script I'm installing the SQLServer module in order to perform SQL queries.
Set-PSRepository -Name PSGallery -InstallationPolicy Trusted
Install-Module SQLServer
if ($sa_password -ne "_") {
Write-Verbose 'Changing SA login credentials'
$sqlcmd = "CREATE DATABASE my-db"
Invoke-SqlCmd -Query $sqlcmd -ServerInstance "."
}
The Invoke-SqlCmd command fails with a connection error:
A network-related or instance-specific error occurred while
| establishing a connection to SQL Server. The server was not
| found or was not accessible. Verify that the instance name is
| correct and that SQL Server is configured to allow remote
| connections. (provider: TCP Provider, error: 40 - Could not
| open a connection to SQL Server)
How do I check if the SQL instance is started and if not, how can I start it?
When I start a container using this image and exec into the container, Get-SqlInstance -ServerInstance "." -Credential Get-Credential fails with the error 'Failed to connect to server'.
Found it. In the Dockerfile, I'm now calling the Powershell script after SQL has started:
CMD ( /opt/mssql/bin/sqlservr & ) | grep -q "Service Broker manager has started" \
&& pwsh ./Initialize-Database.ps1 -sa_password $SA_PASSWORD -data_path $DATA_PATH -Verbose
https://www.kenmuse.com/blog/devops-sql-server-dacpac-docker

How to run the PowerShell batch file or a command.ps1 file through SQL server if sql is in one sever and file is in another server

I want to connect two VM/server one has data file and batch file another have sql install wanted to trigger command of server A which will hit server b files
Sql command--- in server A
EXEC master..xp_cmdshell 'cd.. && "C:\Program Files\Powershell\6\pwsh.exe" -File "C:\Users\sprasad\Desktop\script\command1.ps1"'
error are
1- import-module: The specified module 'C:\Program
Files\Derivation_19_01_rev0\Core.PowershellModule.TradeLoader.dll' was
not loaded because no valid module file was found in any module
directory.
because files are in server B
I am running sql scripts stored in files (sqlscript.sql) on ServerA against a SQL installation on ServerB using remote powershell. The Powershel module SQLPS is needed on serverA.
see link
steps:
enable remotepowershell on serverB
Enable-PSRemoting -force
in your SQL server, add the user that executes the script on serverA in the list of users with rights on the database.
use a script on severA like:
Import-Module -Name SQLPS -NoClobber -DisableNameChecking -Scope Local Invoke-Sqlcmd -ServerInstance serverA -InputFile sqlscript.sql
-Verbose
Invoke-Sqlcmd -ServerInstance 'serverB' -InputFile sqlscript.sql -Verbose

TFS Run batch script on a remote server with admin permission

I currently have Server A which is where my TFS and Build Agent is located. I then have Server B which is when my source code site. I am trying to set up a build definition and copies file from on location in server B to another and then build the solution.
However when I run this batch file as part of a build definition it is not creating folders where it need to be. I believe due to the agent not having correct permissions.
Is there a way to run the following batch script to run with Admin permission from a build definition.
You can try below workarounds:
Convert the batch script to PowerShell script, then copy the
PowerShell script to target machine and use the PowerShell on Target
Machines task to run the script. You can enter your admin user
and password using the task. Reference below screenshot.
Add a PowerShell task and run below script to call the cmd.exe to
run the batch script with an admin user account on target machine
(Copy the batch script to target machine first, in below sample I
copied the batch script to C:\Scripts\Test.bat):
Param(
[string]$computerName = "v-tinmo-12r2",
)
$Username = "Domain\user"
$Password = ConvertTo-SecureString "password-here" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($Username,$password)
Invoke-Command -ComputerName $computerName -Credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'C:\Scripts\Test.bat'"}

SQL Powershell Error: Invoke-Sqlcmd : The term 'Invoke-Sqlcmd' is not recognized as the name of a cmdlet

When I try to run a powershell script I get the following error:
Invoke-Sqlcmd : The term 'Invoke-Sqlcmd' is not recognized as the name of a cmdlet, function, script file, or operable program.
So in Powershell I ran the following:
install-module sqlserver
update-module sqlserver
import-module sqlserver
This all runs fine. However when I rerun my script I still get the same error.
I have also installed powershelltools.msi, downloaded as part of the SQL Server 2014 Feature pack here: https://www.microsoft.com/en-gb/download/details.aspx?id=42295
If I run this command:
Get-Command -Module sqlserver
I get this result:
CommandType Name Version Source
----------- ---- ------- ------
Alias Decode-SqlName 21.0.17224 sqlserver
Alias Encode-SqlName 21.0.17224 sqlserver
Function SQLSERVER: 21.0.17224 sqlserver
Any ideas on what else I should try?
I have SQLServer 2014 and Powershell Version 5
Are you using Powershell Core (v6.1)?
I was having a similar issue and found this SO answer. Turns out the SQLServer module for Powershell Core doesn't include the Invoke-SqlCmd (among others). I switched back to the 64-bit version of Powershell I have installed on Windows 10 (v5.1) and installed, then imported the sqlserver module. Invoke-SQLCmd is now listed.
Install-Module -Name SqlServer -AllowClobber
Import-Module -Name SqlServer -Force
Get-Command -Module SqlServer
Import-Module imports a module only to current powershell session, not globally. Add the import to your script or to profile.
Was searching a solution for the same problem and found the below worked for me.
find-module sqlserver | Install-Module -AllowClobber -Force
Original Answer: https://social.technet.microsoft.com/Forums/en-US/f3a52235-e62a-402e-9b1b-0b0c0cdd17aa/sql-powershell-error-invokesqlcmd-the-term-invokesqlcmd-is-not-recognized-as-the-name-of-a?forum=winserverpowershell
I had the same problem. Apparently I had to unblock all the dll files in the new module folder. In my case C:\Program Files\WindowsPowerShell\Modules\SqlServer.
I found the link here how to do it.
https://www.404techsupport.com/2016/06/24/unblock-files-powershell/
dir -Path [directory path] -Recurse | Unblock-File
Close powershell if you still have a session open.

Using a batch file on a remote computer's powershell scripts

When using a command like
powershell -command "\\%host1%\supportfiles\mypowershellscript"
from my central server to a remote computer, would it be using that powershell on the remote computer or on my own computer when I run it using the batch?
When you execute:
PowerShell -command <path to a script>
The script, whether it is located on the local machine or on a remote machine, will execute locally. If you want to execute some PowerShell script remotely, you need to enable remoting on the remote machine using Enable-PSRemoting -force. Then on the local machine, you have to execute your script as administrator and your account also has to have admin privileges on the remote machine. Inside your script you can execute parts of the script remotely like so:
$session = New-PSSession remoteComputerName
Invoke-Command -Session $session -Scriptblock { ... script to execute on remoteComputerName ...}
...
Remove-PSSession $session

Resources