I am trying to call a PS script as admin (runas) from another PS script and so far have not been successful. I am getting an error but can't see it and it seems that the 2nd script is not even being called as I have a read-host as the first command. If I manually elevate powershell then call the script, it works.
The first script, I have tried going the route of Start-process and $newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell"; but neither works.
I have tried both dot sourcing or hard coding the path (parent script is in the same folder)
I know I am missing something but can't figure out what. The end result I am trying to get is to spin off a process, prompt to elevate, add IP to trusted hosts.
$filepath = ".\UpdateTrustedHosts.ps1"
$arglist = "-noexit -File $filepath"Start-Process powershell.exe -verb runas -ArgumentList "C:\path to file\UpdateTrustedHosts.ps1"
OR
$filepath = ".\UpdateTrustedHosts.ps1"
$arglist = "-noexit -File $filepath"Start-Process powershell.exe -verb runas -ArgumentList $arglist
$newProcess = new-object System.Diagnostics.ProcessStartInfo "PowerShell";$newProcess.Arguments = "C:\Path to Script\UpdateTrustedHosts.ps1";
$newProcess.Verb = "runas";
$process = [System.Diagnostics.Process]::Start($newProcess);
$process.waitforExit()
The second script
$myWindowsID=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$myWindowsPrincipal=new-object System.Security.Principal.WindowsPrincipal($myWindowsID)
$adminRole=[System.Security.Principal.WindowsBuiltInRole]::Administrator
If ($myWindowsPrincipal.IsInRole($adminRole)){
set-item wsman:\localhost\Client\TrustedHosts 10.10.10.10
}Else{
Write-Host "Window not called with Run As Admin"
}