본문 바로가기
파워쉘(Powershell)/파일,폴더

파워쉘 - 파일 이름 변경 및 지우기

by 예배파 2024. 4. 2.

 

파일 이름 변경

 

Rename-Item 

 

사용방법

Rename-Item -Path 파일명 -NewName 바뀔 파일 이름

#스크립트를 실행하는 폴더에 파일이 있는 경우만 실행됨
Rename-Item -Path .\Email_Old.txt -NewName .\Email_New.txt


#스크립트의 위치에 상관없이 실행
Rename-Item -Path "C:\Files\Email_Old.txt" -NewName "C:\Files\Email_New.txt"

 

 

 

변경할 파일 이름이 존재하는 경우는 에러가 발생

 

이런 경우는 Move-Item을 사용해서 파일 이름을 변경하면 됩니다   

#-Force를 사용해서 파일이 Read-only나 hidden같은 파일이라도 강제로 이름변경

Move-Item -Path "C:\Files\Email_Old.txt" -Destination "C:\Files\Email_New.txt" -Force

 

 

 

여러파일을 한 번에 이름 변경

파일의 이름 앞에 오늘 년월일 정보를 붙여서 파일들 이름 변경  

$Files = Get-ChildItem -Path "C:\Files\*.txt"
$today = Get-Date -format "yyyy-MM-dd"
ForEach($file in $Files){
    $newName = "{0}_{1}" -f $today, $file.Name
    Rename-Item $file -NewName $newName
}


원래 파일 리스트
File_1.txt
File_2.txt
File_3.txt

실행결과
2024-04-05_File_1.txt
2024-04-05_File_2.txt
2024-04-05_File_3.txt

 

 

 

파일 지우기

 

Remove-Item

 

파일 하나 지우기

#파일의 절대 경로 사용
Remove-Item -Path "C:\Files\File_1.txt"

#파워쉘 콘솔에서 지금 현재 폴더의 위치가 C:\Files 인 경우
Remove-Item -Path .\File_1.txt

 

 

 

폴더 내 모든 파일 지우기

Remove-Item C:\Files\*.*

 

 

 

특정폴더와 하위폴더의 모든 파일들 지우기

Get-ChildItem -Path "C:\Files" -File -Recurse | Remove-Item

 

 

 

몇 개의 폴더들 파일 지우기    

$Folders = "C:\Files", "C:\Logs"
 
ForEach ($folder in $Folders) {
     Get-ChildItem -Path $folder -File -Recurse | Remove-Item -Force
}

 

'파워쉘(Powershell) > 파일,폴더' 카테고리의 다른 글

파워쉘-엑셀파일 읽기  (0) 2024.04.22
파워쉘 - 엑셀(Excel)에 쓰기  (2) 2024.04.19
파워쉘 - 파일 생성, 읽기, 쓰기  (0) 2024.04.04
파일, 폴더 목록  (0) 2024.03.07