• Status: Solved
  • Priority: Medium
  • Security: Private
  • Views: 53
  • Last Modified:

Powershell starting as admin

Dear expert

This is a question of run powershell script in admin mode, ok, I currently created a script of starting and stopping services items, well scripts works fine... however I noticed that if i simply just right click and choose Run with Powershell of the .ps1 file, it open a user rights powershell window, and when I try to stop services with that, I got "not permitted" error. I would like to do is to run it in a administrator mode. I tried:
Start-Process powershell -verb runas -ArgumentList "-file fullpathofthescript" 

Open in new window

This will work but didn't work with my code, I got:  
param(            
 [string[]]$ComputerName = $env:ComputerName,            
 [parameter(Mandatory=$true)]            
 [string[]]$ServiceName            
) 

Open in new window

If I use that Start-Process it will just jump over the param and param will return as null. I use those param to enter different service name to stops it.
Any idea how I can solve this problem?

Regards
0
WeTi
Asked:
WeTi
  • 3
  • 2
2 Solutions
 
sirbountyCommented:
Have you tried using this?  Just adds a test beforehand, but also moves the verb param to the end...
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }
0
 
WeTiAuthor Commented:
Same problem, what that -if statement did was open a new powershell with administrator rights, then it still passing by Param and end. I will give you my code here:

param(            
 [string[]]$ComputerName = $env:ComputerName,            
 [parameter(Mandatory=$true)]            
 [string[]]$ServiceName            
)    

 foreach($Computer in $ComputerName) {            
 Write-Host "Working on $Computer"            
 if(!(Test-Connection -ComputerName $Computer -Count 1 -quiet)) {            
  Write-Warning "$computer : Offline"            
  Continue            
 }            
             
 foreach($service in $ServiceName) {            
  try {            
   $ServiceObject = Get-WMIObject -Class Win32_Service -ComputerName $Computer -Filter "Name='$service'" -EA Stop            
   if(!$ServiceObject) {            
    Write-Warning "$Computer : No service found with the name $service"            
    Continue            
   }            
   if($ServiceObject.StartMode -eq "Disabled") {            
    Write-Warning "$Computer : Service with the name $service already in disabled state"            
    Continue            
   }            
               
   Set-Service -ComputerName $Computer -Name $service -EA Stop -StartMode Disabled            
   Write-Host "$Computer : Successfully disabled the service $service. Trying to stop it"            
   if($ServiceObject.Status -eq "Running") {            
    Write-Warning "$Computer : $service already in stopped state"            
    Continue            
   }            
   $retval = $ServiceObject.StopService()            
            
   if($retval.ReturnValue -ne 0) {            
    Write-Warning "$Computer : Failed to stop service. Return value is $($retval.ReturnValue)"            
    Continue            
   }            
               
   Write-Host "$Computer : Stopped service successfully"            
               
  } catch {            
   Write-Warning "$computer : Failed to query $service. Details : $_"            
   Continue            
  }                        
 }  }

Open in new window

0
 
sirbountyCommented:
Script is fine - that's not the issue.

"...if i simply just right click and choose Run with Powershell of the .ps1 file,"
Can you not right-click and choose run as administrator?
Or elevate a cmd window and launch powershell within there?
0
WEBINAR: 10 Easy Ways to Lose a Password

Join us on June 27th at 8 am PDT to learn about the methods that hackers use to lift real, working credentials from even the most security-savvy employees. We'll cover the importance of multi-factor authentication and how these solutions can better protect your business!

 
WeTiAuthor Commented:
Nope, I got only option run with powershell...
0
 
oBdACommented:
Lines 7-15 will restart the script as administrator (if possible). You can use that as template for other scripts.
The rest is your original script, reformatted:
* Neither "If" nor "ForEach" are functions/static methods of something, so put a space in front of the round bracket.
* Indenting properly helps immensely tracking the nesting depth.
[CmdletBinding()]
Param(
	[parameter(Mandatory=$true)]
	[string[]]$ServiceName,
	[string[]]$ComputerName = $env:ComputerName
)
$Principal = New-Object -TypeName System.Security.Principal.WindowsPrincipal -ArgumentList ([System.Security.Principal.WindowsIdentity]::GetCurrent())
If (-not $Principal.IsInRole([System.Security.Principal.WindowsBuiltInRole]::Administrator)) {
	Write-Host "Not running elevated; restarting '$($MyInvocation.MyCommand.Path)' elevated ..." -ForegroundColor Yellow
	$ArgumentList = '-NoExit', '-Command', "& '$($MyInvocation.MyCommand.Path)'"
	$Argumentlist += $PSBoundParameters.GetEnumerator() | ForEach-Object {"-$($_.Key) '$($_.Value -join "', '")'"}
	Start-Process -Verb RunAs -FilePath 'powershell.exe' -ArgumentList $ArgumentList
	Write-Host "Non-elevated script ends now." -ForegroundColor Yellow
	Exit
}
Write-Host "Running elevated ..." -ForegroundColor Green

ForEach ($Computer in $ComputerName) {
	Write-Host "Working on $Computer"
	If (!(Test-Connection -ComputerName $Computer -Count 1 -quiet)) {
		Write-Warning "$computer : Offline"
		Continue
	}
	ForEach ($service in $ServiceName) {
		Try {
			$ServiceObject = Get-WmiObject -Class Win32_Service -ComputerName $Computer -Filter "Name='$service'" -EA Stop
			If (!$ServiceObject) {
				Write-Warning "$Computer : No service found with the name $service"
				Continue
			}
			If ($ServiceObject.StartMode -eq "Disabled") {
				Write-Warning "$Computer : Service with the name $service already in disabled state"
				Continue
			}
			Set-Service -ComputerName $Computer -Name $service -EA Stop -StartMode Disabled
			Write-Host "$Computer : Successfully disabled the service $service. Trying to stop it"
			If ($ServiceObject.Status -eq "Running") {
				Write-Warning "$Computer : $service already in stopped state"
				Continue
			}
			$retval = $ServiceObject.StopService()
			If ($retval.ReturnValue -ne 0) {
				Write-Warning "$Computer : Failed to stop service. Return value is $($retval.ReturnValue)"
				Continue
			}
			Write-Host "$Computer : Stopped service successfully"
		} Catch {
			Write-Warning "$computer : Failed to query $service. Details : $_"
			Continue
		}
	}
}

Open in new window

1
 
WeTiAuthor Commented:
As great as you are oBdA this is working fine with your help, Sirbounty thanks for the effort.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

How do you know if your security is working?

Protecting your business doesn’t have to mean sifting through endless alerts and notifications. With WatchGuard Total Security Suite, you can feel confident that your business is secure, meaning you can get back to the things that have been sitting on your to-do list.

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now