My Situation: I have to run a PowerShell script as Administrator (because of accessing a privileged folder) and my script is also referencing files in the same directory as the script. I need to use a relative file path but I can't due to PowerShell switching the directory to C:\\WINDOWS\\system32
when ran as admin.
In PowerShell, is there a way to restore the directory to the current directory that the script is located?
My Script: (will be ran as admin)
Copy-Item -Path .\file1.txt -Destination 'C:\Users\privileged_folder'
Directory Structure:
MyDir\
file1.txt
myscript.ps1 <- ran as admin
In your script, you can set the location to the script folder. From within your script, either of the following techniques will work:
# PowerShell 3+
cd $PSScriptRoot
# PowerShell 2
cd ( Split-Path -Parent $MyInvocation.MyCommand.Definition )
Changing to $PSScriptRoot
works in all currently supported versions of PowerShell, but using Split-Path
to get the script directory is useful if you for some reason still have nodes running PowerShell 2.
If you want to change back to the previous directory after your script is done executing (probably a good move) you can also make use of Push-Location
and Pop-Location
instead of cd
or Set-Location
:
# Also aliased to pushd
Push-Location $PSScriptRoot
# My script stuff
# Also aliased to popd
Pop-Location
These two cmdlets treat locations as a stack - Push-Location
changes your location and adds the directory to the location stack while Pop-Location
will remove the current directory from the stack and return you to the previous location. It works much like push and pop operations on arrays.
You could also prefix your relative paths in your script with either $PSScriptRoot
or ( Split-Path -Parent $MyInvocation.MyCommand.Definition )
as shown in the previous section. If we attach the prefix to the otherwise relative path of file1.txt
:
$filepath1 = "${PSScriptRoot}\file1.txt"
Now you have an absolute path to file1.txt
. Note that this technique will work with any relative path to $PSScriptRoot
, it does not have to be in the same folder as your ps1
script.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.