2015-01-11 60 views
0

我試圖在PowerShell中複製一個文件,並同時放置一個datestamp。這如何在Powershell中正確使用變量作爲Copy-Item的目標參數?

$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

Windows上的文件名不能包含斜槓或冒號。試試不包含那些日期格式? –

+0

謝謝,這是一個愚蠢的開始 – jamesson

回答

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返回文件對象,它們具有可以使用的名稱,全名和基本名稱屬性。

相關問題