I'm trying to copy a file in powershell and put a datestamp at the same time. This
$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
}
}
Returns
The given path's format is not supported.
The write-host returns
[01/11/2015 12:33:55] Uploaded Z:\Desktop\ System.Object[]
I attempted a number of typecasts (.ToString), none of them worked. Any hints?
You seem to be casting everything to array by using @(), which you don't need to do. What about this?
$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
}
}
I've added a format to the date so that there are no special characters, and used Join-Path to merge the paths. Get-ChildItem returns file objects, which have the name, fullname and basename properties that you can use.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.