none
Remove $ # - from filenames with Powershell command RRS feed

  • Question

  • I am working on a mass migration of data from onsite Server based network shares to SharePoint.  In preparation for this I'm try to remove all spaces and $ # - characters from existing file names. So far using code I found in another topic I've been able to replace nearly all spaces with _ . Now I just need to be able to remove any $ # and - from the file names.  Please advise.

    This is what I used to replace the spaces with underscores.

    gci -Recurse | ? { $_.Name -match '\s' } | % { ren $_.FullName ($_.Name -replace '\s', '_') -verbose}

    Thursday, January 19, 2017 3:29 PM

Answers

  • try this:

    -replace '[\s\$#\!@%-]+' , '_'

    Edit: ... no this:

    '([\s\$#\!@%-]+|_)+' , '_'


    Grüße - Best regards

    PS:> (79,108,97,102|%{[char]$_})-join''


    Thursday, January 19, 2017 10:38 PM

All replies

  • -replace '\s|\$|#','_'


    Grüße - Best regards

    PS:> (79,108,97,102|%{[char]$_})-join''

    Thursday, January 19, 2017 3:44 PM
  • Thank you for that.  May I ask how would I include ! @ % - as well?  I noticed on the $ is was identified by \$ but in the instance of # no \ needed to proceed it. 

    Is there also a way if I run the first operation and multiple files end up with more than one underscore in a row such as : GPM $100-%75.xlxs -> GPM__100__75.xlxs I would like a second pass to just turn that file name into GPM_100_75.xlxs.

    Thursday, January 19, 2017 7:57 PM
  • This article documents the characters that must be escaped, with the "\" escape character:

    https://msdn.microsoft.com/en-us/library/4edbef7e(v=vs.110).aspx

    Only the following:

    . $ ^ { [ ( | ) * + ? \

    And per this article:

    https://msdn.microsoft.com/en-us/library/az24scfc(v=vs.110).aspx

    the "+" character means one or more of a character, so '_+' should be one or more underscores.


    Richard Mueller - MVP Enterprise Mobility (Identity and Access)


    Thursday, January 19, 2017 8:43 PM
    Moderator
  • Thank you very much for the link.  With the adjustments detailed there it is working exactly as I wanted it too.  I have to run it a few times to get everything but that is fine.

    This is what I ended up with

    gci -Recurse | ? { $_.Name -match '\s|\$|#|%|_+|-' } | % { ren $_.FullName ($_.Name -replace '\s|\$|#|%|_+|-', '_') -verbose}

    Thursday, January 19, 2017 10:10 PM
  • try this:

    -replace '[\s\$#\!@%-]+' , '_'

    Edit: ... no this:

    '([\s\$#\!@%-]+|_)+' , '_'


    Grüße - Best regards

    PS:> (79,108,97,102|%{[char]$_})-join''


    Thursday, January 19, 2017 10:38 PM