Thursday, March 27, 2014

PowerShell Tips : Joining paths using Join-Path cmdlet

 

Quote of the Day : "“Many of life’s failures are people who did not realize how close they were to success when they gave up” – Thomas Edison."

I am hoping that while using PowerShell , you have seen the  "Join-Path" cmdlet.

It is a very cool cmdlet and I have seems not much of the PowerShell scripters using it ( I was one of them ), to be honest even I was not much using it. But it is very useful and neat way to join to paths.

If you want to join two different path, there are two ways to do that, one is the dirty way (which you can see in my very old scripts) and the other one is using Join-Path cmdlet, neat and clean way.

The Dirty way.

If i want to join a path to my desktop folder using environment variable "UserProfile". I can use concatenation and concatenate it with $env:userprofile and adding "\" and adding Desktop.

"

$userDesktop = $env:USERPROFILE + "\" + "Desktop"

 

"26-03-2014 23-20-34

and you can see it give us a desirable result but it look dirty and it is a bad practice.

The Neat way.

Using Join-Path cmdlet.

$userDesktop = Join-Path $env:USERPROFILE -ChildPath "Desktop"

26-03-2014 23-25-07

 You can compare the result, the result is same, but, it looks clean and it is proper way to join two paths. and it is consider as good and best practice.

In both, ways, using concatenation or using "Join-Path" you will get the same result, but it is always good to use the neat and best way in scripting. 

 

thank-you-1 (1)

Regards

Aman Dhally

 

 

If you like, you can follow me on Twitter and Facebook. You can also check my “You Tube channel for PowerShell video tutorials. You can download all of my scripts from “Microsoft TechNet Gallery”.

No comments:

Post a Comment