1

I have a text file (on local filesystem) that is a map of ID values with file names:

1111, testfile1.xml
2222, testfile2.xml
3333, testfile3.xml

Each line is a map entry, so "1111" is the corresponding ID value for testfile1.xml.

I'm trying to post each testfile to an endpoint, but need to grab the associated ID value that corresponds to the file since it is needed in the URI of the endpoint that we are POST-ing to.

Code snippet from my script that recurses a directory that contains all the testfilex.xml's and does the POST:

$testFiles = Get-ChildItem $testFileDir
$mapFileLocation = "C:/local/Desktop/map.txt"

foreach ($file in $testFiles) {
    $content = Get-Content $file.PSPath
    #$id = GRAB ID HERE /*TODO*/
    $URI = "http://www.myendpoint:1000/" + $id 
    $request = Invoke-WebRequest -Uri $URI -Method PUT -Body $content -ContentType "application/xml"

Is there any way I can build $id like this via PowerShell? Possibly by regex-ing? Can text files even be parsed like this?

1
  • 1
    Have you considered Import-Csv? Commented Aug 25, 2016 at 21:47

1 Answer 1

1

Read the map file into a hashtable where you use the filename as the key and the ID as the value.

$map = @{}
Import-Csv $mapFileLocation | ForEach-Object { $map[$_.Filename] = $_.ID }

If your map file doesn't have headers you can define header names for the columns via the parameter -Header:

Import-Csv $mapFileLocation -Header ID,Filename

If the file contains whitespace as shown in your example you may also want to Trim() the values.

Once you created the hashtable you use it like this:

foreach ($file in $testFiles) {
    $content = Get-Content $file.FullName
    $URI = 'http://www.myendpoint:1000/' + $map[$file.Name]
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.