How to read from a text file when adding firewall rules using new-netfirewallrule - powershell-4.0

I am trying to create a script to read from a text file to which I would like to add firewall rules to each server on a line by line basis.
It doesn't seem like it is reading it line by line, and it looks to only take the first line that I put in.
$ComputersPath = "C:\temp\kofaxcomputers.txt"
Get-Content $ComputersPath | ForEach {
if ($ComputersPath -ne $null) {
New-NetFirewallRule -DisplayName "Kofax - KTM" -Direction Inbound -RemoteAddress Any -Action Allow -Protocol TCP -LocalPort 2424
Write-Host "$_ installed" -ForegroundColor Green;
} else {
Write-Host "$_ failed" -ForegroundColor Red;
}}

If you are trying to create a firewall rule in a bunch of computers,
Have a list of computer in you text file(make sure there are no trailing spaces)
Read all the computers from the text file and save it in a variable.
Use Invoke-command to execute the New-NetFireWallRule on all those computers.
$Computers = get-Content -Path "C:\temp\kofaxcomputers.txt"
Invoke-Command -ComputerName $Computers -ScriptBlock {
New-NetFirewallRule -DisplayName "Kofax - KTM" -Direction Inbound -RemoteAddress Any -Action Allow -Protocol TCP -LocalPort 2424
}

Related

Powershell New-NetFirewallRule with -LocalUser example

How to create Firewall rule which will be impacting only one of the local accounts
In theory below example would be sufficient however Im missing value for parameter "-LocalUser"
Below PowerShell command
New-NetFirewallRule -DisplayName "BLOCKWWW" -Direction Outbound -LocalPort 80,443 -Protocol TCP -Action Block -LocalUser **WHATGOESHERE**
Judging from the examples showing how to use other parameters with similar descriptions (like RemoteUser), it'll take a discretionary ACL in SDDL with a single entry per user.
You could write a small helper function to generate these based on username:
function Get-FirewallLocalUserSddl {
param(
[string[]]$UserName
)
$SDDL = 'D:{0}'
$ACEs = foreach($Name in $UserName){
try{
$LocalUser = Get-LocalUser -Name $UserName -ErrorAction Stop
'(A;;CC;;;{0})' -f $LocalUser.Sid.Value
}
catch{
Write-Warning "Local user '$Username' not found"
continue
}
}
return $SDDL -f ($ACEs -join '')
}
Then use it like:
New-NetFirewallRule -DisplayName "BLOCKWWW" -LocalUser (Get-FirewallLocalUserSddl user1,user2) -Direction Outbound -LocalPort 80,443 -Protocol TCP -Action Block
$user = new-object System.Security.Principal.NTAccount ("corp.contoso.com\Administrators")
$SIDofSecureUserGroup = $user.Translate([System.Security.Principal.SecurityIdentifier]).Value
$secureUserGroup = "D:(A;;CC;;;$SIDofSecureUserGroup)"

find process that is blocking a port on windows

I am trying to connect remote mssql server, but something on my machine is blocking the required 1433 port.
How to find what process/program is blocking outgoing traffic on that port.
All firewall/antiviruses are disabled.
From the command line:
netstat -a -b
..will show you which exe 'owns' a port.
In PowerShell, Get-NetworkStatistics:
#dot source the script (or add to your profile or a custom module):
. "\\path\to\Get-NetworkStatistics.ps1"
#Run Get-NetworkStatistics against exampleComputer, format results in an autosized table
Get-NetworkStatistics -computername exampleComputer | Format-Table -autosize
#Get help on Get-NetworkStatistics
Get-Help Get-NetworkStatistics -Full
#Run get-networkstatistics against k-it-thin-02. Show only results for the Chrome process. If possible, show host names rather than IP addresses. Format in a table.
Get-NetworkStatistics chrome -computername k-it-thin-02 -ShowHostNames | Format-Table
#Get all processes in the listening state using TCP
Get-NetworkStatistics -State LISTENING -Protocol tcp
Code for Get-NetworkStatistics.ps1 below:
function Get-NetworkStatistics {
<#
.SYNOPSIS
Display current TCP/IP connections for local or remote system
.FUNCTIONALITY
Computers
.DESCRIPTION
Display current TCP/IP connections for local or remote system. Includes the process ID (PID) and process name for each connection.
If the port is not yet established, the port number is shown as an asterisk (*).
.PARAMETER ProcessName
Gets connections by the name of the process. The default value is '*'.
.PARAMETER Port
The port number of the local computer or remote computer. The default value is '*'.
.PARAMETER Address
Gets connections by the IP address of the connection, local or remote. Wildcard is supported. The default value is '*'.
.PARAMETER Protocol
The name of the protocol (TCP or UDP). The default value is '*' (all)
.PARAMETER State
Indicates the state of a TCP connection. The possible states are as follows:
Closed - The TCP connection is closed.
Close_Wait - The local endpoint of the TCP connection is waiting for a connection termination request from the local user.
Closing - The local endpoint of the TCP connection is waiting for an acknowledgement of the connection termination request sent previously.
Delete_Tcb - The transmission control buffer (TCB) for the TCP connection is being deleted.
Established - The TCP handshake is complete. The connection has been established and data can be sent.
Fin_Wait_1 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint or for an acknowledgement of the connection termination request sent previously.
Fin_Wait_2 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint.
Last_Ack - The local endpoint of the TCP connection is waiting for the final acknowledgement of the connection termination request sent previously.
Listen - The local endpoint of the TCP connection is listening for a connection request from any remote endpoint.
Syn_Received - The local endpoint of the TCP connection has sent and received a connection request and is waiting for an acknowledgment.
Syn_Sent - The local endpoint of the TCP connection has sent the remote endpoint a segment header with the synchronize (SYN) control bit set and is waiting for a matching connection request.
Time_Wait - The local endpoint of the TCP connection is waiting for enough time to pass to ensure that the remote endpoint received the acknowledgement of its connection termination request.
Unknown - The TCP connection state is unknown.
Values are based on the TcpState Enumeration:
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.tcpstate%28VS.85%29.aspx
Cookie Monster - modified these to match netstat output per here:
http://support.microsoft.com/kb/137984
.PARAMETER ComputerName
If defined, run this command on a remote system via WMI. \\computername\c$\netstat.txt is created on that system and the results returned here
.PARAMETER ShowHostNames
If specified, will attempt to resolve local and remote addresses.
.PARAMETER tempFile
Temporary file to store results on remote system. Must be relative to remote system (not a file share). Default is "C:\netstat.txt"
.PARAMETER AddressFamily
Filter by IP Address family: IPv4, IPv6, or the default, * (both).
If specified, we display any result where both the localaddress and the remoteaddress is in the address family.
.EXAMPLE
Get-NetworkStatistics | Format-Table
.EXAMPLE
Get-NetworkStatistics iexplore -computername k-it-thin-02 -ShowHostNames | Format-Table
.EXAMPLE
Get-NetworkStatistics -ProcessName md* -Protocol tcp
.EXAMPLE
Get-NetworkStatistics -Address 192* -State LISTENING
.EXAMPLE
Get-NetworkStatistics -State LISTENING -Protocol tcp
.EXAMPLE
Get-NetworkStatistics -Computername Computer1, Computer2
.EXAMPLE
'Computer1', 'Computer2' | Get-NetworkStatistics
.OUTPUTS
System.Management.Automation.PSObject
.NOTES
Author: Shay Levy, code butchered by Cookie Monster
Shay's Blog: http://PowerShay.com
Cookie Monster's Blog: http://ramblingcookiemonster.github.io/
.LINK
http://gallery.technet.microsoft.com/scriptcenter/Get-NetworkStatistics-66057d71
#>
[OutputType('System.Management.Automation.PSObject')]
[CmdletBinding()]
param(
[Parameter(Position=0)]
[System.String]$ProcessName='*',
[Parameter(Position=1)]
[System.String]$Address='*',
[Parameter(Position=2)]
$Port='*',
[Parameter(Position=3,
ValueFromPipeline = $True,
ValueFromPipelineByPropertyName = $True)]
[System.String[]]$ComputerName=$env:COMPUTERNAME,
[ValidateSet('*','tcp','udp')]
[System.String]$Protocol='*',
[ValidateSet('*','Closed','Close_Wait','Closing','Delete_Tcb','DeleteTcb','Established','Fin_Wait_1','Fin_Wait_2','Last_Ack','Listening','Syn_Received','Syn_Sent','Time_Wait','Unknown')]
[System.String]$State='*',
[switch]$ShowHostnames,
[switch]$ShowProcessNames = $true,
[System.String]$TempFile = "C:\netstat.txt",
[validateset('*','IPv4','IPv6')]
[string]$AddressFamily = '*'
)
begin{
#Define properties
$properties = 'ComputerName','Protocol','LocalAddress','LocalPort','RemoteAddress','RemotePort','State','ProcessName','PID'
#store hostnames in array for quick lookup
$dnsCache = #{}
}
process{
foreach($Computer in $ComputerName) {
#Collect processes
if($ShowProcessNames){
Try {
$processes = Get-Process -ComputerName $Computer -ErrorAction stop | select name, id
}
Catch {
Write-warning "Could not run Get-Process -computername $Computer. Verify permissions and connectivity. Defaulting to no ShowProcessNames"
$ShowProcessNames = $false
}
}
#Handle remote systems
if($Computer -ne $env:COMPUTERNAME){
#define command
[string]$cmd = "cmd /c c:\windows\system32\netstat.exe -ano >> $tempFile"
#define remote file path - computername, drive, folder path
$remoteTempFile = "\\{0}\{1}`${2}" -f "$Computer", (split-path $tempFile -qualifier).TrimEnd(":"), (Split-Path $tempFile -noqualifier)
#delete previous results
Try{
$null = Invoke-WmiMethod -class Win32_process -name Create -ArgumentList "cmd /c del $tempFile" -ComputerName $Computer -ErrorAction stop
}
Catch{
Write-Warning "Could not invoke create win32_process on $Computer to delete $tempfile"
}
#run command
Try{
$processID = (Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $cmd -ComputerName $Computer -ErrorAction stop).processid
}
Catch{
#If we didn't run netstat, break everything off
Throw $_
Break
}
#wait for process to complete
while (
#This while should return true until the process completes
$(
try{
get-process -id $processid -computername $Computer -ErrorAction Stop
}
catch{
$FALSE
}
)
) {
start-sleep -seconds 2
}
#gather results
if(test-path $remoteTempFile){
Try {
$results = Get-Content $remoteTempFile | Select-String -Pattern '\s+(TCP|UDP)'
}
Catch {
Throw "Could not get content from $remoteTempFile for results"
Break
}
Remove-Item $remoteTempFile -force
}
else{
Throw "'$tempFile' on $Computer converted to '$remoteTempFile'. This path is not accessible from your system."
Break
}
}
else{
#gather results on local PC
$results = netstat -ano | Select-String -Pattern '\s+(TCP|UDP)'
}
#initialize counter for progress
$totalCount = $results.count
$count = 0
#Loop through each line of results
foreach($result in $results) {
$item = $result.line.split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)
if($item[1] -notmatch '^\[::'){
#parse the netstat line for local address and port
if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6'){
$localAddress = $la.IPAddressToString
$localPort = $item[1].split('\]:')[-1]
}
else {
$localAddress = $item[1].split(':')[0]
$localPort = $item[1].split(':')[-1]
}
#parse the netstat line for remote address and port
if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6'){
$remoteAddress = $ra.IPAddressToString
$remotePort = $item[2].split('\]:')[-1]
}
else {
$remoteAddress = $item[2].split(':')[0]
$remotePort = $item[2].split(':')[-1]
}
#Filter IPv4/IPv6 if specified
if($AddressFamily -ne "*")
{
if($AddressFamily -eq 'IPv4' -and $localAddress -match ':' -and $remoteAddress -match ':|\*' )
{
#Both are IPv6, or ipv6 and listening, skip
Write-Verbose "Filtered by AddressFamily:`n$result"
continue
}
elseif($AddressFamily -eq 'IPv6' -and $localAddress -notmatch ':' -and ( $remoteAddress -notmatch ':' -or $remoteAddress -match '*' ) )
{
#Both are IPv4, or ipv4 and listening, skip
Write-Verbose "Filtered by AddressFamily:`n$result"
continue
}
}
#parse the netstat line for other properties
$procId = $item[-1]
$proto = $item[0]
$status = if($item[0] -eq 'tcp') {$item[3]} else {$null}
#Filter the object
if($remotePort -notlike $Port -and $localPort -notlike $Port){
write-verbose "remote $Remoteport local $localport port $port"
Write-Verbose "Filtered by Port:`n$result"
continue
}
if($remoteAddress -notlike $Address -and $localAddress -notlike $Address){
Write-Verbose "Filtered by Address:`n$result"
continue
}
if($status -notlike $State){
Write-Verbose "Filtered by State:`n$result"
continue
}
if($proto -notlike $Protocol){
Write-Verbose "Filtered by Protocol:`n$result"
continue
}
#Display progress bar prior to getting process name or host name
Write-Progress -Activity "Resolving host and process names"`
-Status "Resolving process ID $procId with remote address $remoteAddress and local address $localAddress"`
-PercentComplete (( $count / $totalCount ) * 100)
#If we are running showprocessnames, get the matching name
if($ShowProcessNames -or $PSBoundParameters.ContainsKey -eq 'ProcessName'){
#handle case where process spun up in the time between running get-process and running netstat
if($procName = $processes | Where {$_.id -eq $procId} | select -ExpandProperty name ){ }
else {$procName = "Unknown"}
}
else{$procName = "NA"}
if($procName -notlike $ProcessName){
Write-Verbose "Filtered by ProcessName:`n$result"
continue
}
#if the showhostnames switch is specified, try to map IP to hostname
if($showHostnames){
$tmpAddress = $null
try{
if($remoteAddress -eq "127.0.0.1" -or $remoteAddress -eq "0.0.0.0"){
$remoteAddress = $Computer
}
elseif($remoteAddress -match "\w"){
#check with dns cache first
if ($dnsCache.containskey( $remoteAddress)) {
$remoteAddress = $dnsCache[$remoteAddress]
write-verbose "using cached REMOTE '$remoteAddress'"
}
else{
#if address isn't in the cache, resolve it and add it
$tmpAddress = $remoteAddress
$remoteAddress = [System.Net.DNS]::GetHostByAddress("$remoteAddress").hostname
$dnsCache.add($tmpAddress, $remoteAddress)
write-verbose "using non cached REMOTE '$remoteAddress`t$tmpAddress"
}
}
}
catch{ }
try{
if($localAddress -eq "127.0.0.1" -or $localAddress -eq "0.0.0.0"){
$localAddress = $Computer
}
elseif($localAddress -match "\w"){
#check with dns cache first
if($dnsCache.containskey($localAddress)){
$localAddress = $dnsCache[$localAddress]
write-verbose "using cached LOCAL '$localAddress'"
}
else{
#if address isn't in the cache, resolve it and add it
$tmpAddress = $localAddress
$localAddress = [System.Net.DNS]::GetHostByAddress("$localAddress").hostname
$dnsCache.add($localAddress, $tmpAddress)
write-verbose "using non cached LOCAL '$localAddress'`t'$tmpAddress'"
}
}
}
catch{ }
}
#Write the object
New-Object -TypeName PSObject -Property #{
ComputerName = $Computer
PID = $procId
ProcessName = $procName
Protocol = $proto
LocalAddress = $localAddress
LocalPort = $localPort
RemoteAddress =$remoteAddress
RemotePort = $remotePort
State = $status
} | Select-Object -Property $properties
#Increment the progress counter
$count++
}
}
}
}
}

Powershell Automation for Services

I have 100+ servers for which I have to check services. On almost 5 servers we have identical services. Each boxes contains min of 3 services.
I am importing content from the file I saved in a location. For Server name I am good. For Service I have saved like service_starting_name* in column under the file like below
AA*
BB*
CC*
Below is the code. Is this good idea for automation as per below code ?
$ServerName = Get-Content "Absolutepath"
$Service = Get-Content "Absolutepath"
foreach ($Server in $ServerName) {
write-host $($server)
Get-Service -ComputerName $Server $Service
}
Also , How can we do a better display like, without printing the service name ?
Suppose, In Server X , 5 services , so if all services are running just print all good on that server.
I tried using if conditions but as there are many services , it is printing multiple times because for for each loop .
Please suggest.
You can play around with various things..
For testing I use localhost, when you try:
Get-Service -ComputerName localhost -DisplayName *sophos*
You get:
(Get-Service -ComputerName localhost -DisplayName *sophos*).count
result 10
(Get-Service -ComputerName localhost -DisplayName *sophos*).Status -contains "stopped"
result True
So if you use:
if (!((Get-Service -ComputerName localhost -DisplayName *sophos*).Status -contains stopped)) { Write-Host "Localhost: All ok" }
Or:
if (!(Get-Service -ComputerName $server -DisplayName $Service | select status | where {$_.Status -like "Stopped"})) { Write-Host "$($Server): All OK" }
You can use various checks for services "stopping" or whatever..
The above are just to give you ideas!
Hope it helps.

How to run internal Powershell script function from cmd.exe with arguments

I want to use a powershell (.ps1) script in the command prompt without using this commands
Powershell.exe -noexit Set-ExecutionPolicy Unrestricted -file "C:\Get-NetworkStatistics.ps1"
Currently this command opens powershell windows. I want direct cmd to use this script and giving me output. Is it possible?
Below is my Get-NetworkStatistics.ps1 script. please guide me is there any way to use it directly?
function Get-NetworkStatistics {
<#
.SYNOPSIS
Display current TCP/IP connections for local or remote system
.FUNCTIONALITY
Computers
.DESCRIPTION
Display current TCP/IP connections for local or remote system. Includes the process ID (PID) and process name for each connection.
If the port is not yet established, the port number is shown as an asterisk (*).
.PARAMETER ProcessName
Gets connections by the name of the process. The default value is '*'.
.PARAMETER Port
The port number of the local computer or remote computer. The default value is '*'.
.PARAMETER Address
Gets connections by the IP address of the connection, local or remote. Wildcard is supported. The default value is '*'.
.PARAMETER Protocol
The name of the protocol (TCP or UDP). The default value is '*' (all)
.PARAMETER State
Indicates the state of a TCP connection. The possible states are as follows:
Closed - The TCP connection is closed.
Close_Wait - The local endpoint of the TCP connection is waiting for a connection termination request from the local user.
Closing - The local endpoint of the TCP connection is waiting for an acknowledgement of the connection termination request sent previously.
Delete_Tcb - The transmission control buffer (TCB) for the TCP connection is being deleted.
Established - The TCP handshake is complete. The connection has been established and data can be sent.
Fin_Wait_1 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint or for an acknowledgement of the connection termination request sent previously.
Fin_Wait_2 - The local endpoint of the TCP connection is waiting for a connection termination request from the remote endpoint.
Last_Ack - The local endpoint of the TCP connection is waiting for the final acknowledgement of the connection termination request sent previously.
Listen - The local endpoint of the TCP connection is listening for a connection request from any remote endpoint.
Syn_Received - The local endpoint of the TCP connection has sent and received a connection request and is waiting for an acknowledgment.
Syn_Sent - The local endpoint of the TCP connection has sent the remote endpoint a segment header with the synchronize (SYN) control bit set and is waiting for a matching connection request.
Time_Wait - The local endpoint of the TCP connection is waiting for enough time to pass to ensure that the remote endpoint received the acknowledgement of its connection termination request.
Unknown - The TCP connection state is unknown.
Values are based on the TcpState Enumeration:
http://msdn.microsoft.com/en-us/library/system.net.networkinformation.tcpstate%28VS.85%29.aspx
Cookie Monster - modified these to match netstat output per here:
http://support.microsoft.com/kb/137984
.PARAMETER ComputerName
If defined, run this command on a remote system via WMI. \\computername\c$\netstat.txt is created on that system and the results returned here
.PARAMETER ShowHostNames
If specified, will attempt to resolve local and remote addresses.
.PARAMETER tempFile
Temporary file to store results on remote system. Must be relative to remote system (not a file share). Default is "C:\netstat.txt"
.EXAMPLE
Get-NetworkStatistics | Format-Table
.EXAMPLE
Get-NetworkStatistics iexplore -computername k-it-thin-02 -ShowHostNames | Format-Table
.EXAMPLE
Get-NetworkStatistics -ProcessName md* -Protocol tcp
.EXAMPLE
Get-NetworkStatistics -Address 192* -State LISTENING
.EXAMPLE
Get-NetworkStatistics -State LISTENING -Protocol tcp
.OUTPUTS
System.Management.Automation.PSObject
.NOTES
Author: Shay Levy, code butchered by Cookie Monster
Shay's Blog: http://PowerShay.com
Cookie Monster's Blog: http://ramblingcookiemonster.wordpress.com
.LINK
http://gallery.technet.microsoft.com/scriptcenter/Get-NetworkStatistics-66057d71
#>
[OutputType('System.Management.Automation.PSObject')]
[CmdletBinding(DefaultParameterSetName='name')]
param(
[Parameter(Position=0, ValueFromPipeline=$true,ParameterSetName='name')]
[System.String]$ProcessName='*',
[Parameter(Position=0, ValueFromPipeline=$true,ParameterSetName='address')]
[System.String]$Address='*',
[Parameter(ValueFromPipeline=$true,ParameterSetName='port')]
$Port='*',
[Parameter()]
[ValidateSet('*','tcp','udp')]
[System.String]$Protocol='*',
[Parameter()]
[ValidateSet('*','Closed','Close_Wait','Closing','Delete_Tcb','DeleteTcb','Established','Fin_Wait_1','Fin_Wait_2','Last_Ack','Listening','Syn_Received','Syn_Sent','Time_Wait','Unknown')]
[System.String]$State='*',
[Parameter(ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
[validatescript({test-connection -count 2 -buffersize 16 -quiet -ComputerName $_})]
[System.String]$computername=$env:COMPUTERNAME,
[switch]$ShowHostnames,
[switch]$ShowProcessNames = $true,
[System.String]$tempFile = "C:\netstat.txt"
)
begin{
#Define properties
$properties = 'Protocol','LocalAddress','LocalPort','RemoteAddress','RemotePort','State','ProcessName','PID'
#Collect processes
if($ShowProcessNames){
Try {
$processes = get-process -computername $computername -ErrorAction stop | select name, id
}
Catch {
Write-warning "Could not run Get-Process -computername $computername. Verify permissions and connectivity. Defaulting to no ShowProcessNames"
$ShowProcessNames = $false
}
}
#store hostnames in array for quick lookup
$dnsCache = #()
}
process{
#Handle remote systems
if($computername -ne $env:COMPUTERNAME){
#define command
[string]$cmd = "cmd /c c:\windows\system32\netstat.exe -ano >> $tempFile"
#define remote file path - computername, drive, folder path
$remoteTempFile = "\\{0}\{1}`${2}" -f "$computername", (split-path $tempFile -qualifier).TrimEnd(":"), (Split-Path $tempFile -noqualifier)
#delete previous results
Try{
$null = Invoke-WmiMethod -class Win32_process -name Create -ArgumentList "cmd /c del $tempFile" -ComputerName $computername -ErrorAction stop
}
Catch{
Write-Warning "Could not invoke create win32_process on $computername to delete $tempfile"
}
#run command
Try{
$processID = (Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $cmd -ComputerName $computername -ErrorAction stop).processid
}
Catch{
#If we didn't run netstat, break everything off
Throw $_
Break
}
#wait for process to complete
while (
#This while should return true until the process completes
$(
try{
get-process -id $processid -computername $computername -ErrorAction Stop
}
catch{
$FALSE
}
)
) {
start-sleep -seconds 2
}
#gather results
if(test-path $remoteTempFile){
Try {
$results = Get-Content $remoteTempFile | Select-String -Pattern '\s+(TCP|UDP)'
}
Catch {
Throw "Could not get content from $remoteTempFile for results"
Break
}
Remove-Item $remoteTempFile -force
}
else{
Throw "'$tempFile' on $computername converted to '$remoteTempFile'. This path is not accessible from your system."
Break
}
}
else{
#gather results on local PC
$results = netstat -ano | Select-String -Pattern '\s+(TCP|UDP)'
}
#initialize counter for progress
$totalCount = $results.count
$count = 0
#Loop through each line of results
foreach($result in $results) {
$item = $result.line.split(' ',[System.StringSplitOptions]::RemoveEmptyEntries)
if($item[1] -notmatch '^\[::'){
#parse the netstat line for local address and port
if (($la = $item[1] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6'){
$localAddress = $la.IPAddressToString
$localPort = $item[1].split('\]:')[-1]
}
else {
$localAddress = $item[1].split(':')[0]
$localPort = $item[1].split(':')[-1]
}
#parse the netstat line for remote address and port
if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq 'InterNetworkV6'){
$remoteAddress = $ra.IPAddressToString
$remotePort = $item[2].split('\]:')[-1]
}
else {
$remoteAddress = $item[2].split(':')[0]
$remotePort = $item[2].split(':')[-1]
}
#parse the netstat line for other properties
$procId = $item[-1]
$proto = $item[0]
$status = if($item[0] -eq 'tcp') {$item[3]} else {$null}
#Display progress bar prior to getting process name or host name
Write-Progress -Activity "Resolving host and process names"`
-Status "Resolving process ID $procId with remote address $remoteAddress and local address $localAddress"`
-PercentComplete (( $count / $totalCount ) * 100)
#If we are running showprocessnames, get the matching name
if($ShowProcessNames){
#handle case where process spun up in the time between running get-process and running netstat
if($procName = $processes | ?{$_.id -eq $procId} | select -ExpandProperty name ){ }
else {$procName = "Unknown"}
}
else{$procName = "NA"}
#if the showhostnames switch is specified, try to map IP to hostname
if($showHostnames){
$tmpAddress = $null
try{
if($remoteAddress -eq "127.0.0.1" -or $remoteAddress -eq "0.0.0.0"){
$remoteAddress = $computername
}
elseif($remoteAddress -match "\w"){
#check with dns cache first
if($tmpAddress = $dnsCache -match "`t$remoteAddress$"){
$remoteAddress = ( $tmpAddress -split "`t" )[0]
write-verbose "using cached REMOTE '$tmpADDRESS'"
}
else{
#if address isn't in the cache, resolve it and add it
$tmpAddress = $remoteAddress
$remoteAddress = [System.Net.DNS]::GetHostByAddress("$remoteAddress").hostname
$dnsCache += "$remoteAddress`t$tmpAddress"
write-verbose "using non cached REMOTE '$remoteAddress`t$tmpAddress"
}
}
}
catch{ }
try{
if($localAddress -eq "127.0.0.1" -or $localAddress -eq "0.0.0.0"){
$localAddress = $computername
}
elseif($localAddress -match "\w"){
#check with dns cache first
if($tmpAddress = $dnsCache -match "`t$localAddress$"){
$localAddress = ( $tmpAddress -split "`t" )[0]
write-verbose "using cached LOCAL '$tmpADDRESS'"
}
else{
#if address isn't in the cache, resolve it and add it
$tmpAddress = $localAddress
$localAddress = [System.Net.DNS]::GetHostByAddress("$localAddress").hostname
$dnsCache += "$localAddress`t$tmpAddress"
write-verbose "using non cached LOCAL '$localAddress'`t'$tmpAddress'"
}
}
}
catch{ }
}
#Define the object
$pso = New-Object -TypeName PSObject -Property #{
PID = $procId
ProcessName = $procName
Protocol = $proto
LocalAddress = $localAddress
LocalPort = $localPort
RemoteAddress =$remoteAddress
RemotePort = $remotePort
State = $status
} | Select-Object -Property $properties
#Filter and display the object
if($PSCmdlet.ParameterSetName -eq 'port'){
if($pso.RemotePort -like $Port -or $pso.LocalPort -like $Port){
if($pso.Protocol -like $Protocol -and $pso.State -like $State){
$pso
}
}
}
if($PSCmdlet.ParameterSetName -eq 'address'){
if($pso.RemoteAddress -like $Address -or $pso.LocalAddress -like $Address){
if($pso.Protocol -like $Protocol -and $pso.State -like $State){
$pso
}
}
}
if($PSCmdlet.ParameterSetName -eq 'name'){
if($pso.ProcessName -like $ProcessName){
if($pso.Protocol -like $Protocol -and $pso.State -like $State){
$pso
}
}
}
#Increment the progress counter
$count++
}
}
}
}
Dito to what #Kayasax said so picturesquely - you cannot run a powershell script without powershell, period. An alternative to your command is the following, executes and exits:
#powershell C:\Get-NetworkStatistics.ps1
In response to your comment, "...my main purpose it to run this function Get-NetworkStatistics -computername Gbi1 | Format-Table -autosize..."
You can add these two lines to the end of Get-NetworkStatistics.ps1
(This is a hack to get your purpose met, negates most of the power of Shay's script):
$ARG_COMPNAME = $args[0]
Get-NetworkStatistics -computername $ARG_COMPNAME | Format-Table -autosize
Then you call the Powershell script along the lines of:
C:\>powershell.exe -noprofile -file Get-NetworkStatistics.ps1 Gbi1
The script runs and dumps a netstat table to screen and dumps a file c:\netstat.txt

Powershell script to change service account

Does anyone have a Powershell script to change the credentials used by a Windows service?
Bit easier - use WMI.
$service = gwmi win32_service -computer [computername] -filter "name='whatever'"
$service.change($null,$null,$null,$null,$null,$null,$null,"P#ssw0rd")
Change the service name appropriately in the filter; set the remote computer name appropriately.
I wrote a function for PowerShell that changes the username, password, and restarts a service on a remote computer (you can use localhost if you want to change the local server). I've used this for monthly service account password resets on hundreds of servers.
You can find a copy of the original at http://www.send4help.net/change-remote-windows-service-credentials-password-powershel-495
It also waits until the service is fully stopped to try to start it again, unlike one of the other answers.
Function Set-ServiceAcctCreds([string]$strCompName,[string]$strServiceName,[string]$newAcct,[string]$newPass){
$filter = 'Name=' + "'" + $strServiceName + "'" + ''
$service = Get-WMIObject -ComputerName $strCompName -namespace "root\cimv2" -class Win32_Service -Filter $filter
$service.Change($null,$null,$null,$null,$null,$null,$newAcct,$newPass)
$service.StopService()
while ($service.Started){
sleep 2
$service = Get-WMIObject -ComputerName $strCompName -namespace "root\cimv2" -class Win32_Service -Filter $filter
}
$service.StartService()
}
The PowerShell 6 version of Set-Service now has the -Credential parameter.
Here is an example:
$creds = Get-Credential
Set-Service -DisplayName "Remote Registry" -Credential $creds
At this point, it is only available via download via GitHub.
Enjoy!
I created a text file "changeserviceaccount.ps1" containing the following script:
$account="domain\user"
$password="passsword"
$service="name='servicename'"
$svc=gwmi win32_service -filter $service
$svc.StopService()
$svc.change($null,$null,$null,$null,$null,$null,$account,$password,$null,$null,$null)
$svc.StartService()
I used this as part of by post-build command line during the development of a windows service:
Visual Studio: Project properties\Build Events
Pre-build event command line:
"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil.exe" myservice.exe /u
Post-build event command line:
"C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\installutil.exe" myservice.exe
powershell -command - < c:\psscripts\changeserviceaccount.ps1
A slight variation on the other scripts here, is below. This one will set credentials for any/all services running under a given login account. It will only attempt to restart the service if it was already running, so that we don't accidentally start a service that was stopped for a reason. The script has to be run from and elevated shell (if the script starts telling you about ReturnValue = 2, you're probably running it un-elevated). Some usage examples are:
all services running as the currently logged in user, on the local host:
.\set-servicecredentials.ps1 -password p#ssw0rd
all services running as user: somedomain\someuser on host somehost.somedomain:
.\set-servicecredentials.ps1 somehost.somedomain somedomain\someuser p#ssw0rd
Set-ServiceCredentials.ps1:
param (
[alias('computer', 'c')]
[string] $computerName = $env:COMPUTERNAME,
[alias('username', 'u')]
[string] $serviceUsername = "$env:USERDOMAIN\$env:USERNAME",
[alias('password', 'p')]
[parameter(mandatory=$true)]
[string] $servicePassword
)
Invoke-Command -ComputerName $computerName -Script {
param(
[string] $computerName,
[string] $serviceUsername,
[string] $servicePassword
)
Get-WmiObject -ComputerName $computerName -Namespace root\cimv2 -Class Win32_Service | Where-Object { $_.StartName -eq $serviceUsername } | ForEach-Object {
Write-Host ("Setting credentials for service: {0} (username: {1}), on host: {2}." -f $_.Name, $serviceUsername, $computerName)
$change = $_.Change($null, $null, $null, $null, $null, $null, $serviceUsername, $servicePassword).ReturnValue
if ($change -eq 0) {
Write-Host ("Service Change() request accepted.")
if ($_.Started) {
$serviceName = $_.Name
Write-Host ("Restarting service: {0}, on host: {1}, to implement credential change." -f $serviceName, $computerName)
$stop = ($_.StopService()).ReturnValue
if ($stop -eq 0) {
Write-Host -NoNewline ("StopService() request accepted. Awaiting 'stopped' status.")
while ((Get-WmiObject -ComputerName $computerName -Namespace root\cimv2 -Class Win32_Service -Filter "Name='$serviceName'").Started) {
Start-Sleep -s 2
Write-Host -NoNewline "."
}
Write-Host "."
$start = $_.StartService().ReturnValue
if ($start -eq 0) {
Write-Host ("StartService() request accepted.")
} else {
Write-Host ("Failed to start service. ReturnValue was '{0}'. See: http://msdn.microsoft.com/en-us/library/aa393660(v=vs.85).aspx" -f $start) -ForegroundColor "red"
}
} else {
Write-Host ("Failed to stop service. ReturnValue was '{0}'. See: http://msdn.microsoft.com/en-us/library/aa393673(v=vs.85).aspx" -f $stop) -ForegroundColor "red"
}
}
} else {
Write-Host ("Failed to change service credentials. ReturnValue was '{0}'. See: http://msdn.microsoft.com/en-us/library/aa384901(v=vs.85).aspx" -f $change) -ForegroundColor "red"
}
}
} -Credential "$env:USERDOMAIN\$env:USERNAME" -ArgumentList $computerName, $serviceUsername, $servicePassword
Considering that whithin this class:
$class=[WMICLASS]'\\.\root\Microsoft\SqlServer\ComputerManagement:SqlService'
there's a method named setserviceaccount(), may be this script will do what you want:
# Copyright Buck Woody, 2007
# All scripts provided AS-IS. No functionality is guaranteed in any way.
# Change Service Account name and password using PowerShell and WMI
$class = Get-WmiObject -computername "SQLVM03-QF59YPW" -namespace
root\Microsoft\SqlServer\ComputerManagement -class SqlService
#This remmed out part shows the services - I'll just go after number 6 (SQL
#Server Agent in my case):
# foreach ($classname in $class) {write-host $classname.DisplayName}
# $class[6].DisplayName
stop-service -displayName $class[6].DisplayName
# Note: I recommend you make these parameters, so that you don't store
# passwords. At your own risk here!
$class[6].SetServiceAccount("account", "password")
start-service -displayName $class[6].DisplayName
Just making #alastairs's comment more visible: the 6th parameter must be $false instead of $null when you use domain accounts:
$service = Get-WMIObject -class Win32_Service -filter "name='serviceName'"
$service.change($null, $null, $null, $null, $null, $false, "DOMAIN\account", "mypassword")
Without that it was working for 4/5 of the services I tried to change, but some refused to be changed (error 21).
$svc = Get-WmiObject win32_service -filter "name='serviceName'"
the position of username and password can change so try this line to find the right place$svc.GetMethodParameters("change")
$svc.change($null,$null,$null,$null,$null,$null,$null,$null,$null,"admin-username","admin-password")
What I cannot find in the default PS stack, I find it implemented in Carbon:
http://get-carbon.org/help/Install-Service.html
http://get-carbon.org/help/Carbon_Service.html (Carbon 2.0 only)
The given answers do the job.
Although, there is another important detail; in order to change the credentials and run the service successfully, you first have to grant that user account permissions to 'Log on as a Service'.
To grant that privilege to a user, use the Powershell script provided here by just providing the username of the account and then run the other commands to update the credentials for a service as mentioned in the other answers, i.e.,
$svc=gwmi win32_service -filter 'Service Name'
$svc.change($null,$null,$null,$null,$null,$null,'.\username','password',$null,$null,$null)
Sc config example. First allowing modify access to a certain target folder, then using the locked down "local service" account. I would use set-service -credential, if I had PS 6 or above everywhere.
icacls c:\users\myuser\appdata\roaming\fahclient /grant "local service:(OI)(CI)(M)"
sc config "FAHClient" obj="NT AUTHORITY\LocalService"

Resources