1

我想将一个文件移动到另一个文件夹,变成两个文件名不同的文件,其中包含日期时间、前缀和特定字符。然后在完成后删除原始文件。

例如,我有c:\source\aaa.pdf并且希望它被复制到

  • c:\destination\12345_TPE_aaa_20180614151500.pdf
  • c:\destination\12345_TXG_aaa_20180614151500.pdf
  • 然后删除c:\source\aaa.pdf.

现在我什至只更改文件名,我试过了

Get-ChildItem *.pdf | rename-item -newname ('12345'+'_TPE'+$_.Name+'_'+(Get-Date -f yyyymmddhhmmss)+'.pdf') 

但不包括原始名称。

请问有高手可以帮忙吗?

4

4 回答 4

2

实际上,这是一个相当简单的修复:$_仅存在于作为 cmdlet 参数的脚本块中。您一直在使用普通括号,它们不是脚本块。只需将其更改如下:

Get-ChildItem *.pdf | rename-item -newname {'12345'+'_TPE'+$_.Basename+'_'+(Get-Date -f yyyyMMddhHHmmss)+'.pdf'}

(此外,您的日期格式字符串是可疑的,因为您在那里包含分钟而不是月份;我已经解决了这个问题。)

或者,作为使用单个格式字符串的更容易阅读的替代方案,也许:

Get-ChildItem *.pdf |
  Rename-Item -NewName { '{0}_TPE_{1}_{2:yyyyMMddHHmmss}.pdf' -f 12345,$_.Basename,(Get-Date) }
于 2018-06-14T07:44:44.547 回答
0

您可以遍历Get-ChildItem使用ForEach-Object.

然后将该文件作为新名称复制到每个目标。这样可以节省复制然后重命名文件。

然后最后从源中删除原始文件。

$source = "c:\source"
$destination = "C:\destination"

Get-ChildItem -Path $source -Filter *.txt | ForEach-Object {
    $date = Get-Date -Format yyyyMMddhHHmmss
    Copy-Item -Path $_ -Destination "$destination\12345_TPE_$($_.Basename)_$date.pdf"
    Copy-Item -Path $_ -Destination "$destination\12345_TXG_$($_.Basename)_$date.pdf"
    Remove-Item -Path $_
}
于 2018-06-14T10:07:31.970 回答
0

我喜欢 Joey 采用模块化的方式,在此基础上进行扩展

## Q:\Test\2018\06\14\SO_50852052.ps1
$Src = 'C:\Source'
$Dst = 'c:\destination'
$Prefix = '12345'
$Types = 'TPE','TPG'

Get-ChildItem -Path $Src *.pdf | ForEach-Object {
    ForEach ($Type in $Types){
        $_ | Copy-Item -Destination (Join-Path $Dst (
        "{0}_{1}_{2}_{3:yyyyMMddHHmmss}.pdf" -f $Prefix,$Type,$_.Basename,(Get-Date)))
    }
    $_ | Remove-Item 
}
于 2018-06-14T10:31:43.353 回答
0

这是您问题的另一部分-

$source = "C:\Source"
$dest = "C:\Destination"
$files = Get-ChildItem *.pdf 
foreach($file in $files)
{
    $filename1 = '12345'+'_TPE_'+$file.Basename+'_'+(Get-Date -f yyyymmddhhmmss)+'.pdf'
    $filename2 = '12345'+'_TXG_'+$file.Basename+'_'+(Get-Date -f yyyymmddhhmmss)+'.pdf'
    Copy-Item $file.FullName -Destination $dest -PassThru | Rename-Item -NewName $filename1
    Copy-Item $file.FullName -Destination $dest -PassThru | Rename-Item -NewName $filename2
    Remove-Item $file.FullName -Force
}

可以用连续的管道把它做得更小,但现在的更容易理解,看起来更干净。

于 2018-06-14T10:02:41.760 回答