Not able to change the Service StartMode - windows

I am automating an application deployment.
After installing and starting the service via Choco, I am trying to change the Service StartMode to Auto, but I am getting 21 as the returnvalue and hence the mode is not changed.
PS C:\Windows\system32> $appservice = Get-WmiObject -Class Win32_Service -Filter "Name='<app_name>'"
PS C:\Windows\system32> $appservice.ChangeStartMode("Auto")
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 21
PSComputerName :
PS C:\Windows\system32> Get-WmiObject -Class Win32_Service -Filter "Name='<app_name>'"
ExitCode : 0
Name : <app_name>
ProcessId : 3180
StartMode : Manual
State : Running
Status : OK
Kindly help.
TIA

Try
Get-Service -Name 'TheServiceName' | Set-Service –StartupType Automatic

Related

Powershell: Register service with network-service account results in error 1068

I'm basically running this powershell-command (with an elevated powershell-prompt):
New-Service -name MyServiceName -binaryPathName "C:\myservice.exe -m myArgument" -Description "MyDescription" -displayName "MyDisplayName" -startupType Manual -credential $mycreds
Beforehand I run this to generate $mycreds (the service name is the correct name for network-service in german):
$login = "NT-AUTORITÄT\Netzwerkdienst"
$secpasswd = (new-object System.Security.SecureString)
$mycreds = New-Object System.Management.Automation.PSCredential ($login, $secpasswd)
When I now lookup the service in the windows service manager, I see this under its logon settings (the screenshot is in german but you can get that the credentials seem to have been passed correctly):
When I now start the service, I get this error:
1068: ...“the dependency service or group failed to start”.
This error makes no sense since there is no dependency to this service.
If I now however open up the logon-settings,
set them to "Local System"
click apply
set them to "account:" and enter the account name (NT-AUTORITÄT\Netzwerkdienst), also erasing the values in the boxes for "password" and "repeat password"
click OK
If I now try to start the service, it starts successfully.
However I need to get my service registered automatically so that it uses the networkservice-account.
Am I doing something wrong? Is there another way to do this?
Please also note that I already took care of giving the Network-service account the right to logon as a service before the actions stated in this question. The account does not just get the right to logon as a service because I manually entered the account name and accepted the messagebox that normally pops up to let me know that the account just received the right.
New! I've added this with which you could help me by trying it out yourself:
With this script you can test this out yourself by creating a service from notepad.exe:
$secpasswd = (new-object System.Security.SecureString)
$SID = [System.Security.Principal.WellKnownSidType]::NetworkServiceSid
$Account = new-object system.security.principal.securityidentifier($SID, $null)
$NetworkServiceName = $Account.Translate([system.security.principal.ntaccount]).value
$mycreds = New-Object System.Management.Automation.PSCredential ($NetworkServiceName, $secpasswd)
New-Service -Name test1 -BinaryPathName C:\Windows\System32\notepad.exe -Description testDescription -StartupType Manual -Credential $mycreds
Be sure to give the NetworkService account the right to logon as service though.
Do you get an error when starting the service afterwards? Is it the dependency error which makes no sense or is it something different?
You could try the Cim methods. they may help you get to what you need:
$Arguments = #{
DesktopInteract =$false ;
DisplayName = "notepad Test" ;
#ErrorControl =" " ;
#LoadOrderGroup =" " ;
#LoadOrderGroupDependencies =" " ;
Name ="Notepad" ;
PathName ="C:\Windows\System32\notepad.exe" ;
ServiceDependencies = $Null ;
#ServiceType = "Own Process"#[int32]16 ; #ownService
StartMode ="Manual" ;
StartName ="NT AUTHORITY\NetworkService" ;# ([System.Security.Principal.WellKnownSidType]::BuiltinAdministratorsSid).tostring() ;
#StartPassword = $Null
};
Invoke-CimMethod -ClassName win32_service -methodname Create -Arguments $Arguments
To remove the service via Cim:
$x =Get-CimInstance -ClassName win32_service -filter "name like '%note%'"
Invoke-CimMethod -InputObject $x -MethodName delete
Should you have errors refer to this page for what the error codes mean:
Errors on create can be found here (22) is the one I ran into until I figured out the right means.
https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/create-method-in-class-win32-service
To see how the items are set so you can get to your answer you need (except for the password):
Get-CimInstance -ClassName win32_service -filter 'Name like "%note%"' | select *
Name : Notepad
Status : OK
ExitCode : 0
DesktopInteract : False
ErrorControl : Ignore
PathName : C:\Windows\System32\notepad.exe
ServiceType : Own Process
StartMode : Manual
Caption : notepad Test
Description :
InstallDate :
CreationClassName : Win32_Service
Started : False
SystemCreationClassName : Win32_ComputerSystem
SystemName :
AcceptPause : False
AcceptStop : False
DisplayName : notepad Test
ServiceSpecificExitCode : 0
StartName : NT AUTHORITY\NetworkService
State : Stopped
TagId : 0
CheckPoint : 0
DelayedAutoStart : False
ProcessId : 0
WaitHint : 0
PSComputerName :
CimClass : root/cimv2:Win32_Service
CimInstanceProperties : {Caption, Description, InstallDate, Name...}
CimSystemProperties : Microsoft.Management.Infrastructure.CimSystemProperties

Uninstall Applications Via PowerShell

I have been working this for a couple days now, and no matter how I run this and work it, it seems to uninstall the program via PowerShell and returns the success code:
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 1
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ReturnValue : 0
PSComputerName :
This happens with various notoriously difficult to remove software such as McAfee.
The command being used is:
Get-WmiObject -Class win32_product -Filter "Name like '%McAfee%'" | ForEach-Object {$_.Uninstall()}
I've tried various scripts, solutions here, and variations of these (such as below).
$uninstall32 = gci "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall" | foreach { gp $_.PSPath } | ? { $_ -match "Yahoo Messenger" } | select UninstallString
$uninstall64 = gci "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" | foreach { gp $_.PSPath } | ? { $_ -match "Yahoo Messenger" } | select UninstallString
if ($uninstall64) {
$uninstall64 = $uninstall64.UninstallString -Replace "msiexec.exe","" -Replace "/I","" -Replace "/X",""
$uninstall64 = $uninstall64.Trim()
Write "Uninstalling (x64)..."
start-process "msiexec.exe" -arg "/X $uninstall64 /qb" -Wait
}
if ($uninstall32) {
$uninstall32 = $uninstall32.UninstallString -Replace "msiexec.exe","" -Replace "/I","" -Replace "/X",""
$uninstall32 = $uninstall32.Trim()
Write "Uninstalling (x32)..."
start-process "msiexec.exe" -arg "/X $uninstall32 /qb" -Wait}
Even something simple like Yahoo Messenger, the command fails to uninstall the application when run from a Powershell Window as Administrator yet returns a success code and/or is no longer present on the WMI application list.
You can check the MSIInstaller events to find a clue why the uninstall failed:
Get-WinEvent -computername <computername> -ProviderName MSIInstaller -Maxevents 30
You can also log the MSI activity with /le '<logfilepath>' added to your invocation of msiexec.exe and check the results.
I believe the msi install/uninstall operations are asynchronous. You may have to wait within your pssession until the install is finished.
McAfee Agent sometimes requires frminst.exe /forceuninsall to be removed.

Powershell: How to use Invoke-WmiMethod to Beep a Remote Computer?

I am trying to use the following code to make a beep on a remote computer through Powershell:
Invoke-WmiMethod -Path Win32_Process -Name Create -ArgumentList "[console]::beep(500,300)" -ComputerName "mycompname"
In addition I have used [System.Media.SystemSounds]::Beep.Play() in place of the console command.
It doesn't give any error codes and outputs this:
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH :
ProcessId :
ReturnValue : 9
PSComputerName :
I am running this command with elevated Powershell and I am an admin on the network. Using Invoke-Command DOES NOT work on my computer, so I am opting for Invoke-WmiMethod instead. The following code DOES actually work, so I don't understand why the beep one won't:
Invoke-WmiMethod -path Win32_Process -Name Create -ArgumentList "msg * 'hello'" -ComputerName "mycompname"
Final notes: I would like to be able to use Invoke-WmiMethod to do remote shutdown and taskkill, but those functions also do not work, only sending a message works. Any help would be greatly appreciated.
May be can you try this (modify username and password)
$Username = 'labuser'
$Password = 'labuser'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
Invoke-command –computername "mycompname" -credential $Cred –scriptblock {[console]::beep(500,300)}
TessellatingHeckler was right. I just needed to change the code so that the receiving computer knows that I am using powershell:
Invoke-WmiMethod -Path Win32_Process -Name Create -ArgumentList "powershell.exe [console]::beep(500,300)" -ComputerName "mycompname"
This also works for everything else:
Invoke-WmiMethod -Path Win32_Process -Name Create -ArgumentList "powershell.exe shutdown -s" -ComputerName "mycompname"
Thanks!

Unable to pipe cmdlet objects in cmd

i am using this powershell command to fetch a particular user profile
"Get-WmiObject -Class Win32_UserProfile | Where-Object {$_.LocalPath -eq 'C:\Users\Pela'}"
But when i am using this same command in cmd by invoking powershell i am getting
'Where-Object is not recognized as an internal or external command,operable program or batch file'
The command i am running in cmd is as follows :-
"powershell Get-WmiObject -Class Win32_UserProfile | Where-Object {$_.LocalPath -eq 'C:\Users\Pela'}"
I need to run this command from cmd only , i don't have any other options .
So please give me an alternative to "Where-Object"
So please give me an alternative to "Where-Object"
powershell Get-WmiObject -Class Win32_UserProfile | Where-Object {$_.LocalPath -eq 'C:\Users\Pela
You don't need an alternative. The above command is failing because the pipe | is being interpreted by the cmd shell and not by PowerShell.
If you escape the pipe ^| then the piping is done by the PowerShell command as expected:
powershell Get-WmiObject -Class Win32_UserProfile ^| Where-Object {$_.LocalPath -eq 'C:\Users\Pela
Example:
F:\test>powershell Get-WmiObject -Class Win32_UserProfile ^| Where-Object {$_.LocalPath -eq 'C:\Users\DavidPostill'}
__GENUS : 2
__CLASS : Win32_UserProfile
__SUPERCLASS :
__DYNASTY : Win32_UserProfile
__RELPATH : Win32_UserProfile.SID="S-1-5-21-1699878757-1063190524-3119395976-1000"
__PROPERTY_COUNT : 12
__DERIVATION : {}
__SERVER : HAL
__NAMESPACE : root\cimv2
__PATH : \\HAL\root\cimv2:Win32_UserProfile.SID="S-1-5-21-1699878757-1063190524-3119395976-1000"
LastDownloadTime :
LastUploadTime :
LastUseTime : 20160822200129.697000+000
Loaded : True
LocalPath : C:\Users\DavidPostill
RefCount : 146
RoamingConfigured : False
RoamingPath :
RoamingPreference :
SID : S-1-5-21-1699878757-1063190524-3119395976-1000
Special : False
Status : 0
PSComputerName : HAL
Further Reading
An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
syntax - Escape Characters, Delimiters and Quotes.

Capturing the output from COM port using PowerShell on Windows 7

I want to send Sierra AT commands to a COM port and capture the output and store it in a variable using PowerShell.
PowerShell version:
Name : ConsoleHost
Version : 2.0
InstanceId : eb5987f0-9961-4842-b349-ba215d86fdfa
UI : System.Management.Automation.Internal.Host.InternalHostUserI
nterface
CurrentCulture : en-IN
CurrentUICulture : en-US
PrivateData : Microsoft.PowerShell.ConsoleHost+ConsoleColorProxy
IsRunspacePushed : False
Runspace : System.Management.Automation.Runspaces.LocalRunspace
For example:
at!gstatus?
I tried this, but it's not working for me.
PS> [System.IO.Ports.SerialPort]::getportnames()
COM16
PS> $port= new-Object System.IO.Ports.SerialPort COM16,115200,None,8,one
PS> $port.open()
PS> $port.WriteLine("at!gstatus?")
PS> $port.WriteLine("`r")
PS> $port.ReadExisting() //getting null output
PS> $port.close()
How can this be done?
Modem ? COM port ? AT commands ? Is it 2015 or 1995 ? ^_^
Try with a pause before reading the data:
$port = New-Object System.IO.Ports.SerialPort COM16,115200,None,8,one
$port.Open()
$port.WriteLine( "at!gstatus?" + "`r" )
Start-Sleep -m 50
$port.ReadExisting()
$port.Close()
Source : https://social.technet.microsoft.com/Forums/en-US/2980f24e-56d1-431f-aedc-811c087b5184/powershell-serial-com-port?forum=ITCG

Resources