【问题标题】:Copy files to backup location and rename using Lastwritetime使用 Lastwritetime 将文件复制到备份位置并重命名
【发布时间】:2017-12-20 19:30:59
【问题描述】:

我正在尝试编写一个脚本,将文件从原始位置复制到备份位置。复制到备份位置后,我希望将文件重命名为在名称中包含 lastwritetime。

例如:\\server1\C$\Logs\Logfile-1.txt(上次写入时间为 2017 年 12 月 20 日星期三上午 5:00:27)复制到 \\backupserver\c$\LogBackups\Server1Logfile20171220050027.txt

生成日志文件的程序会在它们达到一定大小时使用 -1、-2、-3 等对其进行迭代。

我有一个包含以下信息的 csv

OldFilePath,NewFilePath,NewFileName
\\server1\c$\Log\LogFile-*.txt,\\backupserver\c$\LogBackups\,Server1LogFile
\\server2\c$\Log\LogFile-*.txt,\\backupserver\c$\LogBackups\,Server2LogFile
\\server3\c$\Log\LogFile-*.txt,\\backupserver\c$\LogBackups\,Server3LogFile

这是我目前得到的脚本。

import-csv \\backupserver\c$\scripts\test.csv | foreach-object {
$FilePath = $_.OldFilePath
$NewFilePath = $_.NewFilePath
$NewFileName = $_.NewFileName

copy-item -path $_.OldFilePath -Destination "$NewFilePath$NewFileName$LastWriteTime.txt"
}

我尝试了以下命令来设置 $LastWriteTime 变量,但到目前为止,还无法正确格式化输出。

$LastWriteTime = Get-ItemPropertyValue -path \\server1\C$\Logfile-1.txt -name LastWriteTime | 
Format-list Year,Month,Day,Hour,Minute,Second

&

$LastWriteTime = Get-ChildItem $OldFilePath | select LastWriteTime

任何帮助我指出正确的方向将不胜感激!

【问题讨论】:

    标签: powershell


    【解决方案1】:

    假设你有一个 DateTime $dt,你可以像这样格式化它:

    $dt = [DateTime]::Parse((get-item D:\temp\grinder.jpg).LastWriteTime)
    $fmt = "{0:N4}{0:N2}{0:N2}{0:N2}{0:N2}{0:N2}" -f $dt.Year, $dt.Month, $dt.Day, $dt.Hour, $dt.Minute, $dt.Second
    

    这给出了:

    20171220110535
    

    Wednesday, December 20, 2017 11:05:35 AM
    

    由此,您应该能够在其余代码上取得进展。

    【讨论】:

    • 非常感谢。这正是我所需要的!
    猜你喜欢
    • 1970-01-01
    • 2012-04-19
    • 2020-01-09
    • 2021-03-12
    • 2011-07-20
    • 1970-01-01
    • 1970-01-01
    • 2018-11-29
    • 1970-01-01
    相关资源
    最近更新 更多