Renaming a Folder and create a new folder in PowerShell

Question:

My folder structure: C:\example\latest.
I want to check if the subfolder latest already exists or not. If it does, I want to rename it as latest_MMddyyyy and then create a new folder called latest.
If it does not have latest already, then simple create the folder.

This is what I have:

It is doing two things:

  1. Rename my latest folder as _MM-dd-yyyy but I want it to rename as “latest_MM-dd-yyyy”
  2. Throw an error: Missing an argument for parameter ‘ItemType’. Specify a parameter of type ‘System.String’ and try again.

what am I doing wrong?

Answer:

Throws an error: Missing an argument for parameter 'ItemType'. Specify a parameter of type 'System.String' and try again.

As Deadly-Bagel’s helpful answer points out, you’re missing an argument to -ItemType and instead follow it with another parameter, -Type, which, in fact, is an alias for -ItemType – so removing either -ItemType or -Type will work.

To find a parameter’s aliases, use something like (Get-Command New-Item).Parameters['ItemType'].Aliases

Renames my latest folder to _MM-dd-yyyy, but I want latest_MM-dd-yyyy.

  • You append the date string directly to $localPath, which has a trailing \, so $newPath looks something like 'c:\example\latest\_02-08-2017', which is not the intent.
  • Ensuring that $localPath has no trailing \ fixes the problem, but do note that Rename-Item generally only accepts a file/directory name as a -NewName argument, not a full path; you can only get away with a full path if its parent path is the same as the input item’s – in other words, you can only specify a path if it wouldn’t result in a different location for the renamed item (you’d need the Move-Item cmdlet to achieve that).
    • Split-Path -Leaf $localPath offers a convenient way of extracting the last path component, whether or not the input path has a trailing \.
      In this case: latest
    • Alternatively, $localPath -replace '\\$' would always return a path without a trailing \.
      In this case: c:\example\latest

If we put it all together:

Note that if you run this script more than once on the same day, you’ll get an error on renaming (which could easily be handled).

Source:

Renaming a Folder and create a new folder in PowerShell by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply