How to capture all outputs from a powershell script? - sql

I am working on script "executeAll.ps1" that would execute multiple "execute.ps1" scripts. I am trying to capture the outputs of each execute.ps1 window but the problem is that the script execute .sql commands from a dacpac and the PRINTS only shows in the powershell window but not in any of my output files.
I have tried having *>> in my executeAll script and Start-Transcript in execute.ps1, but neither of them shows the sql PRINTS.
Is there anything I can do about this, maybe a different approach I am unaware of?
I have access to the .ps1 files, but only a maybe on the .sql files.
Here is my code when executing the script:
Start-Process powershell "& .\execute.ps1 -dbserver $server -databasename $database -client $client *>> "".\output\$client.txt"""

Related

Running SQL against multiple DB in azure pipeline

I want to set up the step in release process for azure pipeline where I can run the SQL from the file checked into the repo against multiple databases.
In my environment, I have one central db, one of the table for e.g "Control" table, keeps the connection to all the databases against which I need to run the sql during the deployment.
What I dont want to do is to setup the deployment step for each database. Is Powershell my only friend?
If so, how can I let powershell know what is the SQL in the file checked in during the deployment?
What I dont want to do is to setup the deployment step for each database. Is Powershell my only friend? If so, how can I let powershell know what is the SQL in the file checked in during the deployment?
In your case, Powershell seems to be the most appropriate.
In order to get the SQL in the file checked in during the deployment, we could use the powershell scripts to get the file names and paths, like:
$files=$(git diff HEAD HEAD~ --name-only)
$temp=$files -split ' '
$count=$temp.Length
echo "Total changed $count files"
For ($i=0; $i -lt $temp.Length; $i++)
{
$name=$temp[$i]
echo "this is $name file"
Copy-Item "$name" -Destination "$(System.DefaultWorkingDirectory)\SQLDeploymentFolder"
}
Check the ticket for some more details.
Then, we could use the extension Run SQL Server Scripts or Run SQL / SQLCMD Scripts passing multiple SQLCMD variables to all SQL Scripts in a folder.
Hope this helps.

How to execute a powershell script in Admin mode via SSIS

I have a powershell script getting all the computers from WSUS using PoshWSUS. I manually execute the script after opening Powershell in admin mode.
I have to execute the script using SSIS now. I have inserted Execute Process Task in Control Flow. The executable is set as C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
This is the argument: -NoProfile -ExecutionPolicy ByPass -command ". c:\mypath\GetWSUSList.ps1" -verb runAs
I've tried many others, mostly including in this page: PowerShell: Running a command as Administrator
But none of them worked and still getting Unauthorization error. Any help would be appreciated.
I found this link Automate Running PowerShell Scripts that Require Admin elevation via SSIS. It seems similar to the issue you have, so you might be able to use this as a reference.
Here is the solution below:
Step 1: Create a powershell script file. My script.ps1 is:
import-module poshwsus
ForEach ($Server in Get-Content $WSUSServers)
{
& connect-poshwsusserver $Server -port $WSUSPort | out-file $ProcessLog -append
& Get-PoshWSUSUpdateSummaryPerClient -UpdateScope (new-poshwsusupdatescope) -ComputerScope (new-poshwsuscomputerscope) | Select Computer, LastUpdated | export-csv -NoTypeInformation -append $FileOutput
}
Step 2: Create a .bat file, let's say it is called RunMyPS1.bat, like below.
#ECHO OFF
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""C:\Scripts\WSUSReport\script.ps1""' -Verb RunAs}"
PAUSE
Note that using -verb runAs at the end of the argument line is very important here.
Step 3: Create a Task Scheduler to run your .bat file, named "RunMyBat" for example.
Open Task Scheduler, click "Create Task" on the right menu. Under General, make sure the checkbox Run with highest priveleges is checked, this is very important. Then navigate to Actions section, add new action by browsing to your .bat file.
Step 4. Run your task scheduler via SSIS
Add "Execute Process Task" to your Control Flow. Make sure the executable of the task is set to: "C:\Windows\System32\schtasks.exe" and the arguments is: "/run /TN "RunMyBat" like below.
Step 5. Run your SSIS package.
Important: Note that after the "execute process task" running the task scheduler is triggered, SSIS directly comes to the next step (if any) without waiting the task scheduler completes its process. Therefore, if there is any tasks that will use the output or updated data by your PowerShell script, then insert a "Script Task" and add sleep to ensure that your powershell script is completed.
System.Threading.Thread.Sleep(120000);

PowerShell execute exe show nothing

I have a PowerShell script that run .exe from command prompt with argument parameter.
When I run the .exe fromcommand from command promp it working well and the .exe insert some rows in DB
C:\NF\debug>CMExecuter.exe abc.rpr
When I try to run the same command from PowerShell , nothing happen . There is neither error appeared nor rows inserted in DB .please help me as I am confused
I tried the both commands from Powershell and both showed nothing .
solution :1
& "C:\NF\debug\CMExecuter.exe" "abc.rpr"
solution :2
Start-Process -FilePath "C:\NF\debug\CMExecuter.exe" -ArgumentList "abc.rpr"
Maybe your command prompt and powershell has different rights?
Please test this the following way: if your command executes well from a command prompt, start the powershell from that command prompt (by typing powershell and enter) and test your ps command from that powershell.

What's in teamcity custom_script.cmd

I'm trying to dig into the depths of teamcity to get a better understanding of what its doing under the hood(and improve my own build knowledge). I noticed that when I run a build step it then executes its own .cmd which I presume wraps up the msbuild scripts. The problem is that whenever I look in the directory specified the file doesn't exist as I'm guessing it creates, executes then deletes almost instantly. Any suggestions on how to access the file? or what's inside?
Starting:D:\TeamCity\buildAgent\temp\agentTmp\custom_script5990675507156014131.cmd
A temporary file is created by TeamCity when you run add a Command Line Build Step with "Custom script" as runner.
The content of this file would be the Custom script you specified inside the user interface.
The produced output would be:
Step 1/1: Command Line (1s)
Starting: D:\TeamCity\buildAgent\temp\agentTmp\custom_script2362934300799611461.cmd
in directory: D:\TeamCity\buildAgent\work\c72dca7a7355b5de
Hello World
Process exited with code 0
In case anyone is wondering about this still, you can force echo back on.
Put as the first thing in the custom script
#echo on
this will undo the silent commands teamcity defaults to.
I looked around for a while but there seems to be no configuration variable in TeamCity allowing to keep generated files. Now if the commands executed take some time, e.g. more than a couple of seconds, you could just open the temp directory in explorer and start hitting F5 (refresh) from the moment a build is started until you see the .cmd file appear, then be quick and right-click it and select 'Edit' to open it in a text editor. If that is too hard you can try with the solution presented here: create a Powershell script with code like this:
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = "D:\TeamCity\buildAgent\temp\agentTmp"
$watcher.Filter = "*.cmd"
$watcher.IncludeSubdirectories = $false
$watcher.EnableRaisingEvents = $true
$action = { $path = $Event.SourceEventArgs.FullPath
Add-content "D:\log.txt" -value (Get-Content $path)
}
Register-ObjectEvent $watcher "Created" -Action $action
Register-ObjectEvent $watcher "Changed" -Action $action
while ($true) {sleep 1}
and run it. When the build starts and creates a cmd file, the powershell script will copy the content to d:\log.txt. This will still not work for very short-lived scripts though. In that case I'd just make the script last longer by adding something like
ping 127.0.0.1 -n 5 -w 1000 > NUL
which will make it last at least 5 seconds.

How to run .sql file from a batch file?

I am running sql server 2008 express and i need to schedule some stored procedures to run nightly...so i have built out these .sql files which i would want to run from .bat file...i need to know the command to execute these .sql files one by one and store their results i guess...can anyone help me out?
I answered this in this other question:
You should invoke the sqlcmd command-line tool from your batch file. Assuming your sql file is "backup.sql", the command line would be something like:
sqlcmd -E -S yoursqlinstance -i backup.sql
-E uses trusted connection, replace with -U and -P if you need to specify a SQL username and password. See also this article with examples.
See the sqlcmd utility:
http://msdn.microsoft.com/en-us/library/ms165702.aspx
This allows you to run sql scripts from the command line
osql:
http://www.di-mgt.com.au/osqlUtility.htm
I don't use SQL Server, but a batch file is just a list of DOS commands. So whatever you use to execute SQL files from the commandline can be used in a batch file.
A quick google search turns up:
sqlcmd -i <inputfile> -o <outputfile>
Hope this helps you :
sqlplus UserName/Password#DataBase #C:\sqlFolder\sqlFile.sql
P.S : Don't forget to add the command "commit;" at the end of sql file (sqlFile.sql), this command order Oracle to save performed changes in database