powershell - 祖父母文件夹名称到文件名
问题描述
我有一个脚本在我指定 c:\script\19\ 的确切目录时运行所有文件的前面。我如何让它查看它正在重命名的文件的祖父母并附加它?它是如何工作的一个例子是这样的文件:
c:\script\18\00000001\Plans.txt
c:\script\19\00001234\Plans.txt
c:\script\17\00005678\App.txt
但是我的脚本正在重命名这样的文件
c:\script\18\00000001\19-0001 Plans.txt
c:\script\19\00001234\19-1234 Plans.txt
c:\script\17\00005678\19-5678 App.txt
我的脚本是这样的:
$filepath = Get-ChildItem "C:script\" -Recurse |
ForEach-Object {
$parent = $_.Parent
$grandparent = $_.fullname | Split-Path -Parent | Split-Path -Parent | Split-Path -Leaf
}
Get-ChildItem "C:\Script\" –recurse –file |
Where-Object {$_.Name –notmatch ‘[0-9][0-9]-[0-9]’} |
rename-item -NewName {$grandparent + '-' + $_.Directory.Name.SubString($_.Directory.Name.length -4, 4) + ' ' + $_.Name}
解决方案
最简单的解决方案是将字符串拆分与-split
运算符与延迟绑定脚本块(您已尝试使用)结合起来:
Get-ChildItem C:\Script –Recurse –File -Exclude [0-9][0-9]-[0-9]* |
Rename-Item -NewName {
# Split the full path into its components.
$names = $_.FullName -split '\\'
# Compose the new file name from the relevant components and output it.
'{0}-{1} {2}' -f $names[-3], $names[-2].Substring($names[-2].Length-4), $_.Name
} -WhatIf
-WhatIf
预览重命名操作;删除它以执行实际重命名。
请注意如何-Exclude
直接与通配符表达式一起使用Get-ChildItem
以排除已经具有目标名称格式的文件。
您的原始文件不起作用的主要原因是您计算了单个、静态
$parent
和$grandparent
值,而不是从每个输入路径派生输入路径特定的值。
此外,您的$grandparent
计算是不必要的复杂;Gert Jan Kraaijeveld 的有用答案显示了一种更简单的方法。
推荐阅读
- python-3.x - 使用 pytest-asyncio 和 aiohttp 时“忽略异常:RuntimeError:事件循环已关闭”
- android - 如何级联 ValueEventListeners 以从 firebase 实时数据库访问两个不同的节点
- php - 插入数据库时参数无效
- javascript - TypeError:无法解构“orderPay”的属性“加载”,因为它未定义
- javascript - 离子 - 将结果放入 textarea
- vue.js - 无法在 Ionic-vue 5.5.2 中关闭模式
- python - python中对不同长度数组的中值测试
- javascript - 在 reactjs 中显示数据库中的日期时出错
- python - 如何在绘图饼图中将所有值设置为水平?
- php - 为什么我的关联数组被转换为对象 PHP?