0

I want to check if I have .xml file first, if I have .xml file, the I have to check the .xml file existed, duplicated or not. For the example, I have those 3 file: ABC_123.xml ABC_456.PRO ABC_123.PRO

From those file, it means I have .xml file (ABC_123.xml), then .xml file is duplicted with this file ABC_123.PRO. Then I have to continue to other process.

I tried this, but it still return the result I have duplicate file, even I change the file name of .xml to DEF_123.xml or other name with .xml extension.

for(;;)
{
$Path = "D:\SERVICE"
if(Test-Path -Path "$Path\*.xml")
{
    Write-Host "XML exist"
    $XML_File = Get-ChildItem -Name "$Path\*.xml"
    $PRO_File = Get-ChildItem -Name "$Path\*.PRO"
    if($XML_File.BaseName -eq $PRO_File.BaseName)
    {
        Write-Host "Duplicated"
        Write-Host "Continue other process
    }
    else{
        Write-Host "Not duplicate, process the xml file"

    }

}
else{
    Write-Host "XML not exist"
}
}
Cheries
  • 834
  • 1
  • 13
  • 32

1 Answers1

1

The script doesn't work, because

$XML_File = Get-ChildItem -Name "$Path\*.xml"
$PRO_File = Get-ChildItem -Name "$Path\*.PRO"
if($XML_File.BaseName -eq $PRO_File.BaseName)

doesn't do what is intended. Get-ChildItem returns an array of FileInfo objects if there is more than one file with matching extension. An array doesn't have BaseName, so if you would use Set-StrictMode -Version 'latest', you'd get an error about non-existing property.

As for a solution, leverage set-based logic. Like so,

# Assume that these test files exist
data.xml
data2.pro
data2.xml
data3.xml

# Two empty arrays, populate each with basenames and see results
$xbase = @()
$obase = @()
@(gci * -include *.xml) | % { $xbase += $_.basename }
$xbase
data
data2
data3

@(gci * -exclude *.xml) | % { $obase += $_.basename }
$obase
data2

Now there are two arrays that contain basenames for XML files and non-XML files. To create a new collection of files that don't have a non-XML counterpart, compare the collections like so,

$onlyXML = Compare-Object $xbase $obase -PassThru
$onlyXML
data
data3

Now the $onlyXML collection contains basenames for files that do not have a counterpart in the non-XML collection. Processing it is easy enough, just remember to add .xml to access the actual file.

$onlyXML | % {
    $x = gci "$_.xml" # For example, get a FileInfo about XML doc
    # TODO: do stuff with $x
}
vonPryz
  • 22,996
  • 7
  • 54
  • 65