Capturing the output from COM port using PowerShell on Windows 7 - windows

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

Related

Powershell - Create GPO firewall rule for WMI

I want to create below GPO Firewall rules via Powershell
Here are properties of existing rules (i want to create with powershell)
Get-NetFirewallRule | where {$_.Name -like "WMI*"}
Name : WMI-RPCSS-In-TCP
DisplayName : Windows Management Instrumentation (DCOM-In)
Description : Inbound rule to allow DCOM traffic for remote Windows Management Instrumentation. [TCP 135]
DisplayGroup : Windows Management Instrumentation (WMI)
Group : #FirewallAPI.dll,-34251
Enabled : True
Profile : Domain, Private, Public
Platform : {}
Direction : Inbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Name : WMI-ASYNC-In-TCP
DisplayName : Windows Management Instrumentation (ASync-In)
Description : Inbound rule to allow Asynchronous WMI traffic for remote Windows Management Instrumentation. [TCP]
DisplayGroup : Windows Management Instrumentation (WMI)
Group : #FirewallAPI.dll,-34251
Enabled : True
Profile : Domain, Private, Public
Platform : {}
Direction : Inbound
Action : Allow
EdgeTraversalPolicy : Block
LooseSourceMapping : False
LocalOnlyMapping : False
Owner :
PrimaryStatus : OK
Status : The rule was parsed successfully from the store. (65536)
EnforcementStatus : NotApplicable
PolicyStoreSource : PersistentStore
PolicyStoreSourceType : Local
Here is my code for creating one of those rules
$GpoName = "Global-WinRM"
$PolicyStoreName = "abc.com\" + $GpoName
$GpoSessionName = Open-NetGPO –PolicyStore $PolicyStoreName
New-NetFirewallRule -Name "Windows Management I" -DisplayName "Windows Management Instrumentation (ASync-In)" -DisplayGroup "Windows Management Instrumentation (WMI)" -Group "%systemroot%\system32\wbem\unsecapp.exe" -Profile Domain -Action Allow -GPOSession $GpoSessionName -Verbose
Error:
New-NetFirewallRule : The system cannot find the file specified.
At line:1 char:1
New-NetFirewallRule -Name "Windows Management I" -DisplayName "Window ...
+ CategoryInfo : ObjectNotFound: (MSFT_NetFirewallRule:root/standardcimv2/MSFT_NetFirewallRule) [New-NetFirewallRule], CimException
+ FullyQualifiedErrorId : Windows System Error 2,New-NetFirewallRule
forgot to add -Program argument
$GpoName = "Global-WinRM"
$PolicyStoreName = "abc.com\" + $GpoName
$GpoSessionName = Open-NetGPO –PolicyStore $PolicyStoreName
New-NetFirewallRule -Name "Windows Management I" -DisplayName "Windows Management Instrumentation (ASync-In)" -Group "#FirewallAPI.dll,-34251" -Program "%systemroot%\system32\wbem\unsecapp.exe" -Profile Domain -Action Allow -GPOSession $GpoSessionName -Verbose
Save-NetGPO -GPOSession $GpoSessionName

Not able to change the Service StartMode

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

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.

Unable to run PowerShell script in Windows 2008 R2 Standard which is installed by Vagrant

I am unable to run this PowerShell script
# Execute .exe file
Get-ChildItem "C:\vagrant" -Filter *.exe | Where Name -NotMatch '.*NoDB\.exe$' | % {
New-Object psobject -Property #{
No = [int]([regex]::Match($_.Name, '(?<=CL)\d+').Value)
Name = $_.FullName
}
} | Sort No -Descending | Select -ExpandProperty Name -First 1 |
Foreach { & $_ -s2 -sp"-SilentInstallation=server -UpdateMaterials=yestoall -UpgradeDBIfRequired=yes"}
in Windows Windows 2008 R2 Standard because
**********************
Windows PowerShell Transcript Start
Start time: 20160719080730
Username : VAGRANT-2008R2\vagrant
Machine : VAGRANT-2008R2 (Microsoft Windows NT 6.1.7601 Service Pack 1)
**********************
Transcript started, output file is C:\Users\vagrant\Documents\PowerShell_transc
ript.20160719080730.txt
Where-Object : Cannot bind parameter 'FilterScript'. Cannot convert the "Name"
value of type "System.String" to type "System.Management.Automation.ScriptBlock
".
At C:\vagrant\Install_Ortho.ps1:7 char:49
+ Get-ChildItem "C:\vagrant" -Filter *.exe | Where <<<< Name -NotMatch '.*NoDB
\.exe$' | % {
+ CategoryInfo : InvalidArgument: (:) [Where-Object], ParameterBi
ndingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerSh
ell.Commands.WhereObjectCommand
**********************
Windows PowerShell Transcript End
End time: 20160719080730
**********************
I tried to use this advice "Try using {} instead of parentheses around your argument." Same error.
This syntax:
Where Property -[OperatorAsParameterName] 'value'
is introduced in PowerShell 3.0 - Windows 2008 R2 comes with PowerShell 2.0!
The version 2.0 equivalent would be:
Where {$_.Name -NotMatch '.*NoDB\.exe$'}
You may fix that one instance, but then other parts of the scripts will likely going to fail, and you have to keep fixing version 3.0 syntax until you've rewritten the entire thing
I would recommend finding a 2008R2-specific version of Vagrant, or filing this finding as a compatibility bug with their development team

Resources