Search code examples
xmlpowershellcurl

running a curl on several XML files in powershell


I've written my first PowerShell script from findings on the net. I want the script to make a web call to generate a CSV file, then convert the rows of the csv into individual XML files. then pass the xml to a CURL routine to post it into my system.

I've successfully got it to generate the CSV, generate the XMLS and but I'm having issues with the curl process.

I can get it to run the curl on the last file it creates but not all the files it created.

i tried to run a get-child items on the directory the files were created in then run a for each routine to cycle through the file names. but that doesn't work either.

I welcome some advice from you experts

here is my full code

#Variables
$Logfolder = 'D:\openacc\etst5080\IMIR_Config\Spool\'               #Location of Spool directory
$logDate = get-date -Format "MM-dd-yyyyHHmmss"
$LogName = $logFolder + "PowerShellLog_" + $LogDate +'.log'
$FilePath = 'C:\Temp\testCSV.csv'                                       #file location for the CSV to import
$XMLPostURL = 'http://mripf203mcy:8084/e.tst'                           #http address for CURL post
$eBISFAURL = 'D:\openacc\etst5080\IMIR_Config\temp\fileactioner\'       #URL for eBIS FileActioner
$eBISCURLURL = 'D:\openacc\etst5080\IMIR_Config\temp\'
$eBISPostMethod = 'Actioner'                                                #How is the data to post into eBIS set to either "CURL" or "Actioner"
$XMLDirectory = ''                                                      #temp directory where XML files will post
$DebugMode = 'ON'   
                                                    #Enable debugging to output txt file of results.

Start-Transcript -path $LogName

#DebugVariables
Write-Host "Variables:"
Write-Host "Log File =" $LogFile
Write-Host "File Path ="  $FilePath
Write-Host "XMLPostURL ="  $XMLPostURL
Write-Host "eBISFAURL =" $eBISFAURL
Write-Host "eBISCURLURL =" $eBISCURLURL
Write-Host  "eBISPostMethod =" $eBISPostMethod
Write-Host  "XMLDirectory = " $XMLDirectory


if ($eBISPostMethod -eq 'CURL') 
{
$XMLDirectory = $eBISCURLURL
}
else 
{
$XMLDirectory = $eBISFAURL
}

$docTemplate = @'
<objItem>
$($invoice -join "`n")
</objItem>
'@

# Per-invoice template.
$entryTemplate = @'
    <objID></objID>
    <objType>IMIR_MRI</objType>
    <alphaID></alphaID>
    <rtgStageName>ScriptImport</rtgStageName>
    <uuserID>System</uuserID>
    <fld01>oa$</fld01> 
    <fld02></fld02>
    <fld03></fld03>
    <fld04>$($FileName.SupplierCode)</fld04>  
    <fld05>$($FileName.DocumentValue)</fld05>
    <fld06>$($FileName.GoodsValue)</fld06>
    <fld07></fld07>
    <fld08>$($FileName.Variance)</fld08>
    <fld09></fld09>
    <fld10></fld10>
    <fld11></fld11>
    <fld12></fld12>
    <fld13>$($FileName.Company)</fld13>
    <fld14>$($FileName.Department)</fld14>
    <fld15></fld15>
    <fld16></fld16>
    <fld17></fld17>
    <fld18>$($FileName.SupplierName)</fld18>
    <fld19></fld19>
    <fld20></fld20>
    <fld21></fld21>
    <fld22></fld22>
    <fld23></fld23>
    <fld24></fld24>
    <fld25></fld25>
    <fld26></fld26>
    <fld27></fld27>
    <fld28></fld28>
    <fld29></fld29>
    <fld30></fld30>
    <fld31>$($FileName.Document)</fld31>
    <fld32>D1/223</fld32>
    <fld33></fld33>
    <fld34></fld34>
    <fld42>$($FileName.DocType)</fld42>
    <fld43>$($FileName.DocNumber)</fld43>
    <fld44>$($FileName.Reference)</fld44>
    <fld45>$($FileName.DocDate)</fld45>
    <fld46>$($FileName.Description)</fld46>
    <fld47>$($FileName.Document)</fld47>
'@



#Step 1 Generate CSV file by calling routine

Write-Host "run extract to generate CSV @ " + $(get-date)

try
{
    $URLParams = 'http://MRIPF203MCY:8084/e.tst/wFlow/webItemUpdate.w?CodeKey=X_lkmbjezdzfkbcpfN&key=202201250000001129&goChoice=_W_Approve'
    $Response = Invoke-WebRequest -Uri $UrLParams
    # This will only execute if the Invoke-WebRequest is successful.
    $StatusCode = $Response.StatusCode
} catch {
    $StatusCode = $_.Exception.Response.StatusCode.value__
}
Write-Host "Extract Complete Status Code =" $StatusCode - $Response.StatusDescription $(get-date)

#Step 2 Import CSV file
Write-Host "Import CSV file @" $(get-date)

Import-Csv -Path $FilePath -Delimiter ',' | Group-Object FileName -ov grp | ForEach-Object {
  # $_.Group contains all invoice associated with the user at hand.
  # Create an XML element for each certificate and collect the results
  # in array.
  $invoice = foreach ($FileName in $_.Group) {
    # Instantiate the per-certificate template.
    $ExecutionContext.InvokeCommand.ExpandString($entryTemplate)  
  }
  # Instantiate the per-user template, which encompasses
  # the per-certificate elements, and output the result. 
  Write-host $XMLDirectory $FileName.FileName'.xml generated'
  $ExecutionContext.InvokeCommand.ExpandString($docTemplate)
} | # Write the resulting XML document string to a file named for the user ID
    Set-Content -LiteralPath { $XMLDirectory + $FileName.FileName + '.xml' } 



#Step 4 Run CURL if required
if ($eBISPostMethod -eq 'CURL'){
$curlDir = $XMLDirectory + $FileName.FileName + '.xml' 
$curlDIR
$Filenames = Get-ChildItem -path 'D:\openacc\etst5080\IMIR_Config\Temp' -filter *xml
$Filenames
$filenames.name
Foreach ( $filenames in Get-ChildItem )
{curl.exe -d $xmlDirectory+@$Filenames.name -H "Content-Type: text/xml" http://mripf203mcy:8084/e.tst/xmlpost.w?params=IMIR,TEST,xmlImport,text
}
else {
    $statusMessage = 'Invoices will be processed by eBIS fileActioner'

}
Write-Host 'Scriptcompleted @ ' $(get-date)
stop-transcript

Solution

  • Replace:

    curl.exe -d $xmlDirectory+@$Filenames.name

    with:

    curl.exe -d (Join-Path $xmlDirectory "@$($Filenames.Name)")

    Or, if the value of $xmlDirectory is guaranteed to end with a path separator (\ or /), as in your case:

    curl.exe -d ($xmlDirectory + "@$($Filenames.Name)")

    In general, in order to pass the value of expressions - such as an + operation - as a command argument, enclosure in (...) is required - see this answer for details.


    $xmlDirectory+@$Filenames.name

    Such an argument is implicitly treated as if it were an expandable (double-quoted) string ("..."), i.e. the same as "$xmlDirectory+@$Filenames.name"; therefore, the following characters / substrings are interpreted verbatim (which probably isn't your intent):

    • +
    • @
    • .name

    See this answer for an overview of the syntax rules in expandable strings ("...") .