我想将.rpt文件从dr_network重命名为dr_network_10yr。然后创建文件夹Output(如果它不存在)并将文件移动到该文件夹。
但是文件的重命名无法移动文件。请注意,文件应该是相对路径。
感谢您的协助。
New-Item .\Output -force
Get-ChildItem *.rpt |
ForEach-Object{
Rename-Item $_ ($_.Name -replace 'dr_network_','dr_network_10yr')
Move-Item $_($_.Fullname -destination ".\Output")
}
答案 0 :(得分:4)
您的示例因多种原因无效。您需要在New-Item
上指定类型New-Item .\Output -force -ItemType Directory
然后获取所有* .rpt文件并遍历它们。重命名语法是正确的,但您在移动语法方面存在问题。 Powershell不知道你想做什么。您还要重命名文件,然后尝试移动已重命名的文件,该文件不再存在。以下内容应该有所帮助:
#Tell powershell its a directory
New-Item .\Output -force -ItemType Directory
Get-ChildItem *.rpt |
ForEach-Object{
#store the new name as a variable
$newName = $_.FullName -replace 'dr_network_','dr_network_10yr'
#rename the file
Rename-Item $_ $newName
#move the newly renamed file to the Output folder
Move-Item $newName -destination ".\Output"
}
答案 1 :(得分:0)
我跟随你的另一篇文章,这有助于理解你想要做的帽子:
cmd insert text into the middle of the file name
我修改了我的代码以执行您希望的操作。它只移动并使用" modelname"重命名rpt文件。或者" dr network"在开始。你可以改变你的想法。
它还允许您指定SourceDir,或者您可以将值保留为"。"相对路径。
# Rename using replace to insert text in the middle of the name
# Set directory where the files you want to rename reside
# This will allow you to run the script from outside the source directory
Set-Variable -Name sourcedir -Value "."
# Set folder and rename variables
Set-Variable -Name modelname -Value "dr network_"
Set-Variable -Name id -Value "10yr_"
# Set new filename which is modelname string + id variable
Set-Variable -Name newmodelname -Value $modelname$id
# Check if folder exisits, if not create
if(!(Test-Path -Path $sourcedir\$modelname )){
# rem make directoy with modelname variable
New-Item -ItemType directory -Path $sourcedir\$modelname
}
# Move the rpt files to new dir created
Move-Item -Path $sourcedir\$modelname*.rpt -Destination $sourcedir\$modelname
# Using GetChildItem (i.e. Dir in dos) command with the pipe, will send a list of files to the Rename-Item command
# The Rename-Item command is replacing the modelname string with new modelname string defined at the start
Get-ChildItem -Path $sourcedir\$modelname | Rename-Item -NewName { $_.name -replace $modelname, $newmodelname }
# You can remove the stuff below this line -----
# Pause here so you can check the result.
# List renamed files in their new directory
Get-ChildItem -Path $sourcedir\$modelname
# rem Pause
Write-Host "Press any key"
$pause = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
# rem End ------
希望你能让它发挥作用。