![Powershell - 파일 일괄 삭제 일부 문자열이 포함되어 있습니까?](https://rvso.com/image/1654379/Powershell%20-%20%ED%8C%8C%EC%9D%BC%20%EC%9D%BC%EA%B4%84%20%EC%82%AD%EC%A0%9C%20%EC%9D%BC%EB%B6%80%20%EB%AC%B8%EC%9E%90%EC%97%B4%EC%9D%B4%20%ED%8F%AC%ED%95%A8%EB%90%98%EC%96%B4%20%EC%9E%88%EC%8A%B5%EB%8B%88%EA%B9%8C%3F.png)
PS C:\RetroArch-Win64\_ROMS\nointro.n64> foreach ($file in (get-childitem $ParentFolder)){
>> write-verbose "($file.name)" -Verbose
>> if ((get-content $file.name) -match '(Beta)'){
>> write-verbose "found the string, deleting" -Verbose
>> remove-item $file.name -force -WhatIf
>> }else{ write-verbose "Didnt match" -Verbose
>> }
>>
>> }
VERBOSE: (007 - The World Is Not Enough (Europe) (En,Fr,De).7z.name)
VERBOSE: Didnt match
VERBOSE: (007 - The World Is Not Enough (USA) (v2) (Beta).7z.name)
VERBOSE: Didnt match
VERBOSE: (007 - The World Is Not Enough (USA) (v21) (Beta).7z.name)
VERBOSE: Didnt match
VERBOSE: (007 - The World Is Not Enough (USA).7z.name)
PS C:\RetroArch-Win64\_ROMS\nointro.n64>
이름에 '(Beta)' 문자열이 포함된 모든 파일을 일괄 삭제하려고 합니다. 위에 붙여넣은 출력은 제가 작성한 코드와 출력을 보여줍니다. 보시다시피 이름에 해당 문자열이 포함되어 있어도 문자열과 '일치하지 않았습니다'.
나는 초보이고 문서를 이해하려고 노력하고 있지만 내가 읽은 모든 곳에서 -contains가 아닌 -match를 사용해야 합니다.
어떤 도움이라도 대단히 감사하겠습니다.
답변1
문자열이 포함된 파일 이름을 일치시키려는 경우에는 (Beta)
를 사용하면 안 됩니다 Get-Content
. 를 사용하면 Get-Content
파일을 열고 해당 내용/값에서 (Beta)
실패한 단어를 찾습니다.
파일 이름만 테스트해야 합니다. 귀하의 코드는 다음과 같아야 합니다:
ForEach ($file in (Get-ChildItem $ParentFolder)){
Write-Verbose "($file.name)" -Verbose
if ($file.Name -Match '(Beta)'){
Write-Verbose "found the string, deleting" -Verbose
Remove-Item $file.Name -WhatIf
}else{ Write-Verbose "Didnt match" -Verbose}
}
답변2
허용된 답변이 작동하고 코드를 수정하는 동안 쉘에서도 직접 사용하기 매우 쉬운 솔루션을 보여드리고 싶습니다.
Get-ChildItem $ParentFolder | Where-Object { $_.Name -like '*(Beta)*' } | Remove-Item -force
또는 짧게 말하면:
gci $ParentFolder | ? Name -like '*(Beta)*' | del -Force
실제로 매개변수가 Get-ChildItem
있으므로 더 짧게 만들 수 있습니다.-Filter
gci $ParentFolder -Filter '*(Beta)*' | del -force
또는 가능한 한 가장 짧게 만들려면 Remove-Item
필터가 있으므로 간단히 다음을 수행할 수 있습니다.
del $ParentPath\*(Beta)* -Force
PowerShell의 모든 항목은 개체이므로 또는 해당 별칭을 Get-ChildItem
사용하여 반환하는 개체(또는 다른 cmdlet)를 간단히 필터링할 수 있습니다 .Where-Object
?
이 경우에는 매개변수 가 있으므로 Get-ChildItem
별도 의 작업 없이도 원하는 객체를 얻을 수도 있습니다.Remove-Item
-filter
Where-Object