【问题标题】:Move-Item not reading the path correctly移动项目未正确读取路径
【发布时间】:2014-07-29 03:48:01
【问题描述】:

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

$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

【问题讨论】:

    标签: powershell powershell-2.0 windows-server-2008-r2


    【解决方案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
    }
    

    【讨论】:

    • 完整路径?我目前没有使用像 C:\DDS\Server\LOGS 这样的完整路径?
    • 您可以这样做,但仅当您使用 Get-ChildItem 搜索项目时。为了更清楚,我编辑了我的答案。
    猜你喜欢
    • 2020-07-05
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    相关资源
    最近更新 更多