none
Powershell is Not Renaming Folder Correctly RRS feed

  • Question

  • I used the below scripts to change SharePoint file names to Title-Case and remove any unwanted symbols with dashes. These work well except when it comes to removing the excess dashes from folder names. Any ideas why?

    # Replaces unwanted symbols with a dash.
    Get-ChildItem “c:\temp” -Recurse | `Where-Object {$_.Name -match ' '} | `
    Rename-Item -NewName { $_.Name -replace '[^a-zA-Z0-9/.]','-' }

    # Replaces an underscore with a dash.
    Get-ChildItem “c:\temp” -Recurse | `Where-Object {$_.Name -match '_'} | `
    Rename-Item -NewName { $_.Name -replace '_','-' }

    # Removes all 3 (---) excess dashes first.
    Get-ChildItem “c:\temp” -recurse | where {-Not $_.PsIscontainer -AND $_.name -match "-"} | foreach {$New=$_.name.Replace('---',"-")
    Rename-Item -path $_.Fullname -newname $New -passthru}

    # Removes all 2 (--) excess dashes leftover.
    Get-ChildItem “c:\temp” -recurse | where {-Not $_.PsIscontainer -AND $_.name -match "-"} | foreach {$New=$_.name.Replace('--',"-")
    Rename-Item -path $_.Fullname -newname $New -passthru}

    # Formats filename to Title-Case and extension to lower case.
    $Culture = Get-Culture
    Get-ChildItem “c:\temp” -recurse |Where {-Not $_.PSIsContainer} |Rename-Item -NewName {
    $Culture.textinfo.totitlecase($_.BaseName)+ ($_.Extension.ToLower())}

    Friday, January 26, 2018 7:07 PM

Answers

  • Like this:

    'xxx-xxx---xxx----xxxx' -replace '--*','-'

    Replace two or more with one.


    \_(ツ)_/



    • Edited by jrv Friday, January 26, 2018 7:31 PM
    • Marked as answer by m3looperPer Friday, February 2, 2018 1:25 AM
    Friday, January 26, 2018 7:30 PM

All replies

  • Like this:

    'xxx-xxx---xxx----xxxx' -replace '--*','-'

    Replace two or more with one.


    \_(ツ)_/



    • Edited by jrv Friday, January 26, 2018 7:31 PM
    • Marked as answer by m3looperPer Friday, February 2, 2018 1:25 AM
    Friday, January 26, 2018 7:30 PM
  • Sorry for not getting back sooner. The link to this wasn't working.

    where {-Not $_.PsIscontainer -AND

    This is the code I needed to remove.

    I mistakenly thought this was to filter out empty folders.

    Friday, February 2, 2018 1:30 AM