Move-Item无法正确读取路径

时间:2014-06-08 12:26:14

标签: powershell powershell-v2.0 windows-server-2008-r2

我有这个脚本,我想将文件从一个路径移动到另一个路径:

$logArchieveDirectory='C:\LogArchieve\'+$archiveTillDate.Day+$archiveTillDate.Month+$archiveTillDate.Year;
$sourcePathServer = 'C:\DDS\Server\LOGS';
$destPathServer=$logArchieveDirectory+'\Server';

#Create Directories
New-Item -ItemType directory -Path $logArchieveDirectory;
New-Item -ItemType directory -Path $destPathServer;

#Moving Logs to new temporary log archieve directories
foreach( $item in (Get-ChildItem $sourcePathServer | Where-Object { $_.CreationTime -le $archiveTillDate }) )
{
    Move-Item $item $destPathServer -force;
}

但是,我已指定两个路径都很好但是当我运行此脚本时我不断收到此错误。

Move-Item : Cannot find path 'C:\DDS\WorkFolder\WebAdapter' because it does not exist.
At C:\DDS\WorkFolder\powerShellScript08062014.ps1:38 char:11
+     Move-Item <<<<  $item $destPathController;
    + CategoryInfo          : ObjectNotFound: (C:\DDS\WorkFolder\WebAdapter:String) [Move-Item], ItemNotFoundException
    + FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.MoveItemCommand

C:\DDS\WorkFolder\实际上是我的脚本文件所在的文件夹。但我不理解的是为什么它在这里寻找文件夹,而不是在哪里给出路径,即$sourcePathServer

1 个答案:

答案 0 :(得分:1)

您的脚本将相对路径传递给Move-Item,它默认为工作目录。一个简单的解决方案是使用.FullName属性传递绝对路径:

foreach ($item in (Get-ChildItem $sourcePathServer `
| Where-Object { $_.CreationTime -le $archiveTillDate })) {
    Move-Item $item.FullName $destPathServer -force
}

由于所有括号,将foreach与管道结合使用看起来并不是很优雅。你可以摆脱它:

Get-ChildItem $sourcePathServer `
| Where-Object { $_.CreationTime -le $archiveTillDate } | Foreach-Object {
    Move-Item $_.FullName $destPathServer -Force
}
相关问题