Reputation: 5933
I am trying to make a script that performs a bunch of installation operations, including executing other files, such as .reg files to update the registry. I created a batch file to kick it off and have code in the powershell script to self elevate to run as admin. The problem is that once run as admin, the working path is C:\Windows\system32, after which the script cannot file to other (relative) files it needs to run.
Install.bat:
powershell InstallSteps.ps1
InstallSteps.ps1:
param([switch]$Elevated)
function Test-Admin {
$currentUser = New-Object Security.Principal.WindowsPrincipal $([Security.Principal.WindowsIdentity]::GetCurrent())
$currentUser.IsInRole([Security.Principal.WindowsBuiltinRole]::Administrator)
}
if ((Test-Admin) -eq $false) {
if ($elevated)
{
# tried to elevate, did not work, aborting
}
else {
Start-Process powershell.exe -Verb RunAs -ArgumentList ('-noprofile -noexit -file "{0}" -elevated' -f ($myinvocation.MyCommand.Definition))
}
exit
}
# THIS SHOWS THE PATH IS "C:\WINDOWS\SYSTEM32"
Write-Host $pwd
# THIS FAILS, BECAUSE IT CAN'T FIND THE FILE
reg IMPORT EnableAllTrustedApps.reg
I have not found a way to pass in the relative path to these to make into the working path. It seems the "Start-Process" method of elevating loses all context of where the script was originally located.
Upvotes: 0
Views: 1627
Reputation: 52689
I recommend always using this function to call external things. It's more reliable than relative paths.
function Get-Script-Directory
{
$scriptInvocation = (Get-Variable MyInvocation -Scope 1).Value
return Split-Path $scriptInvocation.MyCommand.Path
}
e.g.
$script_home = Get-Script-Directory
reg.exe IMPORT "$script_home\EnableAllTrustedApps.reg"
Note - in 3.0 or above you can use this new built-in variable instead of the function.
$PSScriptRoot
You might also want to try specifying the -WorkingDirectory
parameter for Start-Process
e.g. Start-Process -FilePath powershell.exe -verb RunAs -WorkingDirectory $PWD.Path
Upvotes: 2