Powershell - Create GPO firewall rule for WMI - windows

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

Related

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

DNS Search suffix is being ignored

I'm on a Windows 10 laptop and am receiving the following behaviour:
When I check the DNS Search Suffix List:
PS C:\> Get-DnsClientGlobalSetting
UseSuffixSearchList : True
SuffixSearchList : {domain1.co.uk, domain2.com, domain3.box}
UseDevolution : True
DevolutionLevel : 0
When I resolve the hostname without the suffix:
PS C:\> Resolve-DnsName -Name hostname1
Resolve-DnsName : hostname1 : DNS name does not exist
At line:1 char:1
+ Resolve-DnsName -Name hostname1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (hostname1:String) [Resolve-DnsName], Win32Exception
+ FullyQualifiedErrorId : DNS_ERROR_RCODE_NAME_ERROR,Microsoft.DnsClient.Commands.ResolveDnsName
When I resolve the hostname with the suffix manually specified:
PS C:\> Resolve-DnsName -Name hostname1.domain2.com
Name Type TTL Section IPAddress
---- ---- --- ------- ---------
hostname1.domain2.com A 300 Answer 10.10.10.234
hostname1.domain2.com A 300 Answer 10.10.11.197
Why isn't the suffix "domain2.com" being used to resolve "hostname1" to the IP addresses, as is possible when the suffix is added manually? This should be hapenning automatically, shouldn't it?
I've tried running
ipconfig /flushdns
And I've tried restarting, but it still won't take. What's happening here?
Note: The domain2.com suffix is added automatically when I connect to an Open VPN endpoint, and is specified in the OpenVPN configuration file as:
dhcp-option DOMAIN domain2.com
I've seen posts saying that it's to do with the binding order, and that you can solve this (DNS leak) by increasing the metric for the VPC NIC, so I wrote a script to increase the metric of that card to be the highest out of all cards:
$HighestMetric = ((Get-NetIPInterface).InterfaceMetric | Sort-Object -Descending)[0]
$VpcAdapter = Get-NetAdapter | Where-Object -Property InterfaceDescription -Match "TAP"
$currentMetric = (Get-NetIPInterface -InterfaceAlias $VpcAdapter.InterfaceAlias -AddressFamily IPv4).InterfaceMetric
Set-NetIPInterface -InterfaceAlias $VpcAdapter.InterfaceAlias -InterfaceMetric ($HighestMetric +1)
But that still hasn't solved the issue

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

Can't install CredentialManager module in Powershell 5

I'm on a Windows Server 2019 can I can't install the CredentialManager with PowerShell.
PS C:\> Install-Module CredentialManager
I get the following error:
PackageManagement\Install-Package : No match was found for the specified search criteria and module name 'CredentialManager'. Try Get-PSRepository to see all available registered module
repositories.
At C:\Program Files\WindowsPowerShell\Modules\PowerShellGet\1.0.0.1\PSModule.psm1:1809 char:21
+ ... $null = PackageManagement\Install-Package #PSBoundParameters
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Microsoft.Power....InstallPackage:InstallPackage) [Install-Package], Exception
+ FullyQualifiedErrorId : NoMatchFoundForCriteria,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage
I used the same command on Windows 2012 with PowerShell v5 and it works. Ideas?
I was behind a corporate firewall that was preventing this. Once I set up the the proxy, I was able to install PSGallery.
$proxyhost = "your-proxy-url.com"
$proxyport = "1234"
$proxy = "$proxyhost" + ":" + $proxyport
$proxyurl = "http://" + "$proxy"
$proxyuser = "proxy-user"
$proxypwd = "proxy-pwd
# set up proxy credentials
$secPasswd = ConvertTo-SecureString $proxypwd -AsPlainText -Force
$credential = New-Object PSCredential($proxyuser, $secPasswd)
# Set up proxy with netsh
netsh winhttp set proxy proxy-server=$proxy bypass-list=$bypassList
# Recovering the PsGallery Repository behind a Corporate Proxy
[system.net.webrequest]::defaultwebproxy = new-object system.net.webproxy($proxyurl)
[system.net.webrequest]::defaultwebproxy.credentials = $credential
[system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true
if(!(Get-PSRepository "PSGallery")) {
Register-PSRepository -Name "PSGallery" –SourceLocation "https://www.powershellgallery.com/api/v2/" -InstallationPolicy Trusted
}

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