Art*_*hur 6 powershell scripting
这里是新手。我正在尝试编写一个 PowerShell 脚本来:
仅获取所有 .pdf 文件
重命名它们 - 文件名很长 - 超过 30 个字符 - 它们包含我需要提取的 2 个数字 - 示例:
Microsoft Dynamics NAV 2018 累积更新 11(内部版本 25480).pdf -> 结果 : = 18CU11.pdf
我尝试了很多网站的示例,但似乎无法成功循环。要么收到错误 - 该路径不存在,要么无法重命名文件,因为不知何故循环获取文件路径并且我无法重命名
Get-ChildItem "C:\Users\******\Desktop\PowerShell Practice" -Filter *.pdf | #create list of files
ForEach-Object{
$oldname = $_.FullName;
$newname = $_.FullName.Remove(0,17);
#$newname = $_.FullName.Insert(0,"CU")
Rename-Item $oldname $newname;
$oldname;
$newname; #for testing
}
Run Code Online (Sandbox Code Playgroud)
这只是最新的尝试,但任何其他方法都可以——只要它能完成工作。
试试这个逻辑:
[string]$rootPathForFiles = Join-Path -Path $env:USERPROFILE -ChildPath 'Desktop\PowerShell Practice'
[string[]]$listOfFilesToRename = Get-ChildItem -Path $rootPathForFiles -Filter '*.PDF' | Select-Object -ExpandProperty FullName
$listOfFilesToRename | ForEach-Object {
#get the filename wihtout the directory
[string]$newName = Split-Path -Path $_ -Leaf
#use regex replace to apply the new format
$newName = $newName -replace '^Cumulative Update (\d+) .*NAV 20(\d+).*$', '$2CU$1.pdf' # Assumes a certain format; if the update doesn't match this expectation the original filename is maintained
#Perform the rename
Write-Verbose "Renaming '$_' to '$newName'" -Verbose #added the verbose switch here so you'll see the output without worrying about the verbose preference
Rename-Item -Path $_ -NewName $newName
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14712 次 |
| 最近记录: |