I was evaluating what I thought was a string read from a file, then doing an .indexOf on that string. Took me over an hour to debug something so simple.
Trying to get the position of a string within a larger string is pretty basic stuff; yet I was getting the mystery result of -1.
I then printed the file to console, copied into a separate program as a string, and it worked fine.
I was also puzzling why the .LastIndexOf variable didn’t appear in the auto-complete of ISE. That should have been my clue.
When I did the following:
<pre> $templateContent = Get-Content $inputTemplate </pre>
this creates an array in $templateContent, and arrays have a similar method called .IndexOf.
The solution was to add the “-raw tag”. I had tried “-encoding ASCII” and various encodings, and that not getting me anywhere.
<pre> $templateContent = Get-Content $inputTemplate -raw </pre>
Then the code to do the .IndexOf was straight forward. At first, I thought my issue was within the quotes in quotes, so I simplified to something like basic like the word “xml”.
<pre> $valueCustId = "Value=`"%CUSTID%`""; $valueCustId = "xml"; $posValueCustId = $updatedTemplateContent.IndexOf($valueCustId) Write-Host "posValueCustId = $posValueCustId" </pre>