如何根据PowerShell中的用户输入将文件移动到其他文件夹

时间:2016-04-07 09:46:38

标签: powershell

HI我正在尝试为我的powershell练习编写脚本,根据用户输入将文件从一个文件夹移动到另一个文件夹。该脚本工作正常但仅当文件存在于与脚本相同的文件夹中时。有人可以帮助我,我做错了什么或尝试帮助逻辑

$destination = 'P:\Powershell practice\Movefolder'
$ListFile = "P:\Powershell practice\" 
get-childitem $ListFile
$Filename = Read-host -prompt "Please Enter File to be moved"
$FileExists =  test-path $Filename

If ($FileExists -eq $True) {
move-item $Filename $destination
Write-Host "File is moved to $destination "
}
else
{write-host "No File Found"}

2 个答案:

答案 0 :(得分:0)

您需要确定完整的文件路径,否则测试路径会检查文件是否存在于当前位置。您可以使用Join-Path cmdlet加入通行证:

$FilePath = Join-Path $ListFile $FileName
$FileExists =  test-path $FilePath 

If ($FileExists -eq $True) {
move-item $FilePath $destination
...

<强> Offtopic: 您还可以使用网格视图,用户可以在其中选择多个文件,然后按下底部的确定按钮复制文件; - ):

$destination = 'P:\Powershell practice\Movefolder'
$ListFile = 'P:\Powershell practice\' 

$filesToMove = get-childitem $ListFile | Out-GridView -OutputMode Multiple
$filesToMove | % { move-item $_.FullName $destination}

答案 1 :(得分:0)

Incase if someone needs. Below is the correct working script for this

$destination = 'P:\Powershell practice\Movefolder'
$ListFile = 'P:\Powershell practice\' 
get-childitem $ListFile
$Filename = Read-host -prompt "Please Enter File to be moved"
$FilePath = Join-Path $ListFile $FileName
$FileExists =  test-path $FilePath 

If ($FileExists -eq $True) {
move-item $FilePath $destination
Write-Host "File is moved to $destination "
}
else
{write-host "No File Found"}