如何在Powershell中正确使用变量作为Copy-Item的目标参数?

时间:2015-01-11 17:39:25

标签: string powershell casting

我正在尝试在powershell中复制文件并同时放置一个日期戳。此

 $localfiles = @(Get-ChildItem -File $PSScriptRoot)
  Foreach ($i in $localfiles)
    {
        $date = Get-Date
        #write-host $i
        if (!(Test-Path @("Z:\Desktop\" + $i))) 
            {   
                Copy-Item $i "Z:\Desktop\"
                #Add-Content backuplog.txt "[" Get-Date "]" " initalized file " $i
                Write-Host "[$date] Uploaded Z:\Desktop\"$i
            } else {        
                $newpath = @("Z:\Desktop\[$date]" + "$i")
                Copy-Item $i -Destination "$newpath"
                #Write-Host "incremented $newname"
                #Add-Content backuplog.txt "[" Get-Date "]" " incremented file " $i
            } 
    }

返回

 The given path's format is not supported.

写主机返回

[01/11/2015 12:33:55] Uploaded Z:\Desktop\ System.Object[]

我尝试过多次类型转换(.ToString),但都没有。任何提示?

1 个答案:

答案 0 :(得分:1)

您似乎使用@()将所有内容都转换为数组,而您不需要这样做。那怎么样?

$localfiles = Get-ChildItem -File $PSScriptRoot
foreach ($i in $localfiles)
{
    $date = Get-Date -Format "yyyyMMddHHmmss"
    #write-host $i
    if (!(Test-Path (Join-Path "z:\Desktop" $i.Name))) 
    {   
        Copy-Item $i.FullName "z:\Desktop"
        #Add-Content backuplog.txt "[" Get-Date "]" " initialized file " $i
        Write-Host "[$date] Uploaded z:\Desktop\$($i.Name)"
    } else {        
        $newpath = Join-Path "z:\Desktop" "$date-$($i.Name)"
        Copy-Item $i.FullName $newpath
        #Write-Host "incremented $newname"
        #Add-Content backuplog.txt "[" Get-Date "]" " incremented file " $i
    } 
}

我在日期中添加了一种格式,以便没有特殊字符,并使用Join-Path来合并路径。 Get-ChildItem返回文件对象,它们具有您可以使用的名称,全名和基本名称属性。