简体   繁体   中英

Unable to delete files from the list using Remove-Item in PowerShell

I am trying to delete a list of files which is stored as InputObject names from a variable, '$exclude_files', using Remove-Item cmdlet.

Since it is a list, I am iterating through the list and getting the InputObject file names.

Below is the code:

$source_dir ="C:\Files"

#Files are in below variable $exclude_files

$exclude_files

InputObject      SideIndicator
-----------      -------------
Credentials.xml  =>
EC2_Ubuntu.pem   =>
file2.png        =>
file3.txt        =>
Terminals.config =>

# tried with giving path and without giving path
foreach ($i in $exclude_files){ Remove-Item -Path $source_dir  $i.InputObject }

But, I am getting the following error:

Remove-Item : Cannot find path 'C:\\Files\\file3.txt' because it does not exist. At line:1 char:31 + foreach($i in $exclude_files){Remove-Item $i.InputObject} + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (C:\\Files...file3.txt:String) [Remove-Item], ItemNotFoundException + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand

Try the following:

$exclude_files.InputObject | Remove-Item -Path {Join-Path $source_dir $_ }

It seems that $i.InputObject is used as input for the -Filter parameter (since this is the first positional parameter in the Path parameter set), which might not be the intended idea.

i got the solution for that.. as you suggested, when iterate through the list with the InputObject, its working

foreach($i in $exclude_files)
            {
                $i.InputObject | Remove-Item -Path {Join-Path $source_dir $_}
    }

Thank You

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM