Reputation: 2871
I just started playing around with powershell so execuse my newbie mistakes. I am searching for a file and I'm storing the path of the file in a variable, then I want to check if in that path there are specific files and then delete them. I cant find much help on this stuff, I think there is a problem in the if statement but I cant figure it out.
Here's the code:
$startDirectory = ".\somepath\"
$FindFileXml = Get-Childitem $startDirectory
$StorePaths = Get-Childitem $FindFileXml -include "file.xml" -recurse
if($StorePaths -eq "somefile.cs" -and "diffrentfile.cs")
{
Remove-Item "somefile.cs"
Remove-Item "diffrentfile.cs"
}
else{
Write-host "file not found!"
}
UPDATE:
$StorePaths = Get-Childitem $FindFilterXml-Filter "file.xml" -recurse
$StorePaths | Select-Object -ExpandProperty Directory
| Get-ChildItem |
Where-Object {($_.Name -eq 'GeneratedCode.cs') -or ($_.Name -eq 'TypedEnums.cs')}
| Remove-Item
will this store the path of File.xml in $StorePaths ? if so how can i copy it e.g Copy-Item $StorePath.name .\somepath?
Upvotes: 1
Views: 237
Reputation: 59031
You don't need a if statement here. Just filter your result for the files you want to delete and pipe them to the Remove-Item
cmdlet:
$StorePaths |
Where-Object {($_.Name -eq 'somefile.cs') -or ($_.Name -eq 'diffrentfile.cs')} |
Remove-Item
Update: This example only deletes the files in the directory where a file.xml is present:
Get-Childitem $FindFileXml -Filter "file.xml" -recurse |
Select-Object -ExpandProperty Directory |
Get-ChildItem |
Where-Object {($_.Name -eq 'somefile.cs') -or ($_.Name -eq 'diffrentfile.cs')} |
Remove-Item
Upvotes: 4