Folder and File

After having been in the industry for a while. I must admit that I’ve never tried to create a folder and file with the same name in a folder.    Turns out that there is a rule that the same name can’t exist more than once in a folder or directory.  This applies to both windows and linux systems.

I found this out because in my code I didn’t specify the ItemType on New-Item Powershell Cmdlet.

new-item $home/.config/j
Mode                LastWriteTime         Length Name
----                -------------         ------ ----
-a----         1/4/2019   1:07 PM              0 j 

new-item $home/.config/j -itemtype container
new-item : An item with the specified name C:\Users\tschumacher\.config\j already exists.
At line:1 char:1
+ new-item $home/.config/j -itemtype container
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : ResourceExists: (C:\Users\tschumacher\.config\j:String) [New-Item], IOException
+ FullyQualifiedErrorId : DirectoryExist,Microsoft.PowerShell.Commands.NewItemCommand

To make sure I don’t commit this “cardinal sin” again. I wrote a small if statement to remedy my issue.  Since I wanted the item I’m passing to “j” to be a folder I check to see if it is a file. If it’s a file I delete it (forcibly) and then recreate it as a folder.

 if(!(test-path -PathType Container "$home/.config/j" -ErrorAction Ignore))
   if(test-path -path "$home/.config/j" -PathType Leaf)
     Remove-Item "$home/.config/j" -force
   new-item -ItemType Directory "$home/.config/j"

I purposefully have my folder seperators as / instead of \. Thus allowing for this script to work on both windows and linux.

I hope this helps someone.


until then

keep scripting




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s