首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PowerShell -通过文件循环并重命名

PowerShell -通过文件循环并重命名
EN

Stack Overflow用户
提问于 2018-11-13 08:34:26
回答 3查看 12.5K关注 0票数 5

新手来了。我正在尝试编写一个PowerShell脚本:

  1. 循环遍历目录中的所有文件
  2. 列表项目
  3. 只获取所有.pdf文件 重命名它们-文件名是长时间的30个字符-They包含两个数字,我需要提取-Example: MicrosoftDynamicsNAV2018 (Build 25480).pdf ->结果:=18 CU11.pdf

我尝试了许多网站的例子,但我似乎连成功的循环都没有。要么得到一个错误-路径不存在,要么不能重命名文件,因为循环得到一个文件,而我不能重命名

代码语言:javascript
复制
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
}

这只是最新的尝试,但是任何其他的方法都是可以的--只要它能完成任务。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-11-16 12:57:28

试试这个逻辑:

代码语言:javascript
复制
[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 
}
票数 3
EN

Stack Overflow用户

发布于 2018-11-13 11:18:11

查看重命名-项目的帮助。参数-NewName只需要文件的名称,而不是完整路径。

试试这个:

代码语言:javascript
复制
Get-ChildItem "C:\Users\******\Desktop\PowerShell Practice-Filter" -Filter *.pdf |  #create list of files

ForEach-Object{
    $oldname = $_.FullName
    $newname = $_.Name.Remove(0,17)

    Rename-Item -Path $oldname -NewName $newname

    $oldname
    $newname  #for testing
}
票数 3
EN

Stack Overflow用户

发布于 2018-11-13 09:13:13

请尝尝这个

代码语言:javascript
复制
Get-ChildItem -Path "C:\Users\******\Desktop\PowerShell Practice-Filter" -Filter *.pdf | Rename-Item -NewName $newname
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53276843

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档