$binaryPath = "aValidPath"
$user = "aUser"
$passwrd = "aPassword"
$serviceName = "aService"
if (Get-Service $serviceName -ErrorAction SilentlyContinue)
{
# using WMI to remove Windows service because PowerShell does not have CmdLet for this
$serviceToRemove = Get-WmiObject -Class Win32_Service -Filter "name='$serviceName'"
$serviceToRemove | Stop-Service
Remove-WmiObject $serviceToRemove
}
$secured = ConvertTo-SecureString $passwrd -AsPlainText -Force
$creds = New-Object System.Management.Automation.PSCredential ($user, $secured)
New-Service -name $serviceName -binaryPathName $binaryPath -displayName $serviceName -startupType Automatic -credential $creds
Everytime I try to execute this code I get:
Remove-WmiObject: Specified argument was out of the range of valid values.
Parameter name: path
And I can't figure out why.
If you hover over "$serviceToRemove" you get:
\\*redacted*\root\cimv2:Win32_Service.Name="*redacted*"
PSComputerName:"*redacted*"
RunspaceId:*redacted*
PSShowComputerName:$false
the $binaryPath is absolute accurate, as the "New-Service" portion uses it just fine. Remove won't remove the service though cause of that error. And $serviceToRemove.delete() doesn't exist.
Every single example website I can find says to use this:
Remove-WmiObject $serviceToRemove
or
$serviceToRemove.delete()
the way I fixed this script was by using this syntax instead
Remove-WmiObject -path $serviceToRemove
I recently updated everything to the latest Powershell versions and am using the latest "Visual Studio Code" for this. Note: I got the same error messages using the oldschool ISE.