For dotnetcore 3.1 Windows service how to stop, uninstall, install and start the service with a powershell script 5.1

376 views Asked by At

For starters i made the below script for PS 5.1 (i know that PS 6.0 has the Remove-Service option but not 5.1).

I have all the required .exe, dll's and config's along with this script that is packaged as an artifact and will be deployed on the Headnode directory of the target.

Not sure if the below script will uninstall and install the service. But i can see that it is deleting and starting the new service when i run it.**

```
$acl = Get-Acl "C:\Program Files\Matt\Wservice"
$aclRuleArgs = "XYZ", "Read,Write,ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($aclRuleArgs)
$acl.SetAccessRule($accessRule)
if (Get-Service "Wservice" -ErrorAction 'SilentlyContinue')
{
     Stop-Service -Name Wservice -ErrorAction SilentlyContinue -Force
     (Get-WmiObject -Class Win32_Service -filter "Name='Wservice'").delete()
     Write-Host "Please wait until removing the : Wservice  " 
     Start-Sleep -s 30 
    }
$Username = 'xyz'
$Password = '123'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$pass
New-Service -Name  Wservice -BinaryPathName "C:\Program Files\Matt\Wservice\Wservice.exe" -Credential $MySecureCreds -DisplayName "WserviceService"  -StartupType Automatic
Start-Service -Name "Wservice"
```
1

There are 1 answers

4
Wasif On
  • Powershell core 6.0/7.0 dosent seem to have get-wmiobject, WMI is depreceated, then we have to use CIM using Get-CIMInstance.

Rest all seem OK. Coreected code:

$acl = Get-Acl "C:\Program Files\Matt\Wservice"
$aclRuleArgs = "XYZ", "Read,Write,ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($aclRuleArgs)
$acl.SetAccessRule($accessRule)
if (Get-Service "Wservice" -ErrorAction 'SilentlyContinue')
{
     Stop-Service -Name Wservice -ErrorAction SilentlyContinue -Force
     (Get-CIMInstance -Class Win32_Service -filter "Name='Wservice'").delete()
     Write-Host "Please wait until removing the : Wservice  " 
     Start-Sleep -s 30 
    }
$Username = 'xyz'
$Password = '123'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$pass
New-Service -Name  Wservice -BinaryPathName "C:\Program Files\Matt\Wservice\Wservice.exe" -Credential $MySecureCreds -DisplayName "WserviceService"  -StartupType Automatic
Start-Service -Name "Wservice"