powershell - Powershell重命名目录中的文件
问题描述
$ht = @{}
$o = new-object PSObject -property @{
from = "C:\Users\nicolae.calimanu\Documents\scripturi copiere\LAA"
to = "C:\Users\nicolae.calimanu\Documents\scripturi copiere\destinatie" }
$ht.Add($o.from, $o)
$o = new-object PSObject -property @{
from = "C:\Users\nicolae.calimanu\Documents\scripturi copiere\LBB"
to = "C:\Users\nicolae.calimanu\Documents\scripturi copiere\destinatie" }
$ht.Add($o.from, $o)
$o = new-object PSObject -property @{
from = "C:\Users\nicolae.calimanu\Documents\scripturi copiere\LCC"
to = "C:\Users\nicolae.calimanu\Documents\scripturi copiere\destinatie" }
$ht.Add($o.from, $o)
foreach($server in $ht.keys ) {
copy-item $ht.Item($server).from -destination $ht.Item($server).to -Recurse ;
}
# rename
##$destination = "C:\Users\nicolae.calimanu\Documents\scripturi copiere\destinatie"
#foreach($fisier in $destination) {
# Get-ChildItem $fisier |
# Rename-Item -NewName {$_.Basename + '_' + $_.CreationTime.Year + $_.CreationTime.Month + $_.CreationTime.Day + '_'+ $_.CreationTime.Hour + $_.CreationTime.Minute + $_.Extension }
#}
来自定义的 ht 的复制部分正在工作,现在在我复制文件夹和每个我想要添加到该文件夹中每个文件的日期和时间的内容之后,但不更改目标文件夹的名称。最后一部分仍然让我头疼,因为当我从源复制文件夹及其内容时,尝试重命名文件夹时也会重命名文件夹,我只想要文件夹的内容。例如,如果我有包含 50 个项目的文件夹 LAA,我希望只添加这 50 个项目,并将其重命名如下,并带有创建日期和时间。
解决方案
您可以在同一个循环中复制具有新名称的文件,如下所示:
foreach($server in $ht.keys ) {
# for clarity..
$source = $ht.Item($server).from
$destination = $ht.Item($server).to
Get-ChildItem -Path $source -File -Recurse | ForEach-Object {
# create the target path for the file
$targetPath = Join-Path -Path $destination -ChildPath $_.FullName.Substring($source.Length)
# test if this path exists already and if not, create it
if (!(Test-Path $target -PathType Container)) {
$null = New-Item -ItemType Directory -Path $targetPath
}
# create the new file name
$newName = '{0}_{1:yyyyMMdd_HHmm}{2}' -f $_.BaseName, $_.CreationTime, $_.Extension
$_ | Copy-Item -Destination (Join-Path -Path $targetPath -ChildPath $newName)
}
}
希望有帮助
推荐阅读
- javascript - XSLT if-clause with param check 进行排序
- vb.net - 将日期时间转换为字符串导致错误“从字符串“dd.MM.yyyy”到类型“整数”的转换无效。”
- python - 我想用python解析从html中读取典型数据
- sql-server - 在查询中重用别名
- java - java apache poi - xwpfparagraph 到字符串的转换
- angular - array.find 函数阻止访问父类 'this' 对象
- html - Visual Studio 2017 社区 - HTML&CSS 验证
- android - 如何事务替换选项卡中的片段
- python - Pandas 数据规范化给出了奇怪的输出 Python 3
- node.js - Node JS + Put 请求没有正文