Powershell script to extract the data from database using the data in input file and save the results in csv file

29 views Asked by At

SCRIPT TO EXTRACT THE ALL DETAILS

    #Variable to hold variable.
    $SQLServer = "XXXX"
    $SQLDBName = "XXXX"
    #Customer data input file path
    $InputFile = "F:\\CData.csv"
    # Reading the data in input file
    $InputFileContents = Get-Content -Path $InputFile
    #SQL Query for periodic payments.
    $SqlQuery = "SELECT ID,
    FROM \[XXXX\].\[dbo\].\[XXXX\] WITH(NOLOCK) where PSTATUS = 'F' AND Number IN  ($InputFileContents) ORDER BY Number"
    $SqlConnection = New- Objectsystem.Data.SqlClient.SqlConnection("Server=$SQLServer;Database=$SQLDBName;Integrated  Security=True")
    $SqlConnection.Open()
    $SqlCmd = New-ObjectSystem.Data.SqlClient.SqlCommand($SqlQuery, $SqlConnection)
    $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter($SqlCmd)
    $DataSet = New-Object System.Data.DataSet
    $SqlAdapter.Fill($DataSet)
    $Sqlconnection.Close() 
    # Extracts are saving to CSV fil
    $DataSet.Tables\[0\] | Export-Csv "F:\\output.csv" -NoTypeInformation -Encoding UTF8 
    # Get the current date and time
    $dateTime = Get-Date -Format "yyyyMMdd-hh-mm-ss"
    # Add the date and time stamp to the file name
    $fileName = "F:\\output$dateTime.csv"
    # Move the file to new file date & time
    Move-Item "F:\\output.csv.csv" $fileName

I tried above script but i am getting below error while running it Exception calling "Fill" with "1" argument(s): "Incorrect syntax near ')'." At F:\period.ps1:17 char:1

  • $SqlAdapter.Fill($DataSet)
  •   + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
      + FullyQualifiedErrorId : SqlException
    
    

Export-Csv : Cannot bind argument to parameter 'InputObject' because it is null. At F:\period.ps1:20 char:22

  • $DataSet.Tables[0] | Export-Csv "F:\output.c ...
  •   + CategoryInfo          : InvalidData: (:) [Export-Csv], ParameterBindingValidationException
      + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.ExportCsvCo
    mmand
    
0

There are 0 answers