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
LVL 1
WeTiAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

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 }
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

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?
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

WeTiAuthor Commented:
Nope, I got only option run with powershell...
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

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
WeTiAuthor Commented:
As great as you are oBdA this is working fine with your help, Sirbounty thanks for the effort.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Powershell

From novice to tech pro — start learning today.