After much trial and error I came up with a solution:
Create a shortcut with this (edited for your .ps1) so that the scripts run as admin in relation to any directory:
CMD /C PowerShell "SL -PSPath '%CD%'; $Path = (GL).Path; SL ~; Start PowerShell -Verb RunAs -Args \""SL -PSPath '"$Path"'; & '".\YourScriptHere.ps1"'"\""
You will need to clear the βStart atβ shortcut so that its relative path is set as the working directory.
Or here is a script that will generate one of these shortcuts for each .ps1 in the directory (with "Start on" already cleared):
(GCI | Where-Object {$_.Extension -eq ".ps1"}).Name | ForEach-Object { $WshShell = New-Object -ComObject WScript.Shell $Shortcut = $WshShell.CreateShortcut((GL).Path+"\$_ Run.lnk") $Shortcut.TargetPath = 'CMD' $Shortcut.Arguments = "/C PowerShell `"SL -PSPath `'%CD%`'; `$Path = (GL).Path; SL ~; Start PowerShell -Verb RunAs -Args \`"`"SL -PSPath `'`"`$Path`"`'; & `'`".\$_`"`'`"\`"`"" $Shortcut.IconLocation = 'PowerShell.exe' $Shortcut.Save() } ) .Path + "\ $ _ Run.lnk") (GCI | Where-Object {$_.Extension -eq ".ps1"}).Name | ForEach-Object { $WshShell = New-Object -ComObject WScript.Shell $Shortcut = $WshShell.CreateShortcut((GL).Path+"\$_ Run.lnk") $Shortcut.TargetPath = 'CMD' $Shortcut.Arguments = "/C PowerShell `"SL -PSPath `'%CD%`'; `$Path = (GL).Path; SL ~; Start PowerShell -Verb RunAs -Args \`"`"SL -PSPath `'`"`$Path`"`'; & `'`".\$_`"`'`"\`"`"" $Shortcut.IconLocation = 'PowerShell.exe' $Shortcut.Save() } ; (GCI | Where-Object {$_.Extension -eq ".ps1"}).Name | ForEach-Object { $WshShell = New-Object -ComObject WScript.Shell $Shortcut = $WshShell.CreateShortcut((GL).Path+"\$_ Run.lnk") $Shortcut.TargetPath = 'CMD' $Shortcut.Arguments = "/C PowerShell `"SL -PSPath `'%CD%`'; `$Path = (GL).Path; SL ~; Start PowerShell -Verb RunAs -Args \`"`"SL -PSPath `'`"`$Path`"`'; & `'`".\$_`"`'`"\`"`"" $Shortcut.IconLocation = 'PowerShell.exe' $Shortcut.Save() }
If necessary, add -NoExit , -ExecutionPolicy Unrestricted etc. immediately after the first \" .
Notes:
The reason for the second instance of admin PowerShell, to run the first time, is that running as an administrator directly (by selecting the shortcut "Run as administrator"), to , for any reason, ignores the "Start" and always starts in the System32.
CMD is used to start the first instance because PowerShell currently cannot resolve paths containing square brackets, interpreting them as regular expression characters. This can usually be avoided by using LiteralPath parameter (aka PSPath), but here the path is passed behind the scenes at the start, and it is corrected by developers (I just sent a bug report here ).
source share