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

Similar Messages

  • [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

  • 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 can you run a command with elevated rights on a remote server with invoke-command ?

    I am trying to run a script on a remote server with invoke-command.  The script is starting and is running fine, but the problem is that it should be running with elevated rights on the remote server.  On the server where I start the invoke-command, my account has the necessary rights.
    The server were I launch the invoke-command is a W2K8 R2.  The remote box is a W2K3 with powershell v2.0 installed.
    When I launch the script on the remote-box from the command line, I don't get the access denied's.
    Is there a way to do this ?
    Thanks in advance

    The script that I want to run is to install the windows updates.  I get an access denied on the download of the updates.
    When I execute the script on an W2K8 box, (not remotely) and I run it with non-elevated rights, I get the same error.
    The script is running fine when it is launched on W2K3 box locally with a domain account that has local admin rights, or on a W2K8 R2 server with a domain account that has local admin rights, but with elevated rights.
    Thanks in advance for your help.
    #=== start script ====
    param($installOption="TESTINSTALL",$rebootOption="NOREBOOT")
    Function Show-Help
    Write-Host ""
    Write-Host "SCRIPT: $scriptName <installOption> <RebootOption>"
    Write-Host ""
    Write-Host "DESCRIPTION: Installatie van WSUS updates op de lokale server"
    Write-Host ""
    Write-Host "PARAMETERS"
    Write-Host " -installOption <[INSTALL|TESTINSTALL]>"
    Write-Host " -rebootOption <[REBOOT|NOREBOOT|REBOOT_IF_UPDATED]>"
    Write-Host ""
    Write-Host "EXAMPLE:"
    Write-Host "$ScriptName -installOption INSTALL -rebootOption REBOOT_IF_UPDATED"
    Write-Host "$ScriptNAme INSTALL NOREBOOT"
    Write-Host ""
    Write-Host "Indien beide parameter weggelaten worden zijn de defaultwaarden :"
    Write-Host " installOption=TESTINSTALL "
    Write-Host " RebootOption=NOREBOOT"
    Write-Host ""
    Exit
    #Include alle globale variablen
    $CEIF_WIN_PATH = (get-content env:CEIF_WIN_PATH)
    $includeFile=$CEIF_WIN_PATH + "\Scripts\include_win.ps1"
    . $includeFile
    #initialiseer error count
    $errcnt=0
    $scriptName=$MyInvocation.MyCommand.Name
    #argumenten controleren
    $arrInstallOption= "TESTINSTALL", "INSTALL" # Mandatory variable with predefined values
    If (!($arrInstallOption –contains $installOption)){ Show-Help }
    $arrRebootOption = "REBOOT", "NOREBOOT","REBOOT_IF_UPDATED" # Mandatory variable with predefined values
    If (!($arrRebootOption –contains $rebootOption)){ Show-Help }
    #Logfile opbouwen
    $logfile = get-logfileName($MyInvocation.MyCommand.Name)
    Log-scriptStart $MyInvocation.MyCommand.Name $logfile
    function Get-WIAStatusValue($value)
    switch -exact ($value)
    0 {"NotStarted"}
    1 {"InProgress"}
    2 {"Succeeded"}
    3 {"SucceededWithErrors"}
    4 {"Failed"}
    5 {"Aborted"}
    function boot-server()
    if ($installOption -eq "TESTINSTALL")
    logger "TESTINSTALL : - Reboot local Server" $logfile
    else
    logger " - Reboot local Server" $logfile
    $thisServer = gwmi win32_operatingsystem
    $thisServer.psbase.Scope.Options.EnablePrivileges = $true
    $thisServer.Reboot()
    $logmsg="Install option = " + $installOption + ", RebootOption = $rebootOption"
    logger "$logmsg" $logfile
    logger "" $logfile
    logger " - Creating WU COM object" $logfile
    $UpdateSession = New-Object -ComObject Microsoft.Update.Session
    $UpdateSearcher = $UpdateSession.CreateUpdateSearcher()
    logger " - Searching for Updates" $logfile
    $SearchResult = $UpdateSearcher.Search("IsAssigned=1 and IsHidden=0 and IsInstalled=0")
    logger " - Found [$($SearchResult.Updates.count)] Updates to Download and install" $logfile
    $Updates=$($SearchResult.Updates.count)
    logger "" $logfile
    foreach($Update in $SearchResult.Updates)
    if ($Update.EulaAccepted -eq 0)
    $Update.AcceptEula()
    # Add Update to Collection
    $UpdatesCollection = New-Object -ComObject Microsoft.Update.UpdateColl
    $UpdatesCollection.Add($Update) | out-null
    if ($installOption -eq "TESTINSTALL")
    else
    # Download
    logger " + Downloading Update $($Update.Title)" $logfile
    $UpdatesDownloader = $UpdateSession.CreateUpdateDownloader()
    $UpdatesDownloader.Updates = $UpdatesCollection
    $DownloadResult = $UpdatesDownloader.Download()
    $Message = " - Download {0}" -f (Get-WIAStatusValue $DownloadResult.ResultCode)
    if ($DownloadResult.ResultCode -eq 4 )
    { $errcnt = 1 }
    logger $message $logfile
    # Install
    logger " - Installing Update" $logfile
    $UpdatesInstaller = $UpdateSession.CreateUpdateInstaller()
    $UpdatesInstaller.Updates = $UpdatesCollection
    $InstallResult = $UpdatesInstaller.Install()
    $Message = " - Install {0}" -f (Get-WIAStatusValue $InstallResult.ResultCode)
    if ($InstallResult.ResultCode -eq 4 )
    { $errcnt = 1 }
    logger $message $logfile
    logger "" $logfile
    #Indien er een fout gebeurde tijdens download/installatie -> stuur mail naar windowsteam
    if ( $errcnt -gt 0 )
    logger " - Fout tijdens de uitvoering van script -> send mail" $logfile
    $mailSubject=$MyInvocation.MyCommand.Name
    $msg = new-object Net.Mail.MailMessage
    $att = new-object Net.Mail.Attachment($logfile)
    $smtp = new-object Net.Mail.SmtpClient($smtpServer)
    $msg.From = $mailFrom
    $msg.To.Add($mailTo)
    $msg.Subject = $mailSubject
    $msg.Body = “Meer details in attachement”
    $msg.Attachments.Add($att)
    $smtp.Send($msg)
    #Moet de server herstart worden ?
    if ($rebootOption -eq "REBOOT_IF_UPDATED" )
    if ($Updates -gt 0)
    #Reboot the server when updates are installed
    boot-server
    elseif ($rebootOption -eq "REBOOT")
    #reboot the server always
    boot-server
    else
    #Do not reboot the server
    logger "Do not reboot the server" $logfile
    Log-scriptEnd $MyInvocation.MyCommand.Name $logfile
    exit 0

  • 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]

  • 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.
    ¯\_(ツ)_/¯

  • Error trying to publish (real time) to delivery: No response from remote execute trying to save assettype [error was -103].

    Hi all,
    I'm trying to publish for first time to a new environment (delivery).
    The light of target destination is green.
    When i click on "inicialize" i get these errors and in the docs i cannot find why or what i have to do.
    Trying to publish asset types during inicialization it returns this error:
    No response from remote execute trying to save assettype [error was -103].
    Looking for the meaning for this i found: No table. What does it mean? Why the tool has not created the table?
    And then, the next error message is shown (all of them are shown in the same screenshot) trying to mirroring. It might have to do with the previos error message... but i have no idea!
    -12011. No response from remote execute trying to save assettype [error was -103]
    sites.log in delivery environment says as follows
    [2014-01-24 12:13:52,496 CET] [ERROR] [.kernel.Default (self-tuning)'] [fatwire.logging.cs.db] SQLException loading table definition for SiteCatalog with state HY000: [FMWGEN][SQLServer JDBC Driver]Object has been closed.
    java.sql.SQLException: [FMWGEN][SQLServer JDBC Driver]Object has been closed.
    [2014-01-24 12:13:52,527 CET] [ERROR] [.kernel.Default (self-tuning)'] [com.fatwire.logging.cs] ContentServer exception running CS recursively
    COM.FutureTense.Common.ContentServerException: pagename not supplied  Error code:BAD PARAMETER
    [2014-01-24 12:13:52,543 CET] [ERROR] [.kernel.Default (self-tuning)'] [logging.cs.satellite.request] Error accessing the external page with pmd: page: ?Browser=Unknown  Browser&SystemAssetsRoot=/dlv/futuretense_cs/&errdetail=0&errno=0&null= &pagename=fatwire/wem/sso/casInfo
    [2014-01-24 12:13:52,543 CET] [ERROR] [.kernel.Default (self-tuning)'] [fatwire.logging.cs.request] COM.FutureTense.Common.ContentServerException: ContentServerException: (Reading page page: ?Browser=Unknown  Browser&SystemAssetsRoot=/dlv/futuretense_cs/&errdetail=0&errno=0&null= &pagename=fatwire/wem/sso/casInfo from co-resident Content Server failed (errno=0).) Error code:GENERIC SERVER ERROR
    [2014-01-24 12:14:06,021 CET] [ERROR] [.kernel.Default (self-tuning)'] [fatwire.logging.cs.db] SQLException loading table definition for SystemInfo with state HY000: [FMWGEN][SQLServer JDBC Driver]Object has been closed.
    java.sql.SQLException: [FMWGEN][SQLServer JDBC Driver]Object has been closed.
    Does anybody know how to help here?
    Thank you very much.
    Gala

    What SQL server driver are you using, Microsoft's or the jTDS driver (see jTDS JDBC Driver)? It may be worth trying the other.
    Also, can you enable
    com.fatwire.logging.cs=DEBUG
    in log4j.properties and retest, then post the entire resulting sites.log and application server log somewhere for us to see? e.g somewhere like pastebin.com
    Phil

  • 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.

  • C# Run VB Script file remotely thriugh PowerShell Invoke Command

    I have a requirement where need to run vbscript remotely through PowerShell Invoke command. I can run the VB Script locally but not remotely as the vbscript file is not present on the remote machine. I don't want to copy the script file on remote machine.
    Please let me know how to run vb script on remote machine. Below is the code.
    Collection<PSObject> output
    = null;
            using
    (Runspace runSpace =
    RunspaceFactory.CreateRunspace())
                runSpace.Open();
                using
    (Pipeline pipeline = runSpace.CreatePipeline())
    RunspaceInvoke invoke =
    new RunspaceInvoke();
    PowerShell ps = PowerShell.Create();
                    ps.Runspace
    = runSpace;
                    ps.AddCommand("invoke-command");
                    ps.AddParameter("ComputerName",
    "RemoteServerName");
    ScriptBlock sb = ScriptBlock.Create("cscript E:\\Test\\DeleteFiles.vbs");
                    ps.AddParameter("ScriptBlock", sb);
                    output
    = ps.Invoke();
    Regards, Parveen

    Hello Parveen,
    Please refer to the following thread
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/7562eefb-7fba-4bf6-834e-82256f159155/run-script-on-remote-macine?forum=csharpgeneral
    See his code:
    You can use WMI to create processes on a remote machine. In C#, use the ManagementClass.
    using System;
    using System.Management;
    using System.Collections.Generic;
    public class MyClass
    public static void RunNotepad()
    ManagementPath p = new ManagementPath(@"\\targetMachine\root\cimv2:Win32_process");
    ManagementClass m = new ManagementClass(p);
    m.InvokeMethod("Create", new Object[] {"notepad.exe"});
    See: Creating Processes Remotely
    Note that the the scrpt file is not executable so you have to create script like this:
     cscript.exe "\\yourmachine\script\test.vbs".
    Best regards,
    Barry
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • 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]

  • Remote Execute and File Transfer Error

    Whenever we try to do a Remote Execute of File Transfer, we get an 1899
    error. Here's the strange thing, we can RE and FT to desktops that are
    still running the ZfD 4.x client. Seems to be only happening on the latest
    (ZfD 6.5sp2). Any ideas? Also, remote control and remote view still work
    w/o problem.

    Blewis,
    It appears that in the past few days you have not received a response to your
    posting. That concerns us, and has triggered this automated reply.
    Has your problem been resolved? If not, you might try one of the following options:
    - Do a search of our knowledgebase at http://support.novell.com/search/kb_index.jsp
    - Check all of the other support tools and options available at
    http://support.novell.com.
    - You could also try posting your message again. Make sure it is posted in the
    correct newsgroup. (http://support.novell.com/forums)
    Be sure to read the forum FAQ about what to expect in the way of responses:
    http://support.novell.com/forums/faq_general.html
    If this is a reply to a duplicate posting, please ignore and accept our apologies
    and rest assured we will issue a stern reprimand to our posting bot.
    Good luck!
    Your Novell Product Support Forums Team
    http://support.novell.com/forums/

  • Invoke-IpamGpoProvisioning : Failed to import GPO. The system cannot find the file specified. (Exception from HRESULT: 0x80070002)

    Hello Im trying to configure IPAM but im getting this error.
    PS C:\Users\Administrator.IPADE.MX> Invoke-IpamGpoProvisioning –Domain actdir.ipade.mx –GpoPrefixName IPAM –IpamServerFq
    dn minte.actdir.ipade.mx –DelegatedGpoUser Administrator -DomainController discovery.actdir.ipade.mx
    Invoke-IpamGpoProvisioning : Failed to import GPO. The system cannot find the file specified. (Exception from HRESULT:
    0x80070002)
    At line:1 char:1
    + Invoke-IpamGpoProvisioning –Domain actdir.ipade.mx –GpoPrefixName IPAM –IpamServ ...
    + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [Invoke-IpamGpoProvisioning], Exception
        + FullyQualifiedErrorId : InvalidOperation,Invoke-IpamGpoProvisioning
    In the event viewer  I founf this but I don't know what to do.
    Import of backup failed. Error [The system cannot find the file specified.
    Details -
         Backup
             Directory: The system cannot find the file specified.
             Instance : C:\Users\Administrator.IPADE.MX\AppData\Local\Temp\1\ipamprov
             Comment  : {09673450-4573-42E8-85D0-104144DF0BA3}
             Source GPO:
                 DisplayName: IPAMGPO_DNS
                 ID: IPAMGPO_DNS
                 Domain: {7F345996-1D92-4194-85BF-72BFB5298EDA}
         Destination GPO:
                 DisplayName: ipamtestsetup.com
                 ID: IPAM_DNS
                 Domain: {447E8380-91AF-4C2D-8DAA-2C090A6400E8}

    Hi,
    Before going further, what was name specified in the IPAM provisioning wizard while selecting Group Policy based provisioning method? The GPO prefix name specified in the
    PowerShell command must be same as the one specified in the IPAM provisioning wizard while selecting Group Policy based provisioning method.
    Regarding Invoke-IpamGpoProvisioning, the following article can be referred to as reference.
    Invoke-IpamGpoProvisioning
    http://technet.microsoft.com/en-us/library/jj553805.aspx
    Best regards,
    Frank Shen

  • WSIF JCA Execute of operation 'SynchRead' failed due to: The SSH API threw

    Hello All,
    I am getting the following error for SFTP Synchronize operation
    "WSIF JCA Execute of operation 'SynchRead' failed due to: The SSH API threw an exception".
    Have any of you experienced this error and how to fix this.
    thanks
    BPELDeveloper

    <detail>Element not completed: 'Payables_Exp_Payload'</detail>It seems problem is in schema validation. Make sure that you are passing a valid xml to adapter. Exactly what are you doing in your process?
    To get better response cross-post your question in BPEL forum -
    BPEL
    Regards,
    Anuj

  • Remotely execute batch commands for AD users?

    Alright, so I haven't found this anywhere, but is there a way to remotely execute commands for AD users?Eg. I have a user with an invalid signature in Outlook. I originally wrote up a script that would apply these signatures and set them as default on user logon, but I also made versioning available in my script, and I don't want to create an entire new version just because of a single signature, so instead I would prefer to use a command like "xcopy "\\server\deployed\signatures\%username%\signature.htm" /q /y /z" Is it possible for me to do it remotely?PS.Sorry if the question may sound stupid, I just haven't done something like this before.
    This topic first appeared in the Spiceworks Community

    Alright, so I haven't found this anywhere, but is there a way to remotely execute commands for AD users?Eg. I have a user with an invalid signature in Outlook. I originally wrote up a script that would apply these signatures and set them as default on user logon, but I also made versioning available in my script, and I don't want to create an entire new version just because of a single signature, so instead I would prefer to use a command like "xcopy "\\server\deployed\signatures\%username%\signature.htm" /q /y /z" Is it possible for me to do it remotely?PS.Sorry if the question may sound stupid, I just haven't done something like this before.
    This topic first appeared in the Spiceworks Community

Maybe you are looking for

  • 2011 MacBook Pro hard drive power consumption

    Does anyone know the differences in power consumption between the Apple-supplied 750GB 5400rpm HDD, 500GB 7200rpm HDD, and 256GB SSD drives?  I'm currently using a 2011 MacBook Pro with an Apple-supplied 256GB SSD and I'm getting between 5-8 hours of

  • How to get the ID of a Button

    Hi, There is an interface IF_WD_VIEW_ELEMENT inside the class CL_WD_BUTTON whi has two methods: GET_ID and GET_VIEW. My problem is i have to get the ID of a button at runtime inorder to get the text associated with it.  can anybody pls let me know ho

  • Cant install itunes and ipad disabled

    I couldnt open itunes on laptop so uninstalled and tried to reinstall it but didnt work all i get is that it didnt install correctly error 7 windows error 193. Also sons ipad disabled due to him forgetting passcode is there any way to reset it withou

  • Is there a quick way to the desktop in Mac OS X

    Is the keyboard shortcut to get quickly to the desktop? In Windows XP, I use 'Microsoft Key + M'.

  • Adobe Air downloaded/installed on Apple hone 4? A A

    Adobe Air/Apple iPhone 4 downloading and installing, how can it be done?