Using a Different Windows Account for Invoke-Sqlcmdsecurely exposing sql server 2008 for windows...

How would we write a misogynistic character without offending people?

"Murder!" The knight said

What can I substitute for soda pop in a sweet pork recipe?

Does music exist in Panem? And if so, what kinds of music?

How to deny access to SQL Server to certain login over SSMS, but allow over .Net SqlClient Data Provider

Reason Why Dimensional Travelling Would be Restricted

Closure of presentable objects under finite limits

How to speed up a process

As a new poet, where can I find help from a professional to judge my work?

CBP Reminds Travelers to Allow 72 Hours for ESTA. Why?

Understanding Kramnik's play in game 1 of Candidates 2018

Creature spells vs. ability to convert a permanent into a creature

Contradiction with Banach Fixed Point Theorem

What am I? I am in theaters and computer programs

You'll find me clean when something is full

I can't die. Who am I?

Must a tritone substitution use a dominant seventh chord?

Should I choose Itemized or Standard deduction?

Is there a frame of reference in which I was born before I was conceived?

Why does Starman/Roadster have radial acceleration?

Where is this triangular-shaped space station from?

Why is working on the same position for more than 15 years not a red flag?

How to mitigate "bandwagon attacking" from players?

Why do members of Congress in committee hearings ask witnesses the same question multiple times?



Using a Different Windows Account for Invoke-Sqlcmd


securely exposing sql server 2008 for windows authenticationAlways being logged in as SA and not Windows accountEncrypted Connection on Sql ServerPostgres and Windows AD using windows authenticationRunning sp_AskBrent with @ExpertMode = 1 in PowerShellHow to find the 'Instance ID' for PowerShell Invoke-TroubleshootingPack?In SQL Server and using only client side encryption requests, can I use a different certificate for each client?Switch Between Windows Authenticated Users On Single Windows AccountI want Powershell's invoke-sqlcmd to ignore SQL execution errorsHow can I use Invoke-SqlCmd with variables to output the SQL command only or some similar method?













5















I'm attempting to make a Powershell script that needs to interact with SQL Server, so part of the script will involve invoke-sqlcmd. However, the script can't be scheduled as a job in SQL Server and thus make use of the Agent to act as the Windows account used for authentication. Instead, it is going to be run using a different service under an arbitrary Windows account. The documentation for invoke-sqlcmd states that the -Username and -Password parameters are for SQL Server authentication, not Windows, and that it defaults to using the Windows account that is running the script for authentication if no SQL Server parameters are provided.



Is there any way to allow invoke-sqlcmd to use an arbitrary Windows account for authentication instead of the one it's being run under? I am aware that a possible solution would be to make accounts on the SQL Server instances that I want to run the script for and just use the SQL Server authentication option on the command, but I would ideally not want to have to do that. Some other research has also shown that a certificate could be an option to pursue, but I don't think that invoke-sqlcmd can take in certificates or otherwise utilize them like suggested. I could be wrong here though.










share|improve this question


















  • 1





    Check this answer for one possible way to use Impersonation to log onto a remote server.

    – Max Vernon
    Dec 30 '15 at 21:07











  • I use that method all the time to connect my SSMS on my local machine to my client's SQL Server. Great for "authenticating". Still relies on keeping a password in an encrypted file/store or in plain text somewhere if you want to use it in an automated fashion.

    – Jonathan Fite
    Dec 30 '15 at 21:12











  • I'll investigate that as well as a possible solution. Thank you.

    – Dylan Bacon
    Dec 30 '15 at 21:14











  • @DylanBacon, I wouldn't go down that route, if you are going to launch a new thread with a different domain credential you can already do that without using the NETONLY methods, it just adds complexity. I find it useful when I'm crossing domains that don't trust each other (as from my company laptop to a customer's SQL Server).

    – Jonathan Fite
    Dec 30 '15 at 21:17






  • 1





    FYI, this is the command. runas /user:DOMAINAccount /netonly "C:Program Files (x86)Microsoft SQL Server110ToolsBinnManagementStudiossms.exe" it then prompts for the password for the account you specified.

    – Jonathan Fite
    Dec 30 '15 at 21:21


















5















I'm attempting to make a Powershell script that needs to interact with SQL Server, so part of the script will involve invoke-sqlcmd. However, the script can't be scheduled as a job in SQL Server and thus make use of the Agent to act as the Windows account used for authentication. Instead, it is going to be run using a different service under an arbitrary Windows account. The documentation for invoke-sqlcmd states that the -Username and -Password parameters are for SQL Server authentication, not Windows, and that it defaults to using the Windows account that is running the script for authentication if no SQL Server parameters are provided.



Is there any way to allow invoke-sqlcmd to use an arbitrary Windows account for authentication instead of the one it's being run under? I am aware that a possible solution would be to make accounts on the SQL Server instances that I want to run the script for and just use the SQL Server authentication option on the command, but I would ideally not want to have to do that. Some other research has also shown that a certificate could be an option to pursue, but I don't think that invoke-sqlcmd can take in certificates or otherwise utilize them like suggested. I could be wrong here though.










share|improve this question


















  • 1





    Check this answer for one possible way to use Impersonation to log onto a remote server.

    – Max Vernon
    Dec 30 '15 at 21:07











  • I use that method all the time to connect my SSMS on my local machine to my client's SQL Server. Great for "authenticating". Still relies on keeping a password in an encrypted file/store or in plain text somewhere if you want to use it in an automated fashion.

    – Jonathan Fite
    Dec 30 '15 at 21:12











  • I'll investigate that as well as a possible solution. Thank you.

    – Dylan Bacon
    Dec 30 '15 at 21:14











  • @DylanBacon, I wouldn't go down that route, if you are going to launch a new thread with a different domain credential you can already do that without using the NETONLY methods, it just adds complexity. I find it useful when I'm crossing domains that don't trust each other (as from my company laptop to a customer's SQL Server).

    – Jonathan Fite
    Dec 30 '15 at 21:17






  • 1





    FYI, this is the command. runas /user:DOMAINAccount /netonly "C:Program Files (x86)Microsoft SQL Server110ToolsBinnManagementStudiossms.exe" it then prompts for the password for the account you specified.

    – Jonathan Fite
    Dec 30 '15 at 21:21
















5












5








5








I'm attempting to make a Powershell script that needs to interact with SQL Server, so part of the script will involve invoke-sqlcmd. However, the script can't be scheduled as a job in SQL Server and thus make use of the Agent to act as the Windows account used for authentication. Instead, it is going to be run using a different service under an arbitrary Windows account. The documentation for invoke-sqlcmd states that the -Username and -Password parameters are for SQL Server authentication, not Windows, and that it defaults to using the Windows account that is running the script for authentication if no SQL Server parameters are provided.



Is there any way to allow invoke-sqlcmd to use an arbitrary Windows account for authentication instead of the one it's being run under? I am aware that a possible solution would be to make accounts on the SQL Server instances that I want to run the script for and just use the SQL Server authentication option on the command, but I would ideally not want to have to do that. Some other research has also shown that a certificate could be an option to pursue, but I don't think that invoke-sqlcmd can take in certificates or otherwise utilize them like suggested. I could be wrong here though.










share|improve this question














I'm attempting to make a Powershell script that needs to interact with SQL Server, so part of the script will involve invoke-sqlcmd. However, the script can't be scheduled as a job in SQL Server and thus make use of the Agent to act as the Windows account used for authentication. Instead, it is going to be run using a different service under an arbitrary Windows account. The documentation for invoke-sqlcmd states that the -Username and -Password parameters are for SQL Server authentication, not Windows, and that it defaults to using the Windows account that is running the script for authentication if no SQL Server parameters are provided.



Is there any way to allow invoke-sqlcmd to use an arbitrary Windows account for authentication instead of the one it's being run under? I am aware that a possible solution would be to make accounts on the SQL Server instances that I want to run the script for and just use the SQL Server authentication option on the command, but I would ideally not want to have to do that. Some other research has also shown that a certificate could be an option to pursue, but I don't think that invoke-sqlcmd can take in certificates or otherwise utilize them like suggested. I could be wrong here though.







sql-server windows authentication powershell






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 30 '15 at 20:52









Dylan BaconDylan Bacon

1421211




1421211








  • 1





    Check this answer for one possible way to use Impersonation to log onto a remote server.

    – Max Vernon
    Dec 30 '15 at 21:07











  • I use that method all the time to connect my SSMS on my local machine to my client's SQL Server. Great for "authenticating". Still relies on keeping a password in an encrypted file/store or in plain text somewhere if you want to use it in an automated fashion.

    – Jonathan Fite
    Dec 30 '15 at 21:12











  • I'll investigate that as well as a possible solution. Thank you.

    – Dylan Bacon
    Dec 30 '15 at 21:14











  • @DylanBacon, I wouldn't go down that route, if you are going to launch a new thread with a different domain credential you can already do that without using the NETONLY methods, it just adds complexity. I find it useful when I'm crossing domains that don't trust each other (as from my company laptop to a customer's SQL Server).

    – Jonathan Fite
    Dec 30 '15 at 21:17






  • 1





    FYI, this is the command. runas /user:DOMAINAccount /netonly "C:Program Files (x86)Microsoft SQL Server110ToolsBinnManagementStudiossms.exe" it then prompts for the password for the account you specified.

    – Jonathan Fite
    Dec 30 '15 at 21:21
















  • 1





    Check this answer for one possible way to use Impersonation to log onto a remote server.

    – Max Vernon
    Dec 30 '15 at 21:07











  • I use that method all the time to connect my SSMS on my local machine to my client's SQL Server. Great for "authenticating". Still relies on keeping a password in an encrypted file/store or in plain text somewhere if you want to use it in an automated fashion.

    – Jonathan Fite
    Dec 30 '15 at 21:12











  • I'll investigate that as well as a possible solution. Thank you.

    – Dylan Bacon
    Dec 30 '15 at 21:14











  • @DylanBacon, I wouldn't go down that route, if you are going to launch a new thread with a different domain credential you can already do that without using the NETONLY methods, it just adds complexity. I find it useful when I'm crossing domains that don't trust each other (as from my company laptop to a customer's SQL Server).

    – Jonathan Fite
    Dec 30 '15 at 21:17






  • 1





    FYI, this is the command. runas /user:DOMAINAccount /netonly "C:Program Files (x86)Microsoft SQL Server110ToolsBinnManagementStudiossms.exe" it then prompts for the password for the account you specified.

    – Jonathan Fite
    Dec 30 '15 at 21:21










1




1





Check this answer for one possible way to use Impersonation to log onto a remote server.

– Max Vernon
Dec 30 '15 at 21:07





Check this answer for one possible way to use Impersonation to log onto a remote server.

– Max Vernon
Dec 30 '15 at 21:07













I use that method all the time to connect my SSMS on my local machine to my client's SQL Server. Great for "authenticating". Still relies on keeping a password in an encrypted file/store or in plain text somewhere if you want to use it in an automated fashion.

– Jonathan Fite
Dec 30 '15 at 21:12





I use that method all the time to connect my SSMS on my local machine to my client's SQL Server. Great for "authenticating". Still relies on keeping a password in an encrypted file/store or in plain text somewhere if you want to use it in an automated fashion.

– Jonathan Fite
Dec 30 '15 at 21:12













I'll investigate that as well as a possible solution. Thank you.

– Dylan Bacon
Dec 30 '15 at 21:14





I'll investigate that as well as a possible solution. Thank you.

– Dylan Bacon
Dec 30 '15 at 21:14













@DylanBacon, I wouldn't go down that route, if you are going to launch a new thread with a different domain credential you can already do that without using the NETONLY methods, it just adds complexity. I find it useful when I'm crossing domains that don't trust each other (as from my company laptop to a customer's SQL Server).

– Jonathan Fite
Dec 30 '15 at 21:17





@DylanBacon, I wouldn't go down that route, if you are going to launch a new thread with a different domain credential you can already do that without using the NETONLY methods, it just adds complexity. I find it useful when I'm crossing domains that don't trust each other (as from my company laptop to a customer's SQL Server).

– Jonathan Fite
Dec 30 '15 at 21:17




1




1





FYI, this is the command. runas /user:DOMAINAccount /netonly "C:Program Files (x86)Microsoft SQL Server110ToolsBinnManagementStudiossms.exe" it then prompts for the password for the account you specified.

– Jonathan Fite
Dec 30 '15 at 21:21







FYI, this is the command. runas /user:DOMAINAccount /netonly "C:Program Files (x86)Microsoft SQL Server110ToolsBinnManagementStudiossms.exe" it then prompts for the password for the account you specified.

– Jonathan Fite
Dec 30 '15 at 21:21












2 Answers
2






active

oldest

votes


















3














You could grant the account that is going to run the job the necessary permissions onto the SQL Server to run the query. That would be the easiest. If you are going to use Task Scheduler, it even gives a method for specifying the account to use.



The next best would be to use SQL Authentication.



Finally, you can use PowerShell to invoke a new thread to run under a different windows account, that thread then to use Invoke-sql. However, the password then needs to be stored somewhere somehow (usually encrypted in a file). This is not the best solution and not one that I would recommend using.






share|improve this answer
























  • I should have specified that I'm in an enterprise environment where 'permissions' are a carefully guarded and taped thing, but I will agree that it would be the easiest solution if possible.

    – Dylan Bacon
    Dec 30 '15 at 21:05











  • Unfortunately, there isn't much wriggle room on this. The thread has to somehow get authenticated as the desired windows account and there are only a few ways to do that, and most don't store the password securely. Is there a reason they don't want to run the job from SQL Agent? You could setup proxy accounts fairly easily to limit permissions.

    – Jonathan Fite
    Dec 30 '15 at 21:08











  • Hah, more along the lines of 'red tape'. Worries about SQL Server account vulnerabilities are the main reason we are trying to avoid them, I believe. But if forcing a form of Windows authentication is circumventing security in other ways (As most solutions seem to need), then the SQL authentication is probably the lesser of evils. Either way, this answer offers suggestions enough that I'll accept it.

    – Dylan Bacon
    Dec 30 '15 at 21:12








  • 1





    Probably best to have a windows account created for this task and then have the task scheduler run the job using those credentials. Then give that windows account just the permissions it needs to get the job done. It's a bit of a pain but probably fits in their security review models better than turning on SQL authentication if they are already against it.

    – Jonathan Fite
    Dec 30 '15 at 21:19



















0














An alternative, I created a wrapper for Invoke-Sqlcmd for my libraries to use which makes use of Start-Job:



function Invoke-InternalSqlcmd {
[CmdletBinding()]
param (
[Parameter(Mandatory=$true)][string] $Query,
[Parameter(Mandatory=$true)][string] $Database,
[Parameter(Mandatory=$false)][System.Management.Automation.PSCredential] $Credential
)

if (-not $Credential) {
return Invoke-SqlCmd -Query $Query -Database $Database
}
else {
$ScriptBlock = {
param($Query,$Database)
$ErrorActionPreference = 'Stop';

return @{ Result = Invoke-SqlCmd -Query $Query -Database $Database }
}

$Job = Start-Job -Credential $Credential -ScriptBlock $ScriptBlock -ArgumentList $Query,$Database
$JobResult = Wait-Job $Job;

if ($JobResult.State -eq 'Completed') {
return (Receive-Job $Job).Result
}

throw [Exception]::new("Error occurred while executing sql as $($Credential.UserName) $([System.Environment]::NewLine)$($JobResult.ChildJobs[0].JobStateInfo.Reason)", $JobResult.ChildJobs[0].JobStateInfo.Reason)
}
}


Pros




  • Works!

  • Does not use WinRM

  • Returns the exact result that Invoke-Sqlcmd returns

  • Returns errors


Cons




  • Running PS jobs has a nasty overhead. Anywhere between 2-10 seconds. This might not be a big deal but it depends on how long the code you are executing will run.

  • Doesn't respect ErrorActionPreference and will always throw on error. Can be fixed if needed.


I am running in a locked down environment that does not have access to WinRM, and my tasks are long running so this suits my needs. If you want better performance then you could easily replace the job code with Runspaces, as long as you are happy to use WinRM.





share








New contributor




elexis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.




















    Your Answer








    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "182"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f124891%2fusing-a-different-windows-account-for-invoke-sqlcmd%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    3














    You could grant the account that is going to run the job the necessary permissions onto the SQL Server to run the query. That would be the easiest. If you are going to use Task Scheduler, it even gives a method for specifying the account to use.



    The next best would be to use SQL Authentication.



    Finally, you can use PowerShell to invoke a new thread to run under a different windows account, that thread then to use Invoke-sql. However, the password then needs to be stored somewhere somehow (usually encrypted in a file). This is not the best solution and not one that I would recommend using.






    share|improve this answer
























    • I should have specified that I'm in an enterprise environment where 'permissions' are a carefully guarded and taped thing, but I will agree that it would be the easiest solution if possible.

      – Dylan Bacon
      Dec 30 '15 at 21:05











    • Unfortunately, there isn't much wriggle room on this. The thread has to somehow get authenticated as the desired windows account and there are only a few ways to do that, and most don't store the password securely. Is there a reason they don't want to run the job from SQL Agent? You could setup proxy accounts fairly easily to limit permissions.

      – Jonathan Fite
      Dec 30 '15 at 21:08











    • Hah, more along the lines of 'red tape'. Worries about SQL Server account vulnerabilities are the main reason we are trying to avoid them, I believe. But if forcing a form of Windows authentication is circumventing security in other ways (As most solutions seem to need), then the SQL authentication is probably the lesser of evils. Either way, this answer offers suggestions enough that I'll accept it.

      – Dylan Bacon
      Dec 30 '15 at 21:12








    • 1





      Probably best to have a windows account created for this task and then have the task scheduler run the job using those credentials. Then give that windows account just the permissions it needs to get the job done. It's a bit of a pain but probably fits in their security review models better than turning on SQL authentication if they are already against it.

      – Jonathan Fite
      Dec 30 '15 at 21:19
















    3














    You could grant the account that is going to run the job the necessary permissions onto the SQL Server to run the query. That would be the easiest. If you are going to use Task Scheduler, it even gives a method for specifying the account to use.



    The next best would be to use SQL Authentication.



    Finally, you can use PowerShell to invoke a new thread to run under a different windows account, that thread then to use Invoke-sql. However, the password then needs to be stored somewhere somehow (usually encrypted in a file). This is not the best solution and not one that I would recommend using.






    share|improve this answer
























    • I should have specified that I'm in an enterprise environment where 'permissions' are a carefully guarded and taped thing, but I will agree that it would be the easiest solution if possible.

      – Dylan Bacon
      Dec 30 '15 at 21:05











    • Unfortunately, there isn't much wriggle room on this. The thread has to somehow get authenticated as the desired windows account and there are only a few ways to do that, and most don't store the password securely. Is there a reason they don't want to run the job from SQL Agent? You could setup proxy accounts fairly easily to limit permissions.

      – Jonathan Fite
      Dec 30 '15 at 21:08











    • Hah, more along the lines of 'red tape'. Worries about SQL Server account vulnerabilities are the main reason we are trying to avoid them, I believe. But if forcing a form of Windows authentication is circumventing security in other ways (As most solutions seem to need), then the SQL authentication is probably the lesser of evils. Either way, this answer offers suggestions enough that I'll accept it.

      – Dylan Bacon
      Dec 30 '15 at 21:12








    • 1





      Probably best to have a windows account created for this task and then have the task scheduler run the job using those credentials. Then give that windows account just the permissions it needs to get the job done. It's a bit of a pain but probably fits in their security review models better than turning on SQL authentication if they are already against it.

      – Jonathan Fite
      Dec 30 '15 at 21:19














    3












    3








    3







    You could grant the account that is going to run the job the necessary permissions onto the SQL Server to run the query. That would be the easiest. If you are going to use Task Scheduler, it even gives a method for specifying the account to use.



    The next best would be to use SQL Authentication.



    Finally, you can use PowerShell to invoke a new thread to run under a different windows account, that thread then to use Invoke-sql. However, the password then needs to be stored somewhere somehow (usually encrypted in a file). This is not the best solution and not one that I would recommend using.






    share|improve this answer













    You could grant the account that is going to run the job the necessary permissions onto the SQL Server to run the query. That would be the easiest. If you are going to use Task Scheduler, it even gives a method for specifying the account to use.



    The next best would be to use SQL Authentication.



    Finally, you can use PowerShell to invoke a new thread to run under a different windows account, that thread then to use Invoke-sql. However, the password then needs to be stored somewhere somehow (usually encrypted in a file). This is not the best solution and not one that I would recommend using.







    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Dec 30 '15 at 21:02









    Jonathan FiteJonathan Fite

    4,088818




    4,088818













    • I should have specified that I'm in an enterprise environment where 'permissions' are a carefully guarded and taped thing, but I will agree that it would be the easiest solution if possible.

      – Dylan Bacon
      Dec 30 '15 at 21:05











    • Unfortunately, there isn't much wriggle room on this. The thread has to somehow get authenticated as the desired windows account and there are only a few ways to do that, and most don't store the password securely. Is there a reason they don't want to run the job from SQL Agent? You could setup proxy accounts fairly easily to limit permissions.

      – Jonathan Fite
      Dec 30 '15 at 21:08











    • Hah, more along the lines of 'red tape'. Worries about SQL Server account vulnerabilities are the main reason we are trying to avoid them, I believe. But if forcing a form of Windows authentication is circumventing security in other ways (As most solutions seem to need), then the SQL authentication is probably the lesser of evils. Either way, this answer offers suggestions enough that I'll accept it.

      – Dylan Bacon
      Dec 30 '15 at 21:12








    • 1





      Probably best to have a windows account created for this task and then have the task scheduler run the job using those credentials. Then give that windows account just the permissions it needs to get the job done. It's a bit of a pain but probably fits in their security review models better than turning on SQL authentication if they are already against it.

      – Jonathan Fite
      Dec 30 '15 at 21:19



















    • I should have specified that I'm in an enterprise environment where 'permissions' are a carefully guarded and taped thing, but I will agree that it would be the easiest solution if possible.

      – Dylan Bacon
      Dec 30 '15 at 21:05











    • Unfortunately, there isn't much wriggle room on this. The thread has to somehow get authenticated as the desired windows account and there are only a few ways to do that, and most don't store the password securely. Is there a reason they don't want to run the job from SQL Agent? You could setup proxy accounts fairly easily to limit permissions.

      – Jonathan Fite
      Dec 30 '15 at 21:08











    • Hah, more along the lines of 'red tape'. Worries about SQL Server account vulnerabilities are the main reason we are trying to avoid them, I believe. But if forcing a form of Windows authentication is circumventing security in other ways (As most solutions seem to need), then the SQL authentication is probably the lesser of evils. Either way, this answer offers suggestions enough that I'll accept it.

      – Dylan Bacon
      Dec 30 '15 at 21:12








    • 1





      Probably best to have a windows account created for this task and then have the task scheduler run the job using those credentials. Then give that windows account just the permissions it needs to get the job done. It's a bit of a pain but probably fits in their security review models better than turning on SQL authentication if they are already against it.

      – Jonathan Fite
      Dec 30 '15 at 21:19

















    I should have specified that I'm in an enterprise environment where 'permissions' are a carefully guarded and taped thing, but I will agree that it would be the easiest solution if possible.

    – Dylan Bacon
    Dec 30 '15 at 21:05





    I should have specified that I'm in an enterprise environment where 'permissions' are a carefully guarded and taped thing, but I will agree that it would be the easiest solution if possible.

    – Dylan Bacon
    Dec 30 '15 at 21:05













    Unfortunately, there isn't much wriggle room on this. The thread has to somehow get authenticated as the desired windows account and there are only a few ways to do that, and most don't store the password securely. Is there a reason they don't want to run the job from SQL Agent? You could setup proxy accounts fairly easily to limit permissions.

    – Jonathan Fite
    Dec 30 '15 at 21:08





    Unfortunately, there isn't much wriggle room on this. The thread has to somehow get authenticated as the desired windows account and there are only a few ways to do that, and most don't store the password securely. Is there a reason they don't want to run the job from SQL Agent? You could setup proxy accounts fairly easily to limit permissions.

    – Jonathan Fite
    Dec 30 '15 at 21:08













    Hah, more along the lines of 'red tape'. Worries about SQL Server account vulnerabilities are the main reason we are trying to avoid them, I believe. But if forcing a form of Windows authentication is circumventing security in other ways (As most solutions seem to need), then the SQL authentication is probably the lesser of evils. Either way, this answer offers suggestions enough that I'll accept it.

    – Dylan Bacon
    Dec 30 '15 at 21:12







    Hah, more along the lines of 'red tape'. Worries about SQL Server account vulnerabilities are the main reason we are trying to avoid them, I believe. But if forcing a form of Windows authentication is circumventing security in other ways (As most solutions seem to need), then the SQL authentication is probably the lesser of evils. Either way, this answer offers suggestions enough that I'll accept it.

    – Dylan Bacon
    Dec 30 '15 at 21:12






    1




    1





    Probably best to have a windows account created for this task and then have the task scheduler run the job using those credentials. Then give that windows account just the permissions it needs to get the job done. It's a bit of a pain but probably fits in their security review models better than turning on SQL authentication if they are already against it.

    – Jonathan Fite
    Dec 30 '15 at 21:19





    Probably best to have a windows account created for this task and then have the task scheduler run the job using those credentials. Then give that windows account just the permissions it needs to get the job done. It's a bit of a pain but probably fits in their security review models better than turning on SQL authentication if they are already against it.

    – Jonathan Fite
    Dec 30 '15 at 21:19













    0














    An alternative, I created a wrapper for Invoke-Sqlcmd for my libraries to use which makes use of Start-Job:



    function Invoke-InternalSqlcmd {
    [CmdletBinding()]
    param (
    [Parameter(Mandatory=$true)][string] $Query,
    [Parameter(Mandatory=$true)][string] $Database,
    [Parameter(Mandatory=$false)][System.Management.Automation.PSCredential] $Credential
    )

    if (-not $Credential) {
    return Invoke-SqlCmd -Query $Query -Database $Database
    }
    else {
    $ScriptBlock = {
    param($Query,$Database)
    $ErrorActionPreference = 'Stop';

    return @{ Result = Invoke-SqlCmd -Query $Query -Database $Database }
    }

    $Job = Start-Job -Credential $Credential -ScriptBlock $ScriptBlock -ArgumentList $Query,$Database
    $JobResult = Wait-Job $Job;

    if ($JobResult.State -eq 'Completed') {
    return (Receive-Job $Job).Result
    }

    throw [Exception]::new("Error occurred while executing sql as $($Credential.UserName) $([System.Environment]::NewLine)$($JobResult.ChildJobs[0].JobStateInfo.Reason)", $JobResult.ChildJobs[0].JobStateInfo.Reason)
    }
    }


    Pros




    • Works!

    • Does not use WinRM

    • Returns the exact result that Invoke-Sqlcmd returns

    • Returns errors


    Cons




    • Running PS jobs has a nasty overhead. Anywhere between 2-10 seconds. This might not be a big deal but it depends on how long the code you are executing will run.

    • Doesn't respect ErrorActionPreference and will always throw on error. Can be fixed if needed.


    I am running in a locked down environment that does not have access to WinRM, and my tasks are long running so this suits my needs. If you want better performance then you could easily replace the job code with Runspaces, as long as you are happy to use WinRM.





    share








    New contributor




    elexis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
    Check out our Code of Conduct.

























      0














      An alternative, I created a wrapper for Invoke-Sqlcmd for my libraries to use which makes use of Start-Job:



      function Invoke-InternalSqlcmd {
      [CmdletBinding()]
      param (
      [Parameter(Mandatory=$true)][string] $Query,
      [Parameter(Mandatory=$true)][string] $Database,
      [Parameter(Mandatory=$false)][System.Management.Automation.PSCredential] $Credential
      )

      if (-not $Credential) {
      return Invoke-SqlCmd -Query $Query -Database $Database
      }
      else {
      $ScriptBlock = {
      param($Query,$Database)
      $ErrorActionPreference = 'Stop';

      return @{ Result = Invoke-SqlCmd -Query $Query -Database $Database }
      }

      $Job = Start-Job -Credential $Credential -ScriptBlock $ScriptBlock -ArgumentList $Query,$Database
      $JobResult = Wait-Job $Job;

      if ($JobResult.State -eq 'Completed') {
      return (Receive-Job $Job).Result
      }

      throw [Exception]::new("Error occurred while executing sql as $($Credential.UserName) $([System.Environment]::NewLine)$($JobResult.ChildJobs[0].JobStateInfo.Reason)", $JobResult.ChildJobs[0].JobStateInfo.Reason)
      }
      }


      Pros




      • Works!

      • Does not use WinRM

      • Returns the exact result that Invoke-Sqlcmd returns

      • Returns errors


      Cons




      • Running PS jobs has a nasty overhead. Anywhere between 2-10 seconds. This might not be a big deal but it depends on how long the code you are executing will run.

      • Doesn't respect ErrorActionPreference and will always throw on error. Can be fixed if needed.


      I am running in a locked down environment that does not have access to WinRM, and my tasks are long running so this suits my needs. If you want better performance then you could easily replace the job code with Runspaces, as long as you are happy to use WinRM.





      share








      New contributor




      elexis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
      Check out our Code of Conduct.























        0












        0








        0







        An alternative, I created a wrapper for Invoke-Sqlcmd for my libraries to use which makes use of Start-Job:



        function Invoke-InternalSqlcmd {
        [CmdletBinding()]
        param (
        [Parameter(Mandatory=$true)][string] $Query,
        [Parameter(Mandatory=$true)][string] $Database,
        [Parameter(Mandatory=$false)][System.Management.Automation.PSCredential] $Credential
        )

        if (-not $Credential) {
        return Invoke-SqlCmd -Query $Query -Database $Database
        }
        else {
        $ScriptBlock = {
        param($Query,$Database)
        $ErrorActionPreference = 'Stop';

        return @{ Result = Invoke-SqlCmd -Query $Query -Database $Database }
        }

        $Job = Start-Job -Credential $Credential -ScriptBlock $ScriptBlock -ArgumentList $Query,$Database
        $JobResult = Wait-Job $Job;

        if ($JobResult.State -eq 'Completed') {
        return (Receive-Job $Job).Result
        }

        throw [Exception]::new("Error occurred while executing sql as $($Credential.UserName) $([System.Environment]::NewLine)$($JobResult.ChildJobs[0].JobStateInfo.Reason)", $JobResult.ChildJobs[0].JobStateInfo.Reason)
        }
        }


        Pros




        • Works!

        • Does not use WinRM

        • Returns the exact result that Invoke-Sqlcmd returns

        • Returns errors


        Cons




        • Running PS jobs has a nasty overhead. Anywhere between 2-10 seconds. This might not be a big deal but it depends on how long the code you are executing will run.

        • Doesn't respect ErrorActionPreference and will always throw on error. Can be fixed if needed.


        I am running in a locked down environment that does not have access to WinRM, and my tasks are long running so this suits my needs. If you want better performance then you could easily replace the job code with Runspaces, as long as you are happy to use WinRM.





        share








        New contributor




        elexis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.










        An alternative, I created a wrapper for Invoke-Sqlcmd for my libraries to use which makes use of Start-Job:



        function Invoke-InternalSqlcmd {
        [CmdletBinding()]
        param (
        [Parameter(Mandatory=$true)][string] $Query,
        [Parameter(Mandatory=$true)][string] $Database,
        [Parameter(Mandatory=$false)][System.Management.Automation.PSCredential] $Credential
        )

        if (-not $Credential) {
        return Invoke-SqlCmd -Query $Query -Database $Database
        }
        else {
        $ScriptBlock = {
        param($Query,$Database)
        $ErrorActionPreference = 'Stop';

        return @{ Result = Invoke-SqlCmd -Query $Query -Database $Database }
        }

        $Job = Start-Job -Credential $Credential -ScriptBlock $ScriptBlock -ArgumentList $Query,$Database
        $JobResult = Wait-Job $Job;

        if ($JobResult.State -eq 'Completed') {
        return (Receive-Job $Job).Result
        }

        throw [Exception]::new("Error occurred while executing sql as $($Credential.UserName) $([System.Environment]::NewLine)$($JobResult.ChildJobs[0].JobStateInfo.Reason)", $JobResult.ChildJobs[0].JobStateInfo.Reason)
        }
        }


        Pros




        • Works!

        • Does not use WinRM

        • Returns the exact result that Invoke-Sqlcmd returns

        • Returns errors


        Cons




        • Running PS jobs has a nasty overhead. Anywhere between 2-10 seconds. This might not be a big deal but it depends on how long the code you are executing will run.

        • Doesn't respect ErrorActionPreference and will always throw on error. Can be fixed if needed.


        I am running in a locked down environment that does not have access to WinRM, and my tasks are long running so this suits my needs. If you want better performance then you could easily replace the job code with Runspaces, as long as you are happy to use WinRM.






        share








        New contributor




        elexis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.








        share


        share






        New contributor




        elexis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.









        answered 9 mins ago









        elexiselexis

        1012




        1012




        New contributor




        elexis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.





        New contributor





        elexis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






        elexis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
        Check out our Code of Conduct.






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Database Administrators Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f124891%2fusing-a-different-windows-account-for-invoke-sqlcmd%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Szabolcs (Ungheria) Altri progetti | Menu di navigazione48°10′14.56″N 21°29′33.14″E /...

            Discografia di Klaus Schulze Indice Album in studio | Album dal vivo | Singoli | Antologie | Colonne...

            How to make inet_server_addr() return localhost in spite of ::1/128RETURN NEXT in Postgres FunctionConnect to...