HOWTO · PowerShell
PowerShell을 사용하여 파일 및 폴더 이동
PowerShell로 경로를 확인하고 파일과 폴더를 만든 뒤 이동하는 방법을 알아봅니다.
이 페이지의 내용
PowerShell의 Move-Item cmdlet을 사용하면 파일이나 폴더를 상위 디렉터리 또는 다른 위치로 옮길 수 있습니다. 안정적으로 이동하려면 Test-Path로 경로를 확인하고, 대상 위치가 없으면 New-Item으로 만든 다음 항목을 이동하세요. 이 절차는 선택한 파일 여러 개를 옮기는 작업에도 응용할 수 있습니다. (Test-Path; New-Item)
PowerShell로 파일 또는 폴더가 있는지 확인하기
Test-Path는 지정한 경로에 파일이나 디렉터리가 있으면 $true를 반환하고, 없으면 $false를 반환합니다. 예시 경로를 확인하려는 파일이나 폴더의 경로로 바꾸세요. 다음 예제는 자체적으로 실행할 수 있도록 먼저 샘플 파일을 만든 뒤 파일이 있는지 확인합니다.
$sampleDir = Join-Path ([System.IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString())
New-Item -ItemType Directory -Path $sampleDir | Out-Null
$sampleFile = Join-Path $sampleDir 'test.txt'
New-Item -ItemType File -Path $sampleFile | Out-Null
Test-Path -Path $sampleFile
PowerShell로 파일과 폴더 만들기
New-Item에 -ItemType Directory를 지정하면 폴더를 만들고, -ItemType File을 지정하면 파일을 만듭니다. -Path에는 새 항목의 이름까지 포함한 전체 경로를 지정합니다. 다음 예제는 임시 디렉터리 안에 폴더와 파일을 각각 만듭니다.
$sampleDir = Join-Path ([System.IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString())
New-Item -ItemType Directory -Path $sampleDir | Out-Null
$folderPath = Join-Path $sampleDir 'PS'
New-Item -ItemType Directory -Path $folderPath | Out-Null
$filePath = Join-Path $folderPath 'TestFile.txt'
New-Item -ItemType File -Path $filePath | Out-Null
Test-Path -Path $filePath
PowerShell로 파일과 폴더 이동하기
Move-Item은 -Path에 지정한 경로의 파일이나 폴더를 -Destination에 지정한 위치로 옮깁니다. 대상 위치로 상위 디렉터리를 뜻하는 ..이나 다른 폴더를 지정할 수 있습니다. 대상 위치는 미리 존재해야 합니다. Move-Item은 없는 대상 위치를 만들지 않습니다. 다음 예제는 자체적으로 실행할 수 있도록 파일과 폴더를 만든 뒤, 파일을 상위 디렉터리로 옮깁니다. 이어서 사용자 지정 대상 위치가 없으면 만들고 폴더를 그곳으로 이동합니다. 경로 확인 결과는 불리언 값으로 출력됩니다.
$root = Join-Path ([System.IO.Path]::GetTempPath()) ([guid]::NewGuid().ToString())
$sourceDir = Join-Path $root 'Source'
New-Item -ItemType Directory -Path $sourceDir | Out-Null
$filePath = Join-Path $sourceDir 'TestFile.txt'
New-Item -ItemType File -Path $filePath | Out-Null
$folderPath = Join-Path $sourceDir 'PSScripts'
New-Item -ItemType Directory -Path $folderPath | Out-Null
Push-Location $sourceDir
Move-Item -Path 'TestFile.txt' -Destination '..'
Pop-Location
Test-Path -Path (Join-Path $root 'TestFile.txt')
$destination = Join-Path $root 'Archive'
if (-not (Test-Path -Path $destination)) {
New-Item -ItemType Directory -Path $destination | Out-Null
}
Move-Item -Path $folderPath -Destination $destination
Test-Path -Path (Join-Path $destination 'PSScripts')