Sqlcmd, invoke-sqlcmd

We use SQLcmd to mail output of some sql properties to our administrators
Code, i have as input a txt file with all my sql servers:
FOR /F "tokens=*" %%I IN (%InputFile%) DO (
SET ServerNameFDQN=%%I
ECHO Start Processing %ServerNameFDQN% ...
FOR /F "tokens=1 delims=." %%A IN ("%ServerNameFDQN%") DO (
SET ServerName=%%A
ECHO Read DB Prop
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.txt" -i "%ScriptFolder%\DBProp.sql"
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.csv" -W -s";" -i "%ScriptFolder%\DBProp.sql"
ECHO %ServerName% >> %ScriptOutputFolder%\TotalDBProp.txt
ECHO --------------- >> %ScriptOutputFolder%\TotalDBProp.txt
TYPE %ScriptOutputFolder%\%ServerName%-DBProp.txt >> %ScriptOutputFolder%\TotalDBProp.txt
ECHO. >> %ScriptOutputFolder%\TotalDBProp.txt
ECHO. >> %ScriptOutputFolder%\TotalDBProp.txt
ECHO %ServerName% >> %ScriptOutputFolder%\TotalDBProp.csv
ECHO --------------- >> %ScriptOutputFolder%\TotalDBProp.csv
TYPE %ScriptOutputFolder%\%ServerName%-DBProp.csv >> %ScriptOutputFolder%\TotalDBProp.csv
ECHO. >> %ScriptOutputFolder%\TotalDBProp.csv
ECHO. >> %ScriptOutputFolder%\TotalDBProp.csv
Output to csv (nice in colums):
server001                                                      
DATABASE_NAME
DATABASE_SIZE
REMARKS
DATABASE_SERVER
master
37760
NULL
server001
model
22336
NULL
server001
msdb
52416
NULL
server001
db01
162568
NULL
server001
db02
4158016
NULL
server001
db03
149568
NULL
server001
(6 rows affected)
server002
DATABASE_NAME
DATABASE_SIZE
REMARKS
DATABASE_SERVER
master
8640
NULL
server002
model
23360
NULL
server002
msdb
527104
NULL
server002
db01
2548800
NULL
server002
db02
5447488
NULL
server002
db03
777408
NULL
server002
db04
1416960
NULL
server002
tempdb
112640
NULL
server002
(8 rows affected)
This is output per server because sqlcommand accepts a parameter serverinstance
But what i would like is the following output:
DATABASE_NAME
DATABASE_SIZE
REMARKS
DATABASE_SERVER
master
37760
NULL
server001
model
22336
NULL
server001
msdb
52416
NULL
server001
db01
162568
NULL
server001
db02
4158016
NULL
server001
db03
149568
NULL
server001
master
8640
NULL
server002
model
23360
NULL
server002
msdb
527104
NULL
server002
db01
2548800
NULL
server002
db02
5447488
NULL
server002
db03
777408
NULL
server002
db04
1416960
NULL
server002
tempdb
112640
NULL
server002
(14 rows affected)
And i tried to do it with invoke-sqlcmd, but then i don't get the nice colums when i work with export CSV, Anybody got an idea to get the result i want in powershell or in batch if there isn't another option.

Hi Aborgeld,
To achieve your requirement, there's some modification on the part of your batch need to make. please see the below code.
REM for the first run sqlcmd, we need to get the dataset with headers(DATABASE_NAME DATABASE_SIZE REMARKS DATABASE_SERVER)
SET isFirstRunflag=1
FOR /F "tokens=*" %%I IN (%InputFile%) DO (
SET ServerNameFDQN=%%I
ECHO Start Processing %ServerNameFDQN% ...
FOR /F "tokens=1 delims=." %%A IN ("%ServerNameFDQN%") DO (
SET ServerName=%%A
ECHO Read DB Prop
IF %isFirstRunflag%==1 (
REM one more sql file "c:\setNocountOn.sql" to get run to remove the row count message like x rows affected
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.txt" -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql"
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.csv" -W -s"," -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql"
SET isFirstRunflag=0
) ELSE (
REM the paramter -h -1 after sqlcmd ignores the headers
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.txt" -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql" -h -1
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.csv" -W -s"," -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql" -h -1
REM ECHO %ServerName% >> %ScriptOutputFolder%\TotalDBProp.txt
REM ECHO --------------- >> %ScriptOutputFolder%\TotalDBProp.txt
TYPE %ScriptOutputFolder%\%ServerName%-DBProp.txt >> %ScriptOutputFolder%\TotalDBProp.txt
REM ECHO. >> %ScriptOutputFolder%\TotalDBProp.txt
REM ECHO. >> %ScriptOutputFolder%\TotalDBProp.txt
REM ECHO %ServerName% >> %ScriptOutputFolder%\TotalDBProp.csv
REM ECHO --------------- >> %ScriptOutputFolder%\TotalDBProp.csv
TYPE %ScriptOutputFolder%\%ServerName%-DBProp.csv >> %ScriptOutputFolder%\TotalDBProp.csv
REM ECHO. >> %ScriptOutputFolder%\TotalDBProp.csv
REM ECHO. >> %ScriptOutputFolder%\TotalDBProp.csv
So the code can be extracted as below
SET isFirstRunflag=1
FOR /F "tokens=*" %%I IN (%InputFile%) DO (
SET ServerNameFDQN=%%I
ECHO Start Processing %ServerNameFDQN% ...
FOR /F "tokens=1 delims=." %%A IN ("%ServerNameFDQN%") DO (
SET ServerName=%%A
ECHO Read DB Prop
IF %isFirstRunflag%==1 (
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.txt" -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql"
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.csv" -W -s"," -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql"
SET isFirstRunflag=0
) ELSE (
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.txt" -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql" -h -1
sqlcmd -S %ServerNameFDQN% -o "%ScriptOutputFolder%\%ServerName%-DBProp.csv" -W -s"," -i "c:\setNocountOn.sql","%ScriptFolder%\DBProp.sql" -h -1
TYPE %ScriptOutputFolder%\%ServerName%-DBProp.txt >> %ScriptOutputFolder%\TotalDBProp.txt
TYPE %ScriptOutputFolder%\%ServerName%-DBProp.csv >> %ScriptOutputFolder%\TotalDBProp.csv
You also have to create a "c:\setNocountOn.sql" with the content "set nocount on" to igore the output like "x rows affected" that affects the expected output.
As I tested, the code works to lead to the expected output in txt and csv. My table has 2 rows and I set the repeat times as 3 to simulate your scenario(my query returns the rows from my table which are different from yours, but what matters is the output format
here).
If you have any question, feel free to let me know.
Best Regards,
Eric Zhang

Similar Messages

  • Create SQL Job with Invoke-Sqlcmd

    I'm trying to run a set of .sql files, i didn't know how to pass a common variable to all, so i've started running the statements directly in ps.  One of these creates a job but i'm running into all of the errors due to the special characters and the
    variables, can someone help?
    $Client = "C0212"
    $Instance = "SQL03\"+$Client
    $sqlscript3 = "
    --NEED TO CHANGE THE LOG LOCATION BELOW
    USE [msdb]
    GO
    /****** Object:  Job [DatabaseBackup - USER_DATABASES - FULL]    Script Date: 11/15/2013 8:40:20 AM ******/
    BEGIN TRANSACTION
    DECLARE @ReturnCode INT
    SELECT @ReturnCode = 0
    /****** Object:  JobCategory [Database Maintenance]    Script Date: 11/15/2013 8:40:20 AM ******/
    IF NOT EXISTS (SELECT name FROM msdb.dbo.syscategories WHERE name=N''Database Maintenance'' AND category_class=1)
    BEGIN
    EXEC @ReturnCode = msdb.dbo.sp_add_category @class=N''JOB'', @type=N''LOCAL'', @name=N''Database Maintenance''
    IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
    END
    DECLARE @jobId BINARY(16)
    EXEC @ReturnCode =  msdb.dbo.sp_add_job @job_name=N''DatabaseBackup - USER_DATABASES - FULL'', 
    @enabled=1, 
    @notify_level_eventlog=2, 
    @notify_level_email=0, 
    @notify_level_netsend=0, 
    @notify_level_page=0, 
    @delete_level=0, 
    @description=N''Source: http://ola.hallengren.com'', 
    @category_name=N''Database Maintenance'', 
    @owner_login_name=N''sa'', @job_id = @jobId OUTPUT
    IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
    /****** Object:  Step [DatabaseBackup - USER_DATABASES - FULL]    Script Date: 11/15/2013 8:40:20 AM ******/
    EXEC @ReturnCode = msdb.dbo.sp_add_jobstep @job_id=@jobId, @step_name=N''DatabaseBackup - USER_DATABASES - FULL'', 
    @step_id=1, 
    @cmdexec_success_code=0, 
    @on_success_action=1, 
    @on_success_step_id=0, 
    @on_fail_action=2, 
    @on_fail_step_id=0, 
    @retry_attempts=0, 
    @retry_interval=0, 
    @os_run_priority=0, @subsystem=N''CmdExec'', 
    @command=N''sqlcmd -E -S `$(ESCAPE_SQUOTE(SRVR)) -d DBA -Q `"EXECUTE [dbo].[DatabaseBackup] @Databases = ''''USER_DATABASES'''', @Directory = N''''T:\SQLsafe Backups\SQL Native Backup'''', @BackupType = ''''FULL'''',
    @Verify = ''''Y'''', @CleanupTime = 170, @CheckSum = ''''Y'''', @LogToTable = ''''Y''''`" -b'', 
    --NEED TO CHANGE THE LOG LOCATION BELOW
    @output_file_name=N''C:\Program Files\Microsoft SQL Server\MSSQL11.$Client\MSSQL\LOG\DatabaseBackup_`$(ESCAPE_SQUOTE(JOBID))_`$(ESCAPE_SQUOTE(STEPID))_`$(ESCAPE_SQUOTE(STRTDT))_`$(ESCAPE_SQUOTE(STRTTM)).txt'', 
    @flags=0
    IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
    EXEC @ReturnCode = msdb.dbo.sp_update_job @job_id = @jobId, @start_step_id = 1
    IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
    EXEC @ReturnCode = msdb.dbo.sp_add_jobschedule @job_id=@jobId, @name=N''Saturday 4am'', 
    @enabled=1, 
    @freq_type=8, 
    @freq_interval=64, 
    @freq_subday_type=1, 
    @freq_subday_interval=0, 
    @freq_relative_interval=0, 
    @freq_recurrence_factor=1, 
    @active_start_date=20131109, 
    @active_end_date=99991231, 
    @active_start_time=40000, 
    @active_end_time=235959, 
    @schedule_uid=N''5b3c3fcf-28dc-4f4c-95ce-a624667ee378''
    IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
    EXEC @ReturnCode = msdb.dbo.sp_add_jobserver @job_id = @jobId, @server_name = N''(local)''
    IF (@@ERROR <> 0 OR @ReturnCode <> 0) GOTO QuitWithRollback
    COMMIT TRANSACTION
    GOTO EndSave
    QuitWithRollback:
        IF (@@TRANCOUNT > 0) ROLLBACK TRANSACTION
    EndSave:
    GO"
    Invoke-Sqlcmd –ServerInstance $Instance –Database msdb –Query $sqlscript3 -QueryTimeout 300

    So, if I try this:
    $Client = "C0212"
    Invoke-Sqlcmd -InputFile "C:\NewInstanceScripts\PSNI -3 - Create Full Backup job for ALL User Databases.sql" -Variable $Client
    and in my .sql file that line that contains the variable looks like this:
    @output_file_name=N'C:\Program Files\Microsoft SQL Server\MSSQL11.`$(Client)\MSSQL\LOG\DatabaseBackup_$(ESCAPE_SQUOTE(JOBID))_$(ESCAPE_SQUOTE(STEPID))_$(ESCAPE_SQUOTE(STRTDT))_$(ESCAPE_SQUOTE(STRTTM)).txt',
    I get the error: 
    Invoke-Sqlcmd : The format used to define the new variable for Invoke-Sqlcmd cmdlet is invalid. Please use the 'var=value' format for defining a new variable.
    If i try like this:
    Set @Client = "C0212"
    Invoke-Sqlcmd -InputFile "C:\NewInstanceScripts\PSNI -3 - Create Full Backup job for ALL User Databases.sql" -Variable @Client
    Line in .sql file like this:
    @output_file_name=N'C:\Program Files\Microsoft SQL Server\MSSQL11.@Client\MSSQL\LOG\DatabaseBackup_$(ESCAPE_SQUOTE(JOBID))_$(ESCAPE_SQUOTE(STEPID))_$(ESCAPE_SQUOTE(STRTDT))_$(ESCAPE_SQUOTE(STRTTM)).txt',
    I get the error: Set-Variable : A positional parameter cannot be found that accepts argument '2'.

  • Invoke-Sqlcmd problem on Windows server 2008

    We have several Web Servers running Win2008 and need to be able to use the Invoke-Sqlcmd powershell cmdlet to execute arbitrary SQL.  
    Tried installing PowerShellTools.msi but Invoke-Sqlcmd still isn't recognized.
    What do I need to do to get support for PowerShellTools.msi in PowerShell 4.0?
    SQL 2008 SP1

    here are the installation instructions:
    http://blog.smu.edu/wis/2012/11/26/sql-server-powershell-module-sqlps/
    ¯\_(ツ)_/¯
    Installed the dependencies and it still didn't work.  Did myself a favor and used this
    version.  It uses stock SqlConnection/SqlCommand and has no dependencies other than .Net framework.

  • Invoke-sqlcmd with domain user name and password

    I am trying to execute below small SQL script from powershell by passing my domain user name and password..but it is throwing an error login failed for the user.
    Howerver I am able to execute the same query by passing normal user 'non domain' and password. The issue is only when i am trying to connect with domain username.
    Can you please suggest if there is any way to execute below query with domain user..
    Invoke-Sqlcmd
    -query "select name from master.sys.databases"
    -ServerInstance "CM-NCKM-DBTST04\SQL2012" -username "sos\9venk" -password "xxxx"
    Thanks
    Venkat
    venkat

    Hi Venkat,
    Agree with Mike, to connect sql via powershell, you can refer to this article about authentications:
    Connecting to SQL Server through Powershell
    Please try to gather credentials using Get-Credential, and then use New-PSSession -Authentication CredSSP to open the pssession.
    A similar discussion about this issue is for your reference:
    Invoke-SQLCmd with Different Credential
    If there is anything else regarding this issue, please feel free to post back.
    Best Regards,
    Anna Wang
    Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Support, contact [email protected]

  • Powershell command invoke-sqlcmd in batch script

    I have a powershell command that I want to be run in batch script. It works well in powershell window but I cannot call it properly in batch script. the powershell command goes like this:
    invoke-sqlcmd -inputfile "D:\Reports\sql.sql" -ServerInstance Server1 | export-csv "D:\RawDataFiles\Raw\samp.csv" -Force -En UTF8
    I hope somebody could help me out. Also, is it possible to include batch variable in replace of the file path for input and output file instead of putting the whole path in powershell command (stil run inside in batch script)?
    Thanks.

    I have found that works :) to run the invoke-sqlcmd within batch script:
    I have use this line:
    powershell -Command "& {Add-PSSnapin SqlServerCmdletSnapin100; Add-PSSnapin SqlServerProviderSnapin100; invoke-sqlcmd -inputfile '%sqlPath1%' -ServerInstance %Server% | export-csv '%out_path1%\%out1_fn%' -Force -En UTF8;}"
    works like charm yay! ^_^

  • Remotely executing an invoke-sqlcmd fails

    When remotely executing an invoke-sqlcmd fails.  A simple query such as:
    Invoke-Command -ComputerName ComputerName -ScriptBlock{
    $qry = "SELECT SERVERPROPERTY('ServerName') AS ServerName,
    SERVERPROPERTY('ProductVersion') AS ProductVersion,
    SERVERPROPERTY('ProductLevel') AS ProductLevel,
    SERVERPROPERTY('Edition') AS Edition,
    SERVERPROPERTY('EngineEdition') AS EngineEdition;"
    Invoke-Sqlcmd -Query $qry} -ConfigurationName SQLSession
    I get the following error:
    [ComputerName] Connecting to remote server failed with the following error message : The WS-Management service cannot process the request. The resource URI (http://sche
    mas.microsoft.com/powershell/SQLSession) was not found in the WS-Management catalog. The catalog contains the metadata that describes resources, or logical endpoints. For
    more information, see the about_Remote_Troubleshooting Help topic.
    + CategoryInfo : OpenError: (:) [], PSRemotingTransportException
    + FullyQualifiedErrorId : PSSessionStateBroken
    I have run Enable-WSManCredSSP Server on the SQL server and  tried to run Enable-WSManCredSSP -Role Client -DelegatedCredentials * on a Windows 7 x32 workstation but I get the following error:
    Enable-WSManCredSSP : A parameter cannot be found that matches parameter name 'DelegatedCredentials'.
    At line:1 char:55
    + Enable-WSManCredSSP -Role Client -DelegatedCredentials <<<< *
    + CategoryInfo : InvalidArgument: (:) [Enable-WSManCredSSP], ParameterBindingException
    + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.WSMan.Management.EnableWSManCredSSPCommand
    I have tried the Enable-WSManCredSSP with the actual server name instead of a wildcard and it still fails.

    Hi,
    As cmille replied, for the command, there is no DeletegatedCredentials parameter, more details about the command:
    Enable-WSManCredSSP
    http://technet.microsoft.com/en-us/library/hh849872(v=wps.620).aspx
    Did you use Server Core? Please below link to troubleshoot this issue:
    the ws-management service cannot process the request
    http://social.technet.microsoft.com/Forums/windowsserver/en-US/27020cf2-47fc-43e3-b135-e68b80a1bb4e/the-wsmanagement-service-cannot-process-the-request?forum=winservercore
    Regards,
    Yan Li
    Regards, Yan Li

  • Unknown command invoke-sqlcmd

    Hey guys.  So I have this .bat file which automates the installation of SQL Server.  Towards the end of the script, I'm trying to execute a powershell script which calls a SQL Scripts to install objects in our new instance(highlighted in bold below).
    @echo off
    pushd %0\..\
    If NOT Exist C:\Temp\SQL2012 md C:\Temp\SQL2012
    xcopy /E /I /H /R *.* C:\Temp\SQL2012
    cd /d C:\Temp\SQL2012
    If NOT Exist D: powershell -File C:\Temp\SQL2012\DiskPart.ps1
    setup.exe /configurationfile=SQL2K12.ini /iacceptsqlserverlicenseterms
    echo Return code: %ERRORLEVEL%
    pause
    powershell -File C:\Temp\SQL2012\Updates\standards.ps1
    pause
    popd
    Problem is that when the powershell script tries to execute, it gives me an error saying that it doesn't recognize the invoke-sqlcmd.  So I have another bat file which I run just to test out, and it simply calls the same powershell script, and it works.
    @echo off
    pushd %0\..\
    powershell -File C:\Temp\SQL2012\Updates\standards.ps1
    pause
    popd

    it doesn't recognize the invoke-sqlcmd.  
    The command is only available when the SqlPs commandlet is loaded; see
    sqlps Utility
    Olaf Helper
    [ Blog] [ Xing] [ MVP]

  • Invoke-sqlcmd parameter error

    I'm trying to pass semicolan separated value as single parameter to Invoke-SQLCMD via powershell and it throwing "Invoke-Sqlcmd : The format used to define the new variable for Invoke-Sqlcmd cmdlet is invalid. Please use the "var=val
    ue" format for defining a new variable.
    At line:1 char:14" error.
    $conditions = "qrytype = summary;test_id = 562;"Invoke-Sqlcmd -Variable $conditions -ServerInstance "MyInstanse" -Database "testdb" -InputFile "C:\Queue1.sql"
    Could anyone let me know, how do I pass semicolan separated value as single parameter?

    Start by notplacingquotes around everything and don't catenate lines which makes thecode confusing to you.
    $conditions = @("qrytype='summary'",'test_id=562')
    Invoke-Sqlcmd -Variable $conditions -ServerInstance MyInstanse -Database testdb -InputFile C:\Queue1.sql
    See help for SQlCmd to understand how to use it.  Look closely at all of teh examples.
    ¯\_(ツ)_/¯

  • How to execute SQL Script using windows powershell(using invoke-sqlcmd or any if)

    OS : Windows server 2008
    SQL Server : SQL Server 2012
    Script: Test.sql (T-SQL)  example : "select name from sys.databases"
    Batch script: windows  MyBatchscript.bat ( here connects to sql server using sqlcmd  and output c:\Testput.txt) 
     (sqlcmd.exe -S DBserverName -U username -P p@ssword -i C:\test.sql -o "c:\Testoutput.txt)  ---it working without any issues.....
    This can execute if i double click MyBatchscript.bat file and can see the output in c:\testput.txt.
    Powershell: Similarly, How can i do in powershell 2.0 or higher versions?  can any one give full details with each step?
    I found some of them online, but nowhere seen clear details or examples and it not executing through cmd line (or batch script).
    example: invoke-sqlcmd -Servernameinstance Servername -inputfile "c:\test.sql" | out-File -filepath "c:\psOutput.txt"  --(call this file name MyTest.ps1)
    (The above script working if i run manually. I want to run automatic like double click (or schedule with 3rd party tool/scheduler ) in Batch file and see the output in C drive(c:\psOutput.txt))
    Can anyone Powershell experts give/suggest full details/steps for this. How to proceed? Is there any configurations required to run automatic?
    Thanks in advance.

    Testeted the following code and it's working.....thanks all.
    Execute sql script using invoke-sqlcmd with batch script and without batch script.
    Option1: using Import sqlps
    1.Save sql script as "C:\scripts\Test.sql"  script in side Test.sql: select name from sys.databases
    2.Save Batch script as "C:\scripts\MyTest.bat" Script inside Batch script:
    powershell.exe C:\scripts\mypowershell.ps1
    3.Save powershell script as "C:\scripts\mypowershell.ps1"
    import-module "sqlps" -DisableNameChecking
    invoke-sqlcmd -Servername ServerName -inputFile "C:\scripts\Test.sql" | out-File -filepath "C:\scripts\TestOutput.txt"
    4.Run the Batch script commandline or double click then can able to see the output "C:\scripts\TestOutput.txt" file.
    5.Connect to current scripts location  cd C:\scripts (enter)
    C:\scripts\dir (enter )
    C:\scripts\MyTest.bat (enter)
    Note: can able to see the output in "C:\scripts" location as file name "TestOutput.txt".
    Option2: Otherway, import sqlps and execution
    1.Save sql script as "C:\scripts\Test.sql"  script in side Test.sql: select name from sys.databases
    2.Save powershell script as "C:\scripts\mypowershell.ps1"
    # import-module "sqlps" -DisableNameChecking #...Here it not required.
    invoke-sqlcmd -Servername ServerName -inputFile "C:\scripts\Test.sql" | out-File -filepath "C:\scripts\TestOutput.txt"
    3.Connect to current scripts location
    cd C:\scripts (enter)
    C:\scripts\dir (enter )
    C:\scripts\powershell.exe sqlps C:\scripts\mypowershell.ps1 (enter)
    Note: can able to see the output in "C:\scripts" location as file name "TestOutput.txt".

  • How to Provide Windows Credentials in Invoke-sqlcmd

    Hi,
    Could you please let me know how to execute TSQL Queries using Invoke-Sqlcmd by passing Windows Credentials.
    I Know Other methods(sqlcmd, SMO) to Run, But Im looking for this Solution.
    I Tried below Commands but it is failing.
    Add-PSSnapin SqlServerCmdletSnapin100
    Add-PSSnapin SqlServerProviderSnapin100
    Invoke-Sqlcmd -ServerInstance "ABC\XYZ" -Database "master" -Query "select * from sys.databases" -Username "Domain\user_ID" -Password "Pwd"
    The credentials which I have passed is having Sysadmin access to SQL Server and it is a Domain Account.
    Note: if I Run the same command Without passing Credentials in the same machine(ABC), then Im getting the Output.
    Please help

    As Mike notes.  The username and password are only useful when you are connecting in mixed mode and you have defined a SQL standard login.  For all trusted connections you must start PowerShell as the user that you want to connect with.  There
    no alternate credentials in MSSQLServer.  The is a "Trusted" connection and a user login connection.  Logins arte not enabled by default in MSSQLServer.
    If you have sufficient priviliges in SQLServer you can act as another user and use their schema.  I recommend posting in the SQLServer forum to learn how to set up and use this.
    ¯\_(ツ)_/¯

  • Invoke-sqlcmd message handling

    Hi All. if I using invoke-sqlcmd, how to handle the information output and error output.
    for example, I update 2 rows, if successful it would show 2 rows , and command is successful in Management studio.
    if there is error during update, there will be error code, serverity , error message in Management studio
    I want to achieve the same thing in powershell ISE. any method ?

    i try to use try catch
    however i still cant output to error in powershell to an log file.

  • [Forum FAQ] How do I have Invoke-SqlCmd return a date value without adding time

    Introduction
    A select statement executed from Invoke-SqlCmd returns a value from a Date column, the value has "12:00:00 AM" appended.  The same select statement executed within SQL Server Management Studio displays the date properly without any time formatting.
    Sample data is as follows:
    How to have Invoke-SqlCmd return Date values without adding time for multiple Date type columns and pipe the output into CSV file?
    Solution
    In SQL Server 2012 or onwards, use the FORMAT() function to convert datetime values to date format when executing query from Invoke-SqlCmd. In earlier versions such as SQL Server 2008 R2, use the traditional CONVERT() function to format datetime values to
    different date formats(yyyy.mm.dd, mm/dd/yyyy, etc) when executing query from Invoke-SqlCmd. Then pipe the output of SQL query result into CSV file by specifying export-csv parameter. An example is as follows.
    Create a table named “Test_invokesqlcmd” that contains Date type columns in SQL Server.
    USE Test
    Go
    CREATE TABLE [dbo].[Test_invokesqlcmd](
        [id] [int] NOT NULL,
        [name] [varchar](20) NULL,
        [test1] [date] NULL,
        [test2] [date] NULL
    ) ON [PRIMARY]
    GO
    insert into [dbo].[Test_invokesqlcmd]
    values(1,'David','2014-10-15','2015-01-07'),(2,'Jane','2011-08-05','2012-11-7'),(3,'Crystal','2013-09-15','2010-02-24')
    Define a query string, execute it from Invoke-SqlCmd and save the query result to a CSV file.
    Scripts for SQL Server 2012:
    $query1 = @"
        use Test;
        SELECT FORMAT(test1,'d') as newtest1, FORMAT(test2,'d') as newtest2 from dbo.Test_invokesqlcmd
    write-host $query1
    Invoke-Sqlcmd -Query $query1 -ServerInstance localhost | export-csv -notypeinformation -path c:\Files\test.csv
    Scripts for SQL Server 2008 R2:
    $query2 = @"
        Use Test;
        SELECT CONVERT(varchar, test1, 102) as newtest1,CONVERT(varchar, test2, 102) as newtest2
        FROM dbo. Test_invokesqlcmd
    write-host $query2
    Invoke-Sqlcmd -Query $query2 -ServerInstance localhost | export-csv -notypeinformation -path c:\Files\test.csv
    Check the results in SQL Server PowerShell window and csv file.
    SQL Server 2012:
    SQL Server 2008 R2:
    Reference
    Using the Invoke-Sqlcmd cmdlet
    SQL Server Functions that helps to convert date and time values to and from string literals and other date and time formats
    Applies to
    SQL Server 2014
    SQL Server 2012
    SQL Server 2008 R2
    SQL Server 2008
    Please click to vote if the post helps you. This can be beneficial to other community members reading the thread.

    Cross posted. More appropriate in JSF forum so continue conversation there.
    http://forum.java.sun.com/thread.jspa?threadID=717292&messageID=4142615#4142615

  • Invoke-sqlcmd problem

    Hi
    I'm using the invoke-sql command to pull some information out of a sql database.  A few of the fields I'm interested in are stored in hex in the database, for instance 0x00000000000000000000FFFF0A0A3200.
    If I try to view those fields I just get a string of 0's going up the screen. If I try to view them in a table they just appear truncated {0, 0, 0, 0...}.
    I presume I need to tell the command they're hex fields but I've not idea how to do that.
    Any ideas?
    Alex

    They are not hex.  They are binary arrays.  YOu have to index into the array.
    Post in SQLServer forum to get assitance with how to use this datatype.
    It would help if you posted what you have as a datatype(BLOB, Image. Object).  Also post whey you need to query binary data.
    ¯\_(ツ)_/¯

  • Invoke-expression "sqlcmd

    Hi All,
    I am trying to exeucte a stored procedure with paramater from sqlcmd , invoking it using invoke-expression , the exeuction failes with below error
    $Sserver='PC114'
    $Query="'usp_sendfilecopyStatus @ServerName=''$Sserver''" 
    invoke-expression "sqlcmd -E -S xyz-Q $Query  -d DBInventory"
    usp_sendfilecopyStatus @ServerName=''PC114''
    sqlcmd : Sqlcmd: '@ServerName=PC114': Unexpected argument. Enter '-?' for help.
    At line:1 char:1
    + sqlcmd -E -S xyz-Q usp_sendfilecopyStatus @ServerName=''PC114''  -d ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (Sqlcmd:
    '@Serve... '-?' for help.:String) [], RemoteException
        + FullyQualifiedErrorId : NativeCommandError
    Mohd Sufian www.sqlship.wordpress.com Please mark the post as Answered if it helped.

    Hi Mohd,
    I’m
    writing to just check in to see if the suggestions were helpful. If you need further help, please feel free to reply this post directly so we will be notified to follow it up.
    If you have any feedback on our support, please click here.
    Best Regards,
    Anna Wang
    TechNet Community Support

  • PowerShell 2.0 - When to use SqlServer Snap-In

    Hello there,
    Just started learning about sending Sql Server command through PowerShell.
    I understand that we can use .Net objects like SQLConnection, SqlCommand (just like we do in C#) to send the CRUD request to Sql Server database (as $sqlcmd = New-Object System.Data.SqlClient.SqlCommand...)
    However, I was reading about Provider and SnapIns and have two doubts. Below is the snippet from my PS v2.0 window:
    PS C:\> Get-PSSnapin -Registered
    returns:---------------------------------------------------------------------
    Name : SqlServerCmdletSnapin100
    Name : SqlServerProviderSnapin100
    #If I see what commands are available in above SnapIns, I get following:
    PS C:\> get-command -module SqlServerProviderSnapin100
    #returns:---------------------------------------------------------------------
    CommandType Name Definition
    Cmdlet Convert-UrnToPath Convert-UrnToPath [-Urn] <String> [-Verbose.
    Cmdlet Decode-SqlName Decode-SqlName [-SqlName] <String> [-Verbos.
    Cmdlet Encode-SqlName Encode-SqlName [-SqlName] <String> [-Verbos.
    PS C:\> get-command -module SqlServerCmdletSnapin100
    #returns:---------------------------------------------------------------------
    CommandType Name Definition
    Cmdlet Invoke-PolicyEvaluation Invoke-PolicyEvaluation [-Policy] <PSObject.
    Cmdlet Invoke-Sqlcmd Invoke-Sqlcmd [[-Query] <String>] [-ServerI.
    Two questions:
    1. Do I need to Add-PSSnapin only when I need to run above commands?
        So, I don't need to import any snap-ins if I want my PowerShell to use .net framework objects to communicate with SQL Server.
    2. I can send any CRUD request to database using SqlServerCmdletSnapin100 command 'Invoke-Sqlcmd'.
    Which one is preferred method of sending CRUD requests - 'Invoke-Sqlcmd' or .Net Framework objects?
    Can anyone please clarify.
    Thank you!

    Hi Iniki,
    You only need it to perform the exposed commands. You can use .NET types without them.
    I recommend doing it all with one tool - if you're going to use .NET, do it all in .NET. That way, all your trouble will be in one spot. And if you're already familiar with the C# .NET way ...
    I implemented this with .NET types, especially since I could add better connection handling for the interactive Shell of our techs (They can register connections, manage them, declare a default connection to use and so on) ...
    Cheers,
    Fred
    Ps.: Oh, and of course I implemented my own Invoke-SQLCommand function, so users can use it comfortably in interactive sessions. If you got regular admin users, they need Functions / Cmdlets to use ...
    There's no place like 127.0.0.1

Maybe you are looking for

  • Adobe air won't install

    How do I get adobe air to install?  I have downloaded it but nothing happens.  I need this for adobe assistant which I need to download a trial of adobe XI. 

  • Trying to upload video to you tube through Premiere Elements

    I'm trying to upload a video to YouTube through Premiere Elements.  The program asks for permission and I grant it but nothing else happens?  Help.

  • Error when generating the update program::::ID RSAU No. 484****

    Helllo, While Infopackage loading for DS 2LIS_04_P_COMP following error is coming.. please see if anyone may face such kind of error. ***Error when generating the update program::::ID RSAU No. 484*** Diagnosis      An error occurred during program ge

  • Tables fields where the system status is getting stored

    I need to find out the Quotes which have open and completed system status. Once I find these orders I need the check the validity dates of the Quotes. Can experts please let me know the tables where the system status and the validity dates are stored

  • Sort by Ratings

    It's 2006. Can we please sort by user RATINGS? Anywhere on apple.com Design is for users, yes? Please design. More. Many thanks. Addicted to Mac...more than to oil :-o