I want to impersonate user when I access Microsoft SQL Server from powershell

Hi,
Actually I have to perform some SQL operation on my MSSQL server database. but problems is that I have given all credentials (windows fix login/password which can access database) in connection string. but when I execute the script then it is always using
my windows login and password and then giving error that not able to connect with it.
My personal windows credentials does not have access to my enterprise database that is why I am using service ID.
I came to know that I have to do user impersonation of user when i access database but how to do that?? can you guys give me the syntax for that as i have to perform all sql operation using impersonation.
Please reply me as soon as possible as i stuck since long
Vipul Mistry Sr. Embedded Engineer www.eInfochips.com

Hi Guys,
thanks a lot for your support and replies but I found the solution. With below code i was able to do my task and I used $AuthType =3 for my purpose. Hope this will help others also.
$varDBServer = "N0SQL104,1675"
$varDBInstance = ""
$varDBSchema = "Data_Dev"
$varDBUser = "S0060VMSD"
$varDBPassword = "SDCFG345D"
#### Choose authentication type (0=SSO, 1= SQL, 2=Domain)
$AuthType = 3
#### Load the required assembly for sql server administration
#### Requieres SQLServerNativeClient, SQLSysClrTypes and SharedManagementObjects
[reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
$varSQLServer = New-Object -typeName Microsoft.SqlServer.Management.Smo.Server -argumentList "$varDBServer\$varDBInstance"
switch ($AuthType) {
1 {
#### Access the SQL-Server with your current credentials (pass-through)
$varSQLServer.ConnectionContext.LoginSecure = $true
2 {
#### Access the SQL-Server with SQL-Server credentials in mixed mode authentications
$varSQLServer.ConnectionContext.LoginSecure = $false
$varSQLServer.ConnectionContext.Login = $varDBUser
$varSQLServer.ConnectionContext.Password = $varDBPassword
3 {
#### Access the SQL-Server with given domain user credentials
$varSQLServer.ConnectionContext.LoginSecure = $true
$varSQLServer.ConnectionContext.ConnectAsUser = $true
$varSQLServer.ConnectionContext.ConnectAsUserName = $varDBUser
$varSQLServer.ConnectionContext.ConnectAsUserPassword = $varDBPassword
} default {
Write-Host "Please select an authentication type: 0=SSO, 1= SQL, 2=Domain"
exit -1
#### Try connection to SQL-Server with given parameters
Write-Host "`nTry connection to SQL-Server with given parameters`n"
try {
$varBuildOfSQLServer = $varSQLServer.Version.get_Build()
Write-Host "Build of SQL-Server '$varDBServer' is $varBuildOfSQLServer"
} catch {
Write-Host "ERROR: Cannot access SQL-Server '$varDBServer'. Exit script!"
exit –1
Vipul Mistry Sr. Embedded Engineer www.eInfochips.com

Similar Messages

  • Impersonate user when accessing Microsoft SQL Server from powershell using Windows Authentication

    Hi All,
    Below is the powershell script to connect a SQL DB using windows authentication by impersonating a user. The user should have login access to the server. Script can be highly useful when service id is used to access DB using powershell.
    [reflection.assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
    $ds=$null
    $conn = New-Object -typeName Microsoft.SqlServer.Management.Smo.Server -argumentList "Servername"
    $db = New-Object Microsoft.SqlServer.Management.Smo.Database
    $conn.ConnectionContext.ConnectAsUser = $true 
    $conn.ConnectionContext.LoginSecure=$true
    $conn.ConnectionContext.ConnectAsUserName = "username"
    $conn.ConnectionContext.ConnectAsUserPassword ="password
    $conn.Loginmode
    $db = $conn.Databases.Item("dbname")
    $ds = $db.ExecuteWithResults("select top 10 Name from Tablename")
    Foreach ($t in $ds.Tables)
       Foreach ($r in $t.Rows)
          Foreach ($c in $t.Columns)
              Write-Host $c.ColumnName "=" $r.Item($c)

    That is OK when you want to manage the instance biut it wojn't work if the tools are not installed.
    This works from anywhere all of the time and is simpler:
    $datasource='MyServerInstance'
    $database='NorthWind'
    $connStr='Data Source={0}; Database={1}; Trusted_Connection=True;' -f '$datasource,$database
    $conn=New-Object System.Data.SQlClient.SQlConnection($connStr)
    $conn.Open()
    $cmd=$conn.CreateCommand()
    $cmd.CommandText='select * from products'
    $rdr=$cmd.ExecuteReader()
    0..($rdr.FieldCount-1) | %{$rdr.GetName($_)}
    $conn.Close()
    If you want credentials just add them.
    $connStr='Data Source={0}; Database={1}; Trusted_Connection=True;UID={2};PWD={3};' -f  $datasource,$database,uid,$pwd
    ¯\_(ツ)_/¯

  • Query to find the user is having access to sql server DB

    Hi,
    Please help me in this.
    Query to find the whether the user is having access to sql server DB.
    Cheers,
    sajith

    TUBBY_ORCL?Select 1 from dual where 'ORACLE' = 'SQL SERVER';
    no rows selected
    Elapsed: 00:00:00.01

  • What are the different ways in accessing the SQL server from NWDS ?

    Hi Experts,
    Can anyone suggest the different ways for accessing the SQL server from NWDS.I also want to know whether any tool is available for accessing SQL server from Webdynpro java application in Netweaver development studio.
    I am currently using JDBC driver for accessing the SQL server from Webdynpro java application in NWDS.
    Regards,
    Krishna Balaji T

    Note - that no internet backup service has been proven to be safe and effective for backing up the iPhoto library - unless you personally have backup uyp an iPhoto library and restored it sucussfuly form one it should not be recommended - a large number of people have lost their photos trying it
    LN

  • Accessing Microsoft SQL Server Data by using Oracle Forms 9i

    I am currently working on a Project with Oracle Forms 9i at front end and Microsoft
    SQL server at back end. Could Any one please recommand me the STEPS to connect Oracle forms 9i application with SQL Server database.
    Thanks in Advance...
    M. Aamer Javaid
    Oracle Certified DBA
    [email protected]

    1). Is this functionality be added to Forms 10g or later products or it is obsoleted.
    There are no plans to add OCA functionality.
    2). Steps to connect Forms 9i natively by using Java Importer.
    You will need to write some Java to connect to your source, perform the operations you want to do, and return that data to Forms. Doing this, though, means that you may lose the transaction management functionality that Forms provides for you.
    I cannot tell you what Java to write. It depends on your source and what you want to achieve. As for how to use the Java Importer, this is in the Forms documentation and there are papers on the Forms page on OTN.
    3). Any third party product that can conenct the both products natively.
    I don't know of any.
    Regards,
    Robin.

  • How many users can login to Microsoft SQL Server 2012 standard?

    I searched around the forum but didn't find anything specific.
    I downloaded Microsoft SQL Server Standard 2012. How many users can login into it? 

    Hi Texastig,
    Welcome to forum. I guess Sean/Vaibhav aptly answered your question can you please mark there reply as answer. An OP  does not marks his own comment as answer which actually is thank you comment or unless he himself found an answer
    Thanks for understanding
    Please mark this reply as answer if it solved your issue or vote as helpful if it helped so that other forum members can benefit from it
    My Technet Wiki Article
    MVP

  • Error with date field when inserting records into sql server from webdynpro

    Dear SDN's,
    I am trying to insert the records into sql server through my webDynpro program.
    I have created a date field in a dictionary with the datatype date.
    In my webdynpro program to insert the date i am following the below format.
    String dateString = "2006/12/10";
          java.util.Date d=new java.util.Date(dateString);
          java.sql.Date <b>date</b> = new java.sql.Date(d.getTime());
    int i=stmt.executeUpdate("INSERT INTO TRAVEL_HEADER(TRQID,PROJECTID,<b>REQDT</b>,ADVCE,ETADV,PURTR) values(21, '555-1212', '" + <b>date</b> + "', 5000, '20060501','hi')");
    when i try to execute it, it gives the following error.
    <b>com.sap.sql.log.OpenSQLException: The SQL statement "INSERT INTO "TRAVEL_HEADER" ("TRQID","PROJECTID","REQDT","ADVCE","ETADV","PURTR") VALUES (21,'555-1212','2006-12-10',5000,'20060501','hi')" contains the semantics error[s]: - type check error: new value (element number 3 (CHAR)) is not assignable to column  >>REQDT<< (DATE)</b>
    Please correct me.
    Your help will be appreciated.
    Regards,
    Sireesha.B

    Hi,
    int i=stmt.executeUpdate("INSERT INTO TRAVEL_HEADER(TRQID,PROJECTID,REQDT,ADVCE,ETADV,PURTR) values(21, '555-1212', 'date', 5000, '20060501','hi')");
    try like this.
    I Think in SQL the general format to take date as input like this.
    INSERT INTO X VALUES ('10/30/56')
    thaks,
    Lohi.

  • How to fix Login failed for user ''. (Microsoft SQL Server, Error: 18456)in windows 2008?

    Hi All,
    we are facing the Login fails issue .
    how to resolve the bellow error , could you please suggested the possible ways .. ASAP
    TITLE: Connect to Server
    Cannot connect to ..
    ADDITIONAL INFORMATION:
    Login failed for user '  domain\name'. (Microsoft SQL Server, Error: 18456)
    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=18456&LinkId=20476
    BUTTONS:
    OK
    Log Name:      Application
    Source:        MSSQLSERVER
    Date:          10/6/2011 1:56:28 PM
    Event ID:      18456
    Task Category: Logon
    Level:         Information
    Keywords:      Classic,Audit Failure
    User:          domain\name
    Computer:      
    Description:
    Login failed for user '  domain\name'. Reason: Token-based server access validation failed with an infrastructure error. Check for previous errors. [CLIENT: <local machine>]
    RAM

    I was hitting myself in the head with this problem for a couple of minutes.... Everything was fine on the DC and Domain itself.. I added the Domain admins Group Principal for which I am part of... I was getting this error  ... Long History... Short
     (Right Click and Run as Administrator took care of this for me..) UAC was the cause of the problem.
    Cannot connect to XX-DB-XX3.
    ===================================
    Login failed for user 'XXXXS\XXas'. (.Net SqlClient Data Provider)
    For help, click: http://go.microsoft.com/fwlink?ProdName=Microsoft+SQL+Server&EvtSrc=MSSQLServer&EvtID=18456&LinkId=20476
    Server Name: XX-DB-XX3
    Error Number: 18456
    Severity: 14
    State: 1
    Line Number: 65536
    Program Location:
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
       at System.Data.SqlClient.SqlInternalConnectionTds.CompleteLogin(Boolean enlistOK)
       at System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, Boolean ignoreSniOpenTimeout, Int64 timerExpire, SqlConnection owningObject)
       at System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(String host, String newPassword, Boolean redirectedUserInstance, SqlConnection owningObject, SqlConnectionString connectionOptions, Int64 timerStart)
       at System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(SqlConnection owningObject, SqlConnectionString connectionOptions, String newPassword, Boolean redirectedUserInstance)
       at System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, Object providerInfo, String newPassword, SqlConnection owningObject, Boolean redirectedUserInstance)
       at System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection)
       at System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup)
       at System.Data.ProviderBase.DbConnectionFactory.GetConnection(DbConnection owningConnection)
       at System.Data.ProviderBase.DbConnectionClosed.OpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory)
       at System.Data.SqlClient.SqlConnection.Open()
       at Microsoft.SqlServer.Management.SqlStudio.Explorer.ObjectExplorerService.ValidateConnection(UIConnectionInfo ci, IServerType server)
       at Microsoft.SqlServer.Management.UI.ConnectionDlg.Connector.ConnectionThreadUser()

  • BOXI R2 deployment on Solaris, data access to SQL Server and DB2

    <p>Have you deployed BusinessObjects XI Release 2 on Solaris and are accessing Microsoft SQL server 2000/2005? How about DB2? We had planned on using JDBC for SQL Server, and StarSQL 5.x  for DB2. We are having trouble with configuration planning.</p><p>Anyone have experience with this?</p>

    <p>Have you deployed BusinessObjects XI Release 2 on Solaris and are accessing Microsoft SQL server 2000/2005? How about DB2? We had planned on using JDBC for SQL Server, and StarSQL 5.x  for DB2. We are having trouble with configuration planning.</p><p>Anyone have experience with this?</p>

  • Syntax error when creating a user-defined table type in SQL Server 2012

    Why am I getting a syntax error when creating a user-defined table type in SQL Server 2014?
    CREATE TYPE ReportsTableType AS TABLE 
    ( reportId INT
    , questionId INT
    , questionOrder INT );
    Results:
    Msg 156, Level 15, State 1, Line 1
    Incorrect syntax near the keyword 'AS'.

    Hope these posts could help, 
    https://social.msdn.microsoft.com/Forums/sqlserver/en-US/37a45a9a-ed8c-4655-be93-f6e6d5ef44be/getting-incorrect-syntax-while-creating-a-table-type-in-sql-server-2008-r2?forum=transactsql
    Regards, Dineshkumar,
    Please Mark as Answer if my post answers your question and
    Vote as Helpful if it helps you

  • How do you give user permissions to access a terminal server?

    How do you give user permissions to access a terminal server?

    Refer : http://technet.microsoft.com/en-us/library/cc781509(v=ws.10).aspx
    Arnav Sharma | http://arnavsharma.net/ Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading
    the thread.

  • Lync 2013 Enabling Cross-Database Access in SQL Server

    Hello,
    I want to know when Enabling Cross-Database Access in SQL Server will be enabled for Lync Server 2013.
    Will Lync Server enable it by default?
    Stmart

    DCOM Errors are awful.  Here's a few articles that I've read before that match your error. Some you've likely already seen...
    http://d1it.wordpress.com/2013/10/28/dcom-move-lync-user/
    http://blogs.technet.com/b/dodeitte/archive/2010/12/19/issue-when-moving-legacy-users-to-a-lync-server-2010-pool-using-hlb.aspx
    http://www.networksteve.com/windows/topic.php/Unable_to_Move_users_between_2_Lync_Pools/?TopicId=61736&Posts=2
    http://www.bibble-it.com/2011/03/22/unable-to-move-lync-user-dcom-error
    Using the -force command as Saleesh noted should work, but will kill your contacts.  If it's just a few users that are acting up, you can restore the contacts from backup for these users (export-csuserdata before you start).
    Is it all users, or just a handful?
    Please remember, if you see a post that helped you please click "Vote As Helpful" and if it answered your question please click "Mark As Answer".
    SWC Unified Communications

  • How can I develope a native mobile cross platform app that can access an SQL server.

    I would do it in html5 as a web app but I also need to access an SQL server and upload data(text) pictures from the camera and
    geolocation data etc.
    I've developed many web based applications, but this is this first attempt to integrate native device functions AND interact with an SQL database.
    So it would have to be able to use form data  then add a photo and geolocation and send everything to the database.
    A site with examples and/or tutorials would be nice.
    To make things worse, I'd also have to be able to work offline and re-sync when networks connections allow.
    If a native app would be too complex, then I was thinking I might be able to develope an app that gathers data then
    passes the info on to a browser to connect with the database.
    But as much as possible I don't want to have to swing back and forth between a browser and an app.
    Pete

    Here is a page a I bookmarked a while back to use jQUERY to access a php scripts sitting on a server that can then interact with the database in the usual way. This means that you will be able to use DW to create the usual HTML CSS and jQuery to make an interactive app.
    I havn't yet tried this but a quick look over the script looks good. Make sure you use php that sanitizes input.
    http://stackoverflow.com/questions/8246380/adding-a-database-to-jquery-mobile-site
    Let me know how you go.

  • RH server 8 - upscaling from Access to SQL Server 2008?

    Hi gang-
    We are currently running RoboHelp Server 8 on the default Access database and Tomcat. We would like to increase the number of help projects that are tracked by the RH Server, and have concerns that Access will handle the increased load, so we are considering upsizing to SQL Server 2008.
    Our IT people think this should be fairly straightforward, but want to know if Adobe provides any tool or has any recommendations when upsizing from Access to SQL Server.They are concerned about retaining things like primary and secondary keys, as well as any indexes that are currently in Access.
    If anyone has experience with such a migration, please share!
    Thanks,
    -=Ed.

    We are also currently on an Access DB and considering (have been for some time but that's a different story) upgrading to SQL Server. There is no migration tool from Access to SQL Server provided so you'd have to allow some additional effort if you want to retain the data. I am not an expert on DBs but I'm sure there are ways to migrate the data. I have found a few links when searching on Google. For example:
    http://support.microsoft.com/kb/237980
    Adobe does provide a cheat sheet at the link below which may be useful to you.
    http://blogs.adobe.com/techcomm/2009/05/advanced_database_setup_for_robohelp_server_8.html
      The RoboColum(n)
      @robocolumn
      Colum McAndrew

  • What is the best NLS config to be near the ACCESS or SQL Server characters set

    Hi all,
    I am working with an Oracle for Windows.
    I have serious problems with my actual characters set.
    What is the best NLS config to be near the ms-Access or SQL Server characters set behavior ?
    For exemple :
    I have a table with city names
    I want to find the nearest >= city name of a given criteria. so i do this SQL
    SELECT Nom FROM TLCommune WHERE Nom >= 'LIMOGES' ORDER BY Nom, Pays, Dept, Insee
    This SELECT give this result under SQL plus worksheet (same via VB and ADO)
    Why the cities from krosno to Limerick are listed regarding on the WHERE clause Nom >= 'LIMOGES' ?
    NOM
    krosno
    La Manche et la Mer d'Irlande
    Laesv
    Lancashire
    Landes
    Lappi (Lappland)
    Latviya
    Legnica
    Leicester and Rutland
    Leipzig
    Leningrad
    NOM
    Leon
    Lirida
    Leszno
    Liberec
    Libiria
    Libye
    Limburg
    Limburg (Limbourg)
    Limerick
    LIMOGES <--------------------------------------- the city in the nom >= 'LIMOGES' in the SQL statement
    LIMOGES-FOURCHES

    Hi,
    Try these steps:-
    * Open the GUI of Root bridge
    Go to Security/SSID Manager/create SSid/map it to the radio
    * Under Client Authentication setting
    Check the box Open authentication with no Addition ..
    * Then click Apply
    * Go to Ecryption Manager page
    Under Ecryption Modes
    Select Cipher ---TKIP
    Under Encryption Keys
    Select Encryption Key 2 ------Don't put any key ... Leave the box blank and key size be 128bit
    Then click Apply
    * Come back to SSID Manager page
    Under Client Authenticated Key Management ..
    Select Key Management:- Mandatory
    Check the box:- WPA
    Under WPA Pre-shared Key:- Type atleast 8 character key..
    Click Apply:-
    * Then we need to repeat the same settings on Other bridge except the station role will be non-root.
    Now to troubleshoot...
    * First make Bridge are able to talk to each when there is on security setup
    * Set a simple Pre-shared Key ... example 1234567890 on both bridge .. Bridge will not associate if key mismatch..
    Hope this will work for you.

Maybe you are looking for