Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Saturday, October 29, 2011 4:26 AM
Hey everyone,
i'm trying to find a way to make my powershell code run as administrator, without right clicking "run as administrator" and without
having to input the user and password manually.
For example, i'd like to run the script with two arguments (user and password) and then the code will use these arguments some how to run
as administrator and let me perform administrative command automatically.
any ideas?
All replies (5)
Saturday, October 29, 2011 1:32 PM ✅Answered | 2 votes
Create a PsSession using your Administrator credentials, then invoke commands in it.
You could save and retrive the credentials details from a secure file (in the sense that cannot directly be read).
To save the admin pass to a file:
$adminPass=Read-Host -AsSecureString
$adminPass|ConvertFrom-SecureString | Out-File "Pass.txt"
To create a cred from the file:
$lala= gc .\Pass.txt | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PSCredential("Administrator",$lala)
To create the Pssession:
$session= New-PSSession -Credential $cred -ComputerName .
And to invoke commands in that session:
Invoke-Command -ScriptBlock {WhatEverYouWantToRun} -Session ($session)
Saturday, October 29, 2011 4:42 AM
This will elevate the currently-running script with administrative rights.
Start-Process -FilePath PowerShell.exe -ArgumentList $MyInvocation.MyCommand.Definition -Verb RunAs
If you found this post helpful, please "Vote as Helpful". If it answered your question, remember to "Mark as Answer".
Rich Prescott | Infrastructure Architect, Windows Engineer and PowerShell blogger | MCITP, MCTS, MCP
[Blog] Engineering Efficiency | [Twitter] @Rich_Prescott | [Powershell GUI] Client System Administration tool | [PowerShell GUI] New AD User Creation tool
Saturday, October 29, 2011 5:53 AM
Maybe i'm missing something, but this didn't work
added it to my code,
what happened was a pop out window that i had to confirm (asking me to allow powershell to do something) and
then i still got "access is denied" while performing my script.
i do not get access is denied if i run my script from a cmd window that i opened by "run as administrator".
Saturday, October 29, 2011 12:41 PM
Hi,
If you have enabled UAC I think you can't elevate administrative rights without confirm action in UAC pop up.
One alternative then I found it is create Task in Scheduler and set it to run with highest privileges. But I don’t test it jet.
Or try use Invoke-Command but you need configure remote access event you what do something on localhost.
Invoke-Command -ComputerName localhost -FilePath P:\admin.ps1 –Credential administrator
Sunday, October 30, 2011 9:15 AM
Thanks Vodoomsr,
that sounds good.
i'll try it out and return with a result soon...