user3722239
user3722239

Reputation: 3

Change directory to the location of the operating script

So, I can find out the directory of the script with

function Get-ScriptDirectory { Split-Path -parent $PSCommandPath }

But I can't manage to change the directory to the folder, where the script is saved. For example

cd d:\MyScripts\

So something like

cd function Get-ScriptDirectory { Split-Path -parent $PSCommandPath }

doesn't work.

And sorry if that is a common and dumb question, but I'm new in powershell and I searched and tried a lot before posting here

Upvotes: 0

Views: 3351

Answers (1)

Rahul
Rahul

Reputation: 77866

You can do it like below. You can include the code sample in your script. Then if you are running the script from other location (by means of fully qualifying path name to the script); $MyInvocation will pickup the invocation location.

From Documentation

$MyInvocation
   Contains an information about the current command, such as the name, 
   parameters, parameter values, and information about how the command was
   started, called, or "invoked," such as the name of the script that called
   the current command.

Code Sample

$scriptpath = $MyInvocation.MyCommand.Path
$dir = Split-Path $scriptpath
cd $dir

Upvotes: 1

Related Questions