How to add hash table values to SQL Table using Powershell

Hi,
I have sharepoint list with four(column1, column2, column3,column4)columns.I am reading the list column values and adding to hashtable. Now I want to add values from hastable to SQL table with four(column1, column2, colum3,column4)columns using powershell.
I have written the following script for single column but I would like to know how to add values for multiple columns.
            if(($key -eq "Column1") )
               $SqlQuery = "INSERT INTO [TableName] ([Column1]) VALUES ('" + $HashTable.Item($key) +"')"
               #Set new object to connect to sql database
               $connection = new-object system.data.sqlclient.sqlconnection
               $Connection.ConnectionString ="server=SQLServerName;database=SQLDBName;Integrated Security = True;"
          $connection #List connection information 
               $connection.open() #Open Connection
             $Cmd = New-Object System.Data.SqlClient.SqlCommand
             $Cmd.CommandText = $SqlQuery
               $Cmd.Connection = $connection
              $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
              $SqlAdapter.SelectCommand = $SqlCmd
              $DataSet = New-Object System.Data.DataSet
              $SqlAdapter.Fill($DataSet)
              $DataSet.Tables[0]
              $connection.Close()
Can anybody please help me out to accomplish the task? Any help would be greatly appreciated.
AA.

Hi AOk2013,
Not knowledgable on PowercShell, based on my understanding on HashTable in Java, Some modification you can make in your code to achieve your requirement.
If the Keys in HashTable are "Column1","Column2","Column3","Column4", you can reference below.
if(($key -eq "Column1") ) #what is the purposed of this if ?
#$SqlQuery = "INSERT INTO [TableName] ([Term]) VALUES ('" + $HashTable.Item($key) +"')"
#specify the real column names in the table
$SqlQuery = "INSERT INTO [TableName] ([ColumnA],[ColumnB],[ColumnC],[ColumnD]) VALUES ('" + $HashTable.Item("Column1") +"','"+ $HashTable.Item("Column2") +"','"+$HashTable.Item("Column3") +"','"+$HashTable.Item("Column4") +"')"
#Set new object to connect to sql database
$connection = new-object system.data.sqlclient.sqlconnection
$Connection.ConnectionString ="server=SQLServerName;database=SQLDBName;Integrated Security = True;"
$connection #List connection information
$connection.open() #Open Connection
$Cmd = New-Object System.Data.SqlClient.SqlCommand
$Cmd.CommandText = $SqlQuery
$Cmd.Connection = $connection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$DataSet.Tables[0]
$connection.Close()
Since your question is regarding PowerShell, I would suggest you post it in a dedicated
PowerShell Forum. It is more appropriate and more experts will assist you.
If you have any feedback on our support, you can click
here.
Eric Zhang
TechNet Community Support

Similar Messages

  • How to add multiple users permissions to a calendar using powershell?

    I have an organization that was recently setup in Exchange Online and they have unique circumstances in that every user in the organization needs "reviewer"
    access to every other users calendars.  I cannot change the default permission since new users added after this should not be able to see these calendars details.  There are a few I will go back to run a Set command on to change an individual permission
    here and there for specific needs, but the main need is below.
    I have basic experience with powershell commands and have found how to manually add a single users permissions to a calendar using the command below:
    Add-MailboxFolderPermission -Identity alias:\calendar -user alias -AccessRights reviewer
    Since it's not realistic to run this command thousands of times changing the user aliases each time, I was hoping someone could help me build a command to run on a single mailbox's calendar that would add every current user in the organization with certain
    permissions such as "reviewer" or "availabilityonly".
    Thanks for the help!

    Hi,
    A possible solution is to do this via Security Groups.
    Add-MailboxFolderPermission -Identity [email protected]:\Calendar -User [email protected] -AccessRights Owner
    This way, you simply add users that require access to the CalendarOwnerAccessGroup
    You still have to run this on every mailbox that should have this feature, but that could be solved using powershell piping.
    http://technet.microsoft.com/en-us/library/ee176927.aspx
    /Anders Eide

  • How to add new group entry in Cisco Vpn using powershell

    I am working on a powershell script to connect cisco vpn using powershell, I am able to connect to vpn but not sure how to add new group to vpn. I am using the following script$vpn_profile = 'Test'
    $username = 'TestUser'
    $userPassword = ConvertTo-SecureString -String "Password" -AsPlainText -Force
    $credentials = new-object -typename System.Management.Automation.PSCredential -argumentlist
    $username,$userPassword
    $password = $credentials.GetNetworkCredential().Password
    Set-Location 'c:\Program Files (x86)\Cisco Systems\VPN Client'
    .\vpnclient.exe connect $vpn_profile user $username pwd $password
    Write-Host "You Are Connected"
    cd "C:\"

    Have you entered .\vpnclient.exe /? to see if it will return information about other switches you can use with this executable? Other than connect, I was able to track down a few without actually having the executable (http://www.scribd.com/doc/40108893/Cisco-VPN-Client-Command-Line).
    That said, I do not believe that there is a switch that will help you create a connection. These are either done manually through the GUI, or can be likely be added by supplying a properly formatted file in the proper place.
    If you're using the version of the Cisco VPN client I think you are, then your connection settings, or profiles, are stored in individual .pcf files somewhere on your computer (likely in the Cisco directory). These are simple, text-based files. Find one
    on your computer, save it with another name, and then modify it manually. If you really want to use PowerShell, then use this opportunity to learn how to create and edit basic text files using PowerShell. If you have a standard connection file, then you can
    put that file onto remote computers any number of ways. If a .pcf file exists in the proper place when the VPN client is opened, then it likely will not prompt for a new connection.
    Update: Added more info; clarified

  • From two given tables, how do you fetch the values from two columns using values from one column(get values from col.A if col.A is not null and get values from col.B if col.A is null)?

    From two given tables, how do you fetch the values from two columns using values from one column(get values from col.A if col.A is not null and get values from col.B if col.A is null)?

    Hi,
    Use NVL or COALESCE:
    NVL (col_a, col_b)
    Returns col_a if col_a is not NULL; otherwise, it returns col_b.
    Col_a and col_b must have similar (if not identical) datatypes; for example, if col_a is a DATE, then col_b can be another DATE or it can be a TIMESTAMP, but it can't be a VARCHAR2.
    For more about NVL and COALESCE, see the SQL Language manual: http://docs.oracle.com/cd/E11882_01/server.112/e26088/functions119.htm#sthref1310
    I hope this answers your question.
    If not, post a little sample data (CREATE TABLE and INSERT statements, relevant columns only) for all tables involved, and also post the results you want from that data.
    Explain, using specific examples, how you get those results from that data.
    Always say which version of Oracle you're using (e.g., 11.2.0.2.0).
    See the forum FAQ: https://forums.oracle.com/message/9362002

  • How can i pass calculated value to internal table

    Hi
    i have to pass calculated value into internal table
    below field are coming from database view and i' m passing view data into iznew1
    fields of iznew1
                 LIFNR  LIKE EKKO-LIFNR,
                 EBELN  LIKE EKKO-EBELN,
                 VGABE  LIKE EKBE-VGABE,
                 EBELP  LIKE EKBE-EBELP,
                 BELNR  LIKE EKBE-BELNR,
                 MATNR  LIKE EKPO-MATNR,
                 TXZ01  LIKE EKPO-TXZ01,
            PS_PSP_PNR  LIKE EKKN-PS_PSP_PNR,
                 KOSTL  LIKE EKKN-KOSTL,
                 NAME1  LIKE LFA1-NAME1,
                 NAME2  LIKE LFA1-NAME2,
                 WERKS  LIKE EKPO-WERKS,
                 NETWR  LIKE EKPO-NETWR,
                 KNUMV  LIKE EKKO-KNUMV,
                 GJAHR  LIKE EKBE-GJAHR,
    and now i want to pass
    one field ED1  which i has calculated separatly and i want to pass this value into iznew1
    but error is coming that iznew1 is a table with out header line  has no component like ED1.
    so how can i pass calculated value to internal table iznew1,

    When you declare your internal table , make an addtion occurs 0
    eg . data : begin of iznew occurs 0 ,
                    fields ...
       add the field here ed1.
               end of iznew.
    now when you are calculating the value of ed1,
    you can pass the corresponding value of  ed1 and modify table iznew.
    eg
    loop at iznew.
    iznew-ed1 = ed1.
    modify iznew.
    endloop.

  • How to add new field into dynamic internal table

    Hello Expert.
    how to add new field into dynamic internal table.
    PARAMETERS: P_TABLE(30).    "table name
    DATA: I_TAB TYPE REF TO DATA.
    FIELD-SYMBOLS: <TAB> TYPE standard TABLE.
    *Create dynamic FS
    create DATA I_TAB TYPE TABLE OF (p_table).
      ASSIGN I_TAB->* TO <TAB>.
    SELECT * FROM (p_table) INTO TABLE <TAB>.
       here i want to add one more field into <TAB> at LAST position and my 
       Field name  =  field_stype     and
       Field type    =  'LVC_T_STYL'
    could you please helpme out .

    Hi,
    Please find the code below.You can add the field acc to your requirement.
    Creating Dynamic internal table
    TYPE-POOLS: slis.
    FIELD-SYMBOLS: <t_dyntable> TYPE STANDARD TABLE,  u201C Dynamic internal table name
                   <fs_dyntable>,                     u201C Field symbol to create work area
                   <fs_fldval> type any.              u201C Field symbol to assign values 
    PARAMETERS: p_cols(5) TYPE c.                     u201C Input number of columns
    DATA:   t_newtable TYPE REF TO data,
            t_newline  TYPE REF TO data,
            t_fldcat   TYPE slis_t_fldcat_alv,
            t_fldcat   TYPE lvc_t_fcat,
            wa_it_fldcat TYPE lvc_s_fcat,
            wa_colno(2) TYPE n,
            wa_flname(5) TYPE c. 
    Create fields .
      DO p_cols TIMES.
        CLEAR wa_it_fldcat.
        move sy-index to wa_colno.
        concatenate 'COL'
                    wa_colno
               into wa_flname.
        wa_it_fldcat-fieldname = wa_flname.
        wa_it_fldcat-datatype = 'CHAR'.
        wa_it_fldcat-intlen = 10.
        APPEND wa_it_fldcat TO t_fldcat.
      ENDDO. 
    Create dynamic internal table and assign to FS
      CALL METHOD cl_alv_table_create=>create_dynamic_table
        EXPORTING
          it_fieldcatalog = t_fldcat
        IMPORTING
          ep_table        = t_newtable. 
      ASSIGN t_newtable->* TO <t_dyntable>. 
    Create dynamic work area and assign to FS
      CREATE DATA t_newline LIKE LINE OF <t_dyntable>.
      ASSIGN t_newline->* TO <fs_dyntable>.
    Populating Dynamic internal table 
      DATA: fieldname(20) TYPE c.
      DATA: fieldvalue(10) TYPE c.
      DATA: index(3) TYPE c. 
      DO p_cols TIMES. 
        index = sy-index.
        MOVE sy-index TO wa_colno.
        CONCATENATE 'COL'
                    wa_colno
               INTO wa_flname. 
    Set up fieldvalue
        CONCATENATE 'VALUE' index INTO
                    fieldvalue.
        CONDENSE    fieldvalue NO-GAPS. 
        ASSIGN COMPONENT  wa_flname
            OF STRUCTURE <fs_dyntable> TO <fs_fldval>.
        <fs_fldval> =  fieldvalue. 
      ENDDO. 
    Append to the dynamic internal table
      APPEND <fs_dyntable> TO <t_dyntable>.
    Displaying dynamic internal table using Grid. 
    DATA: wa_cat LIKE LINE OF fs_fldcat. 
      DO p_cols TIMES.
        CLEAR wa_cat.
        MOVE sy-index TO wa_colno.
        CONCATENATE 'COL'
                    wa_colno
               INTO wa_flname. 
        wa_cat-fieldname = wa_flname.
        wa_cat-seltext_s = wa_flname.
        wa_cat-outputlen = '10'.
        APPEND wa_cat TO fs_fldcat.
      ENDDO. 
    Call ABAP List Viewer (ALV)
      CALL FUNCTION 'REUSE_ALV_GRID_DISPLAY'
        EXPORTING
          it_fieldcat = fs_fldcat
        TABLES
          t_outtab    = <t_dyntable>.

  • How to add a default value in a site column for every item in a document library

    HI
    i created a content type with some site columns ,
    and included in a Document library.
    Process ( content type)
    -ProcessNo
    -ProcessName
    after that i uploaded 100 Documents but not  added value in a site column process name.
    now  how i add a default value in a site column for every document in a document library 
    adil

    HI
    i get below error when i change the script 
    PS C:\scripts> C:\Scripts\updatedefaultvalue.ps1
    Cannot index into a null array.
    At C:\Scripts\updatedefaultvalue.ps1:8 char:7
    + IF($i[ <<<< "Title"] -eq $null)
        + CategoryInfo          : InvalidOperation: (Title:String) [], RuntimeExce
       ption
        + FullyQualifiedErrorId : NullArray
    $web = Get-SPWeb http://tspmcwfe:89/
    $list = $web.Lists["test"]
    $item = $list.Items | Where { $_["Name"] -eq "Emc" }
    foreach($i in $items)
    IF($i["Title"] -eq $null)
             $i["Title"] = "test"
           $i.Update()
    adil
    Why are you piping a where in the items? Do you only want to add the "test" to ones matching
    a name?
    If you have ISE installed on your server I recommend you put your code in there and debug it. 
    If this is helpful please mark it so. Also if this solved your problem mark as answer.

  • How to assign select-option values to internal table

    hi all,
    how to assign select-option values to internal table
    thanks in advance.

    Hi,
    You just need to loop at your select-option field and take the values from low and high fields.
    for. e.g
    loop at s_werks .
    move:s_werks-low to <your itab>
    if not s_werks-high is initial .
    move: s_werks-high to <youritab>
    endif .
    append <your itab>
    endloop .
    OR use select statement.
    regards,
    Omkar.
    Message was edited by:
            Omkaram Yanamala
    Message was edited by:
            Omkaram Yanamala

  • How can add some suggested value to a propert on a Declarative Component,

    how can add some suggested value to a propert on a Declarative Component?

    kenyatta,
    Where you want to add the value ?
    If you want put some UIComponent(Value) to your declarative Component than follow my blog ( http://jneelmani.blogspot.com/2009/02/11g-how-to-create-declarative-component.html ) and add your value in STEP-5.
    You can watch live-demo at http://www.oracle.com/technology/products/jdev/viewlets/viewlet.html
    --Neelmani Jaiswal
    Edited by: Neelmani Jaiswal on Mar 23, 2009 11:11 AM

  • Transfer data from SAP TABLES to a SQL table

    Hi,
    I need to transfer data from SAP tables to a SQL table. Please suggest the best way as well as the steps please.
    Regards,
    Kamlesh

    Hi
    Step 1: Create an entry for the External database in DBCON table using Trxn: DBCA.
    Field Name Description Value (For: E.g.:)
    CON_NAME Logical name
    for database con RAJ
    DBMS Database system MSS
    USER_NAME Database user <username>
    PASSWORD Password for setting up
    the connection
    to the database <pwd>/<pwd>
    CON_ENV Database-specific MSSQL_SERVER=depotserver MSSQL_DBNAME=HOF_INDORE
    DB_RECO Availability type for an open database connect
    Then, you can define internal table and code the following way:
    DATA: BEGIN OF wa,
    c_locid(3),
    c_locname(50),
    c_locstate(5),
    END OF wa.
    EXEC SQL.
    CONNECT TO 'RAJ' AS 'V'
    ENDEXEC.
    EXEC SQL.
    SET CONNECTION 'V'
    ENDEXEC.
    < Populate SAP data into an internal table >
    Loop on itab.
    EXEC SQL.
    < code here for populating data into MS-SQL Server table>
    ENDEXEC.
    Endloop.
    Regards,
    Raj

  • How to add interface to customlize MXML Component when use Flex Builder 3?

    How to add interface to customlize MXML Component when use
    Flex Builder 3?

    David,
    I don't believe you can add the interface via the creation
    dialog in FlexBuilder 3. You can always manually add the
    "implements" property to your MXML Component root tag. Something
    like this: <mx:VBox implements="com.mycorp.IMyInterface">
    If you want autogeneration of the interface, then create an
    ActionScript class with that interface and then copy the generated
    functions and setter/getters into the script block of your MXML
    component.

  • Diference b/w normal tables and pl/sql tables

    what is the diference b/w normal tables and pl/sql tables.
    already we have tables then what is the purpose of pl/sql tables.
    what are the advantages of pl/sql tables compare nor mal tables.

    user10447332 wrote:
    what is the diference b/w normal tables and pl/sql tables.As BluShadow pointed out "PL/SQL tbles" are now called collections. They are memory structures that store data and go away when your program stops running - essentially arrays or "tables" in other programming languages. "normal" ("heap") tables are stored on disk and are persistant - they store data permanently.
    already we have tables then what is the purpose of pl/sql tables.Collections are used to store data temporarily in memory, when it will be accessed shortly or repeatedly for fast access. This works best with smaller data sets because if you store too much data in a collection you can run out of memory to use
    what are the advantages of pl/sql tables compare nor mal tables.Collections give you faster access to data you need to read more than once during the same application. They work well for fast lookups and for smaller data sets can improve program performance slightly with the use of the bulk collect and forall PL/SQL operators under the right conditions.

  • How to add additional disks on vmware OEL4 and use it for Oracle 10gR2?

    I created a virtual machine on vmware workstation 6 and installed OEL4.
    during first install I created 20 GB disk but now I want to add more disks.
    from vmware documentation I tried to add more 8 gb disk to the virtual host.
    under devices I see two lines;
    Hard Disk (SCSI 0:0) 20.0 GB
    Hard Disk (SCSI 0:2) 8.0 GB
    but I must be missing some step since I can not see 20 + 8 gb at df;
    [root@antuhost ~]# df -h
    Filesystem            Size  Used Avail Use% Mounted on
    /dev/sda1              13G  9.7G  2.3G  82% /
    none                  506M     0  506M   0% /dev/shm
    /dev/sda2             4.9G  851M  3.8G  19% /homeThank you.

    Oh the check the answer from Re: How to add additional disks on vmware OEL4 and use it for Oracle 10gR2?

  • How to set Current quota template dropdownto 50 GB using powershell script

    In central administrator under Application Management -> Configure quotas and locks  we have Current quota template drop down. I  want to set drop down value to 50 GB using powershell . Is it possible and it if it possible then How ? Please
    let me know 
    Thanks in Advance 
    Regards
    Subhash
     

    Hi Sub_84,
    A quota template consists of storage limit values that specify the maximum amount of data that can be stored in a site collection. When the storage limit is reached, a quota template can also trigger an e-mail alert to the site
    collection administrator. You can create a quota template that can be applied to any site collection in the farm. The storage limit applies to the sum of the content sizes for the top-level site and all subsites within the site collection.
    You can create quota template using powershell, ojbect module and sharepoint UI.
    Create new Quota template using powershell:
    $newQuotaTemplate = New-Object Microsoft.SharePoint.Administration.SPQuotaTemplate
    $newQuotaTemplate.Name = "New Quota Template"
    $newQuotaTemplate.StorageMaximumLevel = (150 * 1024) * 1024
    $newQuotaTemplate.StorageWarningLevel = (100 * 1024) * 1024
    $newQuotaTemplate.UserCodeMaximumLevel = 300
    $newQuotaTemplate.UserCodeWarningLevel = 300
    $contentService =[Microsoft.SharePoint.Administration.SPWebService]::ContentService
    $contentService.QuotaTemplates.Add($newQuotaTemplate)
    $contentService.Update()
    Check the link which can guide you how
    http://www.c-sharpcorner.com/uploadfile/anavijai/quota-templates-in-sharepoint-2010/
    Please mark the Answer and vote me if you think that above solution can help you to resolve the issue

  • How to create sharepoint Group with read only permissions using powershell for entire site ?

    How to create sharepoint Group with read only permissions using powershell for entire site (including subsites and top level site)

    Hi
    using (SPSite site = new SPSite(url))
    using (SPWeb web = site.OpenWeb())
    SPUserCollection users = Web.AllUsers;
    SPUser owner = users[string.Format("{0}{1}", "Domain", "Owner Username")];
    SPMember member = users[string.Format("{0}{1}", "Domain", "Default Member Username")];
    SPGroupCollection groups = Web.SiteGroups;
    string GroupName = “Super Exclusive”;//your group name
    string GroupDescription = “Super exclusive group description.”;
    groups.Add(GroupName, owner, member, GroupDescription);
    SPGroup NewSPGroup = groups[GroupName];
    SPRoleDefinition role = Web.RoleDefinitions["Read"];
    SPRoleAssignment roleAssignment = new SPRoleAssignment(NewSPGroup);
    roleAssignment.RoleDefinitionBindings.Add(role);
    Web.RoleAssignments.Add(roleAssignment);
    Web.Update();
    Please 'propose
    as answer' if it helped you, also 'vote
    helpful' if you like this reply.

Maybe you are looking for

  • Batch printing using Applescript - no longer works

    For several years I have been using a simple Applescript to monitor the contents of a folder, print new files then delete these files: on adding folder items to this_folder after receiving added_items repeat with each_item in added_items tell applica

  • Apple loops and importing to logic

    I have logic pro 8 and Soundtrack pro 1 and I want to know if it is possible to link up the loops from soundtrack into logic without having to import them individually. There does 't seem to be a way to do this and it is a pain if you can't. Maybe it

  • Wrong Encoding for JDBC-Receiver

    Dear all, we've to convert from UTF-8 to ISO-8859-1 before we write payload data into database. We've tried with "AF_Modules/XMLAnonymizerBean"  but it does not work! Is there any issue regarding JDBC? Should we use "AF_Modules/TextCodepageConversion

  • Can't click on link in Mac Mail to open Firefox

    I use Firefox as my default browser on my iMac. Now (for the past month) when I click on a link in Mac Mail nothing happens. It works fine on my Mac-book. Does anyone know how to solve this problem? I should say I can click on a link if I set Safari

  • How to handle with display driver error?

    I am using a Toshiba laptop and it keeps crashing on me. It says it is something to do with the display drivers. I can only use it in safe mode. I have tried downloading drivers from the Toshiba website but it says I have not got the software spec to