powershell 重命名列表中的文件夹

agxfikkp  于 2023-01-30  发布在  Shell
关注(0)|答案(1)|浏览(134)

我有一个包含56个文件夹的文本文件列表,其中包括一组文件夹的完整路径。我需要重命名路径末尾的文件夹。示例:

Original: \this folder\needs to\move  
New: \this folder\needs to\move.moved

我对powershell完全陌生,正在努力学习。我想这可能是一个很好的开始方式。任何帮助都将非常感谢。

dxpyg8gm

dxpyg8gm1#

# Get the content of the list
# in this case, a text file with no heading, and one path per line
$listContent = Get-Content $ENV:USERPROFILE\Desktop\list.txt

# Loop over each child folder and rename it

foreach($line in $listContent)
{
    # check if the current path is valid

    $pathTest = Test-Path -Path $line

    if($pathTest -eq $True)
    {
        Write-Output "`nOld path: $($line)"
        $newName = $line + ".moved"

        Write-Output "New name: $newName"

        try 
        {
            # on success, write out message
            Rename-Item -Path $line -NewName $newName -Force

            # split the string from the file and get the data after the last \ for readability
            Write-Output "`nSuccessfully changed directory name $($line.split('\')[-1]) to $newName"
        }
        catch 
        {
            # on error, throw first error in the Error array
            throw $Error[0]
        }
    }
    else {
        Write-Output "$($line) is not a valid path"
    }

}

Write-Output "`nEnd of script!"

相关问题