Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set-Location versus SetCurrentDirectory

Tags:

powershell

What is the difference in Powershell between

Set-Location "$env:ProgramFiles\My App\"

and

[System.IO.Directory]::SetCurrentDirectory("$env:ProgramFiles\My App\")

The reason for asking is that I recently had a script which used Add-Type -Path XXX to add a reference to an assembly. The assembly depended on a number of DLLs (some possibly linked at runtime not loadtime) located in the same folder as the assembly.

So I thought I would change directory to the folder, to help the assembly find all the necessary files. When I changed directory using Set-Location I got an error (one that was specific to the assembly) complaining it could not find all the DLLs. Using SetCurrentDirectory worked however.

Therefore the two commands seem to be doing different things. I would have expected them to be the same.

like image 398
Bob Mortimer Avatar asked Sep 05 '25 03:09

Bob Mortimer


2 Answers

Set-Location set current location for PowerShell Runspace. PowerShell location can point to any PowerShell provider, like Certificate, Registry or WSMan. One process can have multiple active PowerShell Runspaces and each of them have their own current location, and all of them can be different from each other.

[System.IO.Directory]::SetCurrentDirectory set current working directory for process. Process have only one current working directory and it has to point to the file system. It can not point to registry or something else.

like image 127
user4003407 Avatar answered Sep 09 '25 16:09

user4003407


Unfortunately comparing the System.IO.Directory.SetCurrentDirectory help with the Set-Location Help doesn't seem to offer much indication in the behaviour you experienced however looking at this TechNet article (Using the Set-Location Cmdlet) it seems that the Set-Location changes the working directory of the current "namespace" (Technet's term, presumably for a runspace) while the SetCurrentDirectory method changes the working directory for the powershell process.

System.IO.Directory.SetCurrentDirectory - (https://msdn.microsoft.com/en-us/library/system.io.directory.setcurrentdirectory(v=vs.110).aspx)

Set-Location - (https://technet.microsoft.com/en-us/library/hh849850.aspx)

like image 25
Djarid Avatar answered Sep 09 '25 18:09

Djarid