简体   繁体   中英

How to properly use -Exclude in Remove-Item for a list of string from a variable in Powershell?

I have a variable that stored the list of files to be removed in this format:

$list = """" + "file1.txt" + """"

and a complete $list would be looking something like this:

$list
"file1.txt","file2.txt","file3.txt",...

and trying to use Remove-Item with the variable failed, it removed all the files:

Remove-Item -Recurse -Path "c:\myfiles\*" -Exclude $list

How to properly achieve this? Thanks in advance!

You're close but $list needs to be an array not a string (with excess quotes).

Just quote each element, and separate them with a comma to do this:

$list = "file1.txt","file2.txt"

Remove-Item -Path "c:\myfiles\*" -Recurse -Exclude $list -WhatIf

I would also recommend reading about_quoting_rules as it seems you don't know that double and single quotes do different things.

Using single quotes instead:

$list = """" + "file1.txt" + """"

can be expressed as:

$list = '"file1.txt"'

(These extra quotes aren't needed for the code above)

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