0

I have a small powershell script (script.ps1 file) that installs a service.

Remove-Service -Name "MyService"

This code has 2 problems:

  1. It should run with admininstrator privilegs
  2. New-Service command is a powershell6 command, but ps1 files runs by ps5.

I found here a solution for the first problem:

if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
    $arguments = "& '" +$myinvocation.mycommand.definition + "'"
    Start-Process powershell -Verb runAs -ArgumentList $arguments
    Break
}

These code opens a new instance of powershell with admin privilegs, But it opens a ps5. How can i open a ps6/ps7? if I cange it to Start-Process pwsh, the parameter -Verb runAs make an error.

Sorry for my bad english, and thank you for any help.

JudahA
  • 99
  • 1
  • 12
  • 1
    To launch PowerShell < 6 the executable is named **powershell.exe**. In version 6 and above, the executable name is **pwsh.exe**. Also, you should do `exit` instead of `break` to shut down the non-admin instance after relaunching with administrative permissions. And.. `New-Service` is also available in PowerShell 5.1 [see here](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/new-service?view=powershell-5.1) – Theo Nov 08 '21 at 09:48
  • @Theo, You are right about ```New-Service```, But there is other commands that not available. I edited my question following your comment. I know that every new command has old replacment, but i prefer to use new commands. – JudahA Nov 08 '21 at 10:40
  • 1
    But... Didn't you read the first line of my comment?. To launch PS > 5, use `pwsh.exe` in the `Start-Process` call. – Theo Nov 08 '21 at 11:04

1 Answers1

0

OK, @Theo help me to find the solution.

This is the installation script:

$scriptPath = $MyInvocation.MyCommand.Path

if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
  Start-Process pwsh -ArgumentList $scriptPath -Verb runAs
  exit
}

$scriptFolder = Split-Path $scriptPath
$projectPath = Split-Path $scriptFolder
$exePath = JOIN-Path $projectPath WorkerService1.exe
$name = "MyService"

New-Service -Name $name -BinaryPathName $exePath -StartupType Automatic
Start-Service -Name $name
Get-Service -Name $name
Read-Host -Prompt "Press Enter to exit"

And this is the uninstall script:

$scriptPath = $MyInvocation.MyCommand.Path

if (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
  Start-Process pwsh -ArgumentList $scriptPath -Verb runAs
  exit
}

$name = "MyService"
Stop-Service -Name $name
Remove-Service -Name $name
Read-Host -Prompt "Press Enter to exit"
Theo
  • 57,719
  • 8
  • 24
  • 41
JudahA
  • 99
  • 1
  • 12