Call Set-Location from within a cmdlet
-
24-06-2021 - |
Question
I'm creating a cmdlet for PowerShell and I need to be able to call Set-Location
(aka cd
) from within a the cmdlet. I would do it like this
var setLocation = new Microsoft.PowerShell.Commands.SetLocationCommand();
setLocation.Path = path;
setLocation.Invoke();
except that it gives me an error that says You cannot invoke a cmdlet that derrives from PSCmdlet
. I'd like to use Set-Location
, but I'd be happy with just simply changing the directory of the shell.
Solution
The best answer I could find was to use InvokeScript
to change directory:
InvokeCommand.InvokeScript(string.Format("Set-Location {0}", fullPath));
It's possible that there's a "more C#" way to do this, but I couldn't find it.
OTHER TIPS
The question is a bit older but here is a slightly nicer solution:
The class PathIntrinsics contains the method SetLocation.
To manipulate the path of the current session, you can access the PathIntrinsics via the SessionState using the Path property.
long story short:
SessionState.Path.SetLocation("C:/some/path");
You could try to derive from CMDLET not PSCMDLET.
Simply using Set-Location inside the script should do the work.
So for example:
# Script.ps1
CD ~
Get-Location
Set-Location c:\Windows
Get-location
Once the script finishes, try Get-Location again!
If I use Set-Location in a script, I usually like to first use Push-Location to store the current location and then at the end of my script I can use Pop-Location to return the user to where they were.
Push-Location $PWD
Set-Location $somewhere
#script body
Pop-Location
Unless of course, the intention of the script is to change directories for the user.