HOWTO · PowerShell
PowerShell を使用したファイルとフォルダーの移動
PowerShell でパスの存在を確認し、ファイルやフォルダーを作成して移動する方法を説明します。
このページの内容
PowerShell の Move-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 は、存在しない移動先を作成しません。次の自己完結型の例では、ファイルとフォルダーを作成し、ファイルを親ディレクトリへ移動します。続いて、必要に応じて指定先のフォルダーを作成してから、フォルダーをそこへ移動します。パスの確認結果は Boolean 値として表示されます。
$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')