0

I'm trying to find .nfo files that aren't XML. It seems to mostly work, but some of the files are XML and are still being listed. One example has this for the first line:

<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>

Here is my code. I'm not sure what I am doing wrong.

Get-ChildItem "c:\*.nfo" -recurse | ForEach-Object {
    if (Get-Content -LiteralPath $_ -First 1 | Select-String -Pattern 'xml' -NotMatch) 
    {
        Write-Output $_.Fullname
    }
}

I don't care if they are properly formatted XML files so I am just using the first line to test.

6
  • 2
    -LiteralPath $_ -> -LiteralPath $_.FullName Commented Nov 20, 2020 at 3:52
  • A different option to Mathias' would be to pipe the FileInfo object to Get-Content, the PSPath property would be used as an alias for LiteralPath. if (-not ($_ | Get-Content -TotalCount 1).Contains('xml')). Select-String shouldn't be needed as you've already got the first line anyway, and -First is an alias so using the main parameter name -TotalCount may be better practise. Commented Nov 20, 2020 at 7:17
  • I guess some of your xml files start with an empty line. Please try to create an minimal reproducible example: remove the out loop, and show the first lines of your failing xml file in the question. Commented Nov 20, 2020 at 8:16
  • @iRon I thought that two and tried getting the first two lines but it was the same result. I also looked at one of those files in Notepad++ showing all characters and there is no extra characters like a line feed. I will change the code to output the first line and see what it shows. Commented Nov 20, 2020 at 15:12
  • The answer #1 below gave errors due to not using LiteralPath. When using LiteralPath it yielded the exact same results as my code. Some of the filenames have brackets. Commented Nov 20, 2020 at 15:13

1 Answer 1

1

try this

Get-ChildItem "c:\*.nfo" -recurse | Where-Object{(Get-Content $_ -First 1) -notmatch 'xml'}
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.