8

I wrote a script that will switch between having a computer connect via Wi-Fi or wired Internet simply by running a batch file. I wrote this because I don't like having to type in my username and password to switch between the two every time.

NOTE: I HAVE to have UAC enabled so unfortunately just turning it off isn't an option.

It looks at the status of the wireless adapter. If it is currently enabled, it will turn off the wireless adapter and enable the wired adapter. If the wireless is not enabled, it will enabled and disable the wired. This is the code.

$adapter = Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName . | Where-Object {$_.ServiceName -ne "hamachi"}
function wirelessOn
{
    $wireless = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.Name -like "*Wireless*"}
    $wireless.Disable()
    $wired = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.Name -like "*gigabit*"}
    $wired.Enable()
}

function wirelessOff
{
    $wired = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.Name -like "*gigabit*"}
    $wired.Disable()
    $wireless = Get-WmiObject -Class Win32_NetworkAdapter | Where-Object {$_.Name -like "*Wireless*"}
    $wireless.Enable()
}

switch -wildcard ($adapter.description){
    "*wireless*" {
        wirelessOn
    }
    "*gigabit*" {
        wirelessOff
    }
}

Unfortunately, this script only functions properly if run as administrator, thus the whole reason I wrote it is moot. Is there a way I can have this elevate to administrator privileges without me having to do anything?

3
  • 1
    In effect, you're asking how to run a script elevated without having to deal with UAC. This completely negates the whole point of UAC. If you could do this, it would be a serious hole in UAC, don't you think? Commented Oct 3, 2012 at 14:22
  • I don't believe so. Because I know it's possible to get the credentials to pass to UAC from a text file or hard coded in. I know this is possible because I'm fairly certain servers are constaintly waiting for the sys admin to log in and click "yes" Commented Oct 22, 2012 at 16:06
  • See also: stackoverflow.com/q/50553894/45375 Commented Aug 21, 2024 at 22:29

2 Answers 2

12

You can start a new, elevated PowerShell process to run your script e.g.:

Start-Process PowerShell -verb runas -ArgumentList '-noexit','-File','path-to-script'

If you don't want the PowerShell window to hang around then get rid of the '-noexit' but for debugging the launch of your script, it is useful.

If you had access to an admin account username/password, you could do this:

# Capture encrypted password once and store to file
$passwd = Read-Host "Enter password" -AsSecureString
$encpwd = ConvertFrom-SecureString $passwd
$encpwd > $path\password.bin

# Afterwards always use this to start the script
$encpwd = Get-Content $path\password.bin
$passwd = ConvertTo-SecureString $encpwd
$cred = new-object System.Management.Automation.PSCredential 'domain\username',$passwd
Start-Process PowerShell -Cred $cred -ArgumentList '-noexit','-File','path-to-script'   
Sign up to request clarification or add additional context in comments.

4 Comments

i still get UAC when i do this
Typical UAC config is to prompt to "allow" the program to run. That happens when you're user account is a member of Administrators but you run with a standard user token. It sounds like you are actually running under a standard user account? If so, do you know an admin username/password? In that case, you can pass in credentials to the Start-Process cmdlet. Also there are ways to safely store the password in DPAPI and then retrieve it in a script so that you don't have to be prompted to supply a password.
I do not have access to the "admin" account. If I type my credentials in, it does in fact work. How would I pass mine in automatically?
@mhopkins321 i m facing same issue. where i dont have admin access. i tried running my script using runas but m getting UAC prompt to launch powershell.. how did you get around it?
10

You can do this by using a batch (.bat) file and Task Scheduler.

First, you must create a batch file (you can use notepad for this) in the same folder as your PowerShell .ps1 file with the following contents:

@ECHO OFF
SET ThisScriptsDirectory=%~dp0
SET PowerShellScriptPath=%ThisScriptsDirectory%PutTheNameOfYourPowerShellScriptHere.ps1
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PowerShellScriptPath%""' -Verb RunAs}";

Open Task Scheduler and click on Task Scheduler Library on the left pane. Then, right-click Task Scheduler Library and select Create Task (this should open a window). Give your task a name and check that Run with highest privileges is selected. Then, click on the Actions tab and click on New (this should open a window). Verify that the selected Action is Start a program and then click on Browse to select the batch file. Click Ok on both windows and you should be back on the main Task Scheduler window. You should see your newly created task on top of the list, so right-click it and select Run. You should see that your PowerShell script runs with full Administrator Privileges and without any UAC prompts.

Now, if you want to run your PowerShell script on a regular schedule, you could customize that by right-clicking your newly created task, selecting Properties, clicking on the Triggers tab and clicking on New.

However, if you'd prefer to run your PowerShell script by double-clicking a shortcut file you'd have to follow some additional steps. Right-click on your desktop and select New > Shortcut and enter the following location:

C:\Windows\System32\schtasks.exe /run /tn "PutTheNameOfYourNewlyCreatedTaskHere"

Click Next, give your shortcut a name and click on Finish. You should try opening your shortcut and see if your PowerShell script runs as you want.

That is all.

Bonus: if you want to run your PowerShell script by pressing a key or a key combination, you can also right-click your shortcut and input what you want in the Shortcut key: field. However, if it doesn't let you enter a particular key or key combination, you could also install PowerToys by Microsoft and use its Keyboard Manager utility to remap a key or a key combination. For example. you could enter the F8 in the Shortcut key: field and then remap that to a key that you rarely use, like the Calculator key on most keyboards.

Please let me know if you have any problems while following this guide.

5 Comments

Also, I'm aware that this is an 8-year-old question, but wanted to help anyways 😉
surprisingly this seems to be the only viable option I have found in the last hour and it doesn't "leak" password. (And has one-time setup with the scheduler). The only missing part for my use case is that I need to be able to pass parameters to the script... and not sure schtasks.exe supports it...
Alternatively, you can manually create the scheduled task once with all the settings you need/want, and then export the task. This will give you an XML file that you can then import wherever you need it. You can do this either with SchTasks.exe or with Export-ScheduledTask & RegisterScheduledTask
As an aside: There's no reason to use "& { ... }" in order to invoke code passed to PowerShell's CLI via the -Command (-c) parameter - just use "..." directly. Older versions of the CLI documentation erroneously suggested that & { ... } is required, but this has since been corrected.
There is no need for an aux. batch file: all that matters is whether the task itself runs elevated: if it does, powershell.exe can be invoked directly. If it doesn't, Start-Process -Verb RunAs won't help. The fundamental limitation of this approach is that it only works if the user account in whose context the scheduled task is configured to run is a member of the Administrators group and that on-demand invocation is made from the very same account. See this answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.