I have folders in"Directory1" and zip of these folders in "Directory2" with the mention "_OK" at the end of the zip name.
Directory1 : 1B002955_SML 23_LEAP 1A version2 mars2022_2022-03-11T08h00m40s_s603575
Directory2 : 1B002955_SML 23_LEAP 1A version2 mars2022_2022-03-11T08h00m40s_s603575_OK
Now i want to delete the folders from the 1st directory if the corresponding zip exists in the 2nd directory. The two directory aren't on the same server.
I thought about renaming Directory2 zip by removing "_OK"
rename-item $_ $_.Name.Replace("_OK", "")
Then compare Directory1 and Directory2 with the compare-object cmdlet but I found that it's for comparing the specified properties and in my case I just want to compare names
Still new to powershell, i'm not sure the best way to proceed
Hope someone can help
Thank you
CodePudding user response:
Use the Compare-Object
cmdlet as follows, assuming that:
$filesA
contains theSystem.IO.DirectoryInfo
instances representing the folders to potentially delete,and
$fileeB
theSystem.IO.FileInfo
instances representing the corresponding ZIP files,
as output by Get-ChildItem
calls:
Compare-Object -IncludeEqual -PassThru $filesA $filesB -Property {
$_.BaseName -replace '_OK$'
} | Where-Object SideIndicator -eq == |
Remove-Item -Recurse -Force -WhatIf
Note: The -WhatIf
common parameter in the command above previews the operation. Remove -WhatIf
once you're sure the operation will do what you want.
-IncludeEqual
makesCompare-Object
also include objects that compare the same (by default, only differing objects are reported).-PassThru
causes the LHS input object from a pair of matching objects to be output (by default, only the matching property value - as defined by the-Property
argument(s) - is output.)-Property { $_.BaseName -replace '_OK$' }
uses a nameless calculated property to compare pairs of input objects by; in this case, the-replace
operator is used to effectively remove string_OK
, if present at the end ($
), from the base file name (the file name without extension).Where-Object
SideIndicator -eq ==
limits the output to objects that compare equal, using simplified syntax.Adding
-Recurse
to theRemove-Item
ensures that no confirmation prompt is shown if the target directory is non-empty;-Force
ensures that removal succeeds even if the target directory is hidden or contains hidden items.