get IPv4 address into a variable - windows

Is there an easy way in PowerShell 3.0 on Windows 7 to get the local computer's IPv4 address into a variable?

Here is another solution:
$env:HostIP = (
Get-NetIPConfiguration |
Where-Object {
$_.IPv4DefaultGateway -ne $null -and
$_.NetAdapter.Status -ne "Disconnected"
}
).IPv4Address.IPAddress

How about this? (not my real IP Address!)
PS C:\> $ipV4 = Test-Connection -ComputerName (hostname) -Count 1 | Select IPV4Address
PS C:\> $ipV4
IPV4Address
-----------
192.0.2.0
Note that using localhost would just return and IP of 127.0.0.1
PS C:\> $ipV4 = Test-Connection -ComputerName localhost -Count 1 | Select IPV4Address
PS C:\> $ipV4
IPV4Address
-----------
127.0.0.1
The IP Address object has to be expanded out to get the address string
PS C:\> $ipV4 = Test-Connection -ComputerName (hostname) -Count 1 | Select -ExpandProperty IPV4Address
PS C:\> $ipV4
Address : 556228818
AddressFamily : InterNetwork
ScopeId :
IsIPv6Multicast : False
IsIPv6LinkLocal : False
IsIPv6SiteLocal : False
IsIPv6Teredo : False
IsIPv4MappedToIPv6 : False
IPAddressToString : 192.0.2.0
PS C:\> $ipV4.IPAddressToString
192.0.2.0

If I use the machine name this works. But is kind of like a hack (because I am just picking the first value of ipv4 address that I get.)
$ipaddress=([System.Net.DNS]::GetHostAddresses('PasteMachineNameHere')|Where-Object {$_.AddressFamily -eq "InterNetwork"} | select-object IPAddressToString)[0].IPAddressToString
Note that you have to replace the value PasteMachineNameHere in the above expression
This works too
$localIpAddress=((ipconfig | findstr [0-9].\.)[0]).Split()[-1]

Here are three methods using windows powershell and/or powershell core, listed from fastest to slowest.
You can assign it to a variable of your choosing.
Method 1: (this method is the fastest and works in both windows powershell and powershell core)
$ipAddress = (Get-NetIPAddress | Where-Object {$_.AddressState -eq "Preferred" -and $_.ValidLifetime -lt "24:00:00"}).IPAddress
Method 2: (this method is as fast as method 1 but it does not work with powershell core)
$ipAddress = (Test-Connection -ComputerName (hostname) -Count 1 | Select -ExpandProperty IPv4Address).IPAddressToString
Method 3: (although the slowest, it works on both windows powershell and powershell core)
$ipAddress = (Get-NetIPConfiguration | Where-Object {$_.IPv4DefaultGateway -ne $null -and $_.NetAdapter.status -ne "Disconnected"}).IPv4Address.IPAddress

Here is what I ended up using
$ipaddress = $(ipconfig | where {$_ -match 'IPv4.+\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' } | out-null; $Matches[1])
which breaks down as
execute ipconfig command - get all the network interface information
use powershell's where filter with a regular expression
regular expression finds the line with "IPv4" and a set of 4 blocks each with 1-3 digits separated by periods, i.e. a v4 IP address
disregard the output by piping it to null
finally get the first matched group as defined by the brackets in the regular expression.
catch that output in $ipaddress for later use.

(Get-WmiObject -Class Win32_NetworkAdapterConfiguration | where {$_.DHCPEnabled -ne $null -and $_.DefaultIPGateway -ne $null}).IPAddress

This one liner gives you the IP address:
(Test-Connection -ComputerName $env:computername -count 1).ipv4address.IPAddressToString
Include it in a Variable?
$IPV4=(Test-Connection -ComputerName $env:computername -count 1).ipv4address.IPAddressToString

Another variant using $env environment variable to grab hostname:
Test-Connection -ComputerName $env:computername -count 1 | Select-Object IPV4Address
or if you just want the IP address returned without the property header
(Test-Connection -ComputerName $env:computername -count 1).IPV4Address.ipaddressTOstring

tldr;
I used this command to get the ip address of my Ethernet network adapter into a variable called IP.
for /f "tokens=3 delims=: " %i in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do set IP=%i
For those who are curious to know what all that means, read on
Most commands using ipconfig for example just print out all your IP addresses and I needed a specific one which in my case was for my Ethernet network adapter.
You can see your list of network adapters by using the netsh interface ipv4 show interfaces command. Most people need Wi-Fi or Ethernet.
You'll see a table like so in the output to the command prompt:
Idx Met MTU State Name
--- ---------- ---------- ------------ ---------------------------
1 75 4294967295 connected Loopback Pseudo-Interface 1
15 25 1500 connected Ethernet
17 5000 1500 connected vEthernet (Default Switch)
32 15 1500 connected vEthernet (DockerNAT)
In the name column you should find the network adapter you want (i.e. Ethernet, Wi-Fi etc.).
As mentioned, I was interested in Ethernet in my case.
To get the IP for that adapter we can use the netsh command:
netsh interface ip show config name="Ethernet"
This gives us this output:
Configuration for interface "Ethernet"
DHCP enabled: Yes
IP Address: 169.252.27.59
Subnet Prefix: 169.252.0.0/16 (mask 255.255.0.0)
InterfaceMetric: 25
DNS servers configured through DHCP: None
Register with which suffix: Primary only
WINS servers configured through DHCP: None
(I faked the actual IP number above for security reasons 😉)
I can further specify which line I want using the findstr command in the ms-dos command prompt.
Here I want the line containing the string IP Address.
netsh interface ip show config name="Ethernet" | findstr "IP Address"
This gives the following output:
IP Address: 169.252.27.59
I can then use the for command that allows me to parse files (or multiline strings in this case) and split out the strings' contents based on a delimiter and the item number that I'm interested in.
Note that I am looking for the third item (tokens=3) and that I am using the space character and : as my delimiters (delims=: ).
for /f "tokens=3 delims=: " %i in ('netsh interface ip show config name^="Ethernet" ^| findstr "IP Address"') do set IP=%i
Each value or token in the loop is printed off as the variable %i but I'm only interested in the third "token" or item (hence tokens=3). Note that I had to escape the | and = using a ^
At the end of the for command you can specify a command to run with the content that is returned. In this case I am using set to assign the value to an environment variable called IP. If you want you could also just echo the value or what ever you like.
With that you get an environment variable with the IP Address of your preferred network adapter assigned to an environment variable. Pretty neat, huh?
If you have any ideas for improving please leave a comment.

I was looking for the same thing and figured this out:
$ip = Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $(Get-NetConnectionProfile | Select-Object -ExpandProperty InterfaceIndex) | Select-Object -ExpandProperty IPAddress
This filters out both the loopback address and some virtual networks I have.

$ip = (Get-NetIPAddress -AddressFamily IPv4 -InterfaceIndex $(Get-NetConnectionProfile).InterfaceIndex).IPAddress
OR
function Get-LocalIP {
(
Get-NetIPAddress `
-AddressFamily IPv4 `
-InterfaceIndex $(
Get-NetConnectionProfile
).InterfaceIndex
).IPAddress
}
$ip = Get-LocalIP

To grab the device's IPv4 addresses, and filter to only grab ones that match your scheme (i.e. Ignore and APIPA addresses or the LocalHost address). You could say to grab the address matching 192.168.200.* for example.
$IPv4Addr = Get-NetIPAddress -AddressFamily ipV4 | where {$_.IPAddress -like X.X.X.X} | Select IPAddress

# Patrick Burwell's Ping Script - Patrick.Burwell#Infosys.com #
$Output= #() #sets an array
$names = Get-Content ".\input\ptd.pc_list.txt" #sets a list to use, like a DNS dump
foreach ($name in $names){ #sets the input by enumerating a text file to loop through and sets a variable to execute against
if ($IPV4 = Test-Connection -Delay 15 -ComputerName $name -Count 1 -ErrorAction SilentlyContinue|select IPV4Address #run ping and sets only IPV4Address response variable
){# If true then run...
$Output+= $Name,($IPV4.IPV4Address).IPAddressToString # Fills the array with the #true response
Write-Host $Name',','Ping,'($IPV4.IPV4Address).IPAddressToString -ForegroundColor Green #Sets the output to receive the Name, result and IPV4Address and prints the reply to the console with specific colors
}
else{#If false then run...
$Output+= "$name," #Fills the array with the #false response
Write-Host "$Name," -ForegroundColor Red #Prints the reply to the console with specific colors
}
}
#$Output | Out-file ".\output\result.csv" #<-- use to export to a text file (Set path as needed)
#$Output | Export-CSV ".\output\result.csv" -NoTypeInformation #<-- use to export to a csv file (Set path as needed)
#If you choose, you can merely have the reply by the name and IP, and the Name and no IP by removing the Ping comments

As I was working in Powershell 3, none of the answers here worked for me. It's based on Rob's approach, but this one works when you have multiple network adapters, it also picks out the IP correctly using capture groups
function GetIPConfig {
return ipconfig | select-string ('(\s)+IPv4.+\s(?<IP>(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}))(\s)*') -AllMatches | %{ $_.Matches } | % { $_.Groups["IP"]} | %{ $_.Value }
}

Non of the top comments are actually fully correct since a computer can have multiple interfaces and an interface can have multiple IP addresses. There are a few answers here which technically correct but utilizes "funky" ways to filter out wellknown addresses (like APIPA, localhost, etc) whereas even Powershell 3.0 have a native way to do so with PrefixOrigin.
$IPv4Addresses = $(Get-NetIPAddress | Where-Object { $_.PrefixOrigin -ne "WellKnown" -and $_.AddressFamily -eq "IPv4" }).IPAddress

I do this :
$interFaceAliasName="LAN" # You have to change the name according to your interface's name
$myInterface=(Get-NetIPAddress -InterfaceAlias $interFaceAliasName)
$myIP=$myInterface.IPv4Address

I recently had the same issue. So I wrote a script to parse it from the ipconfig /all output. This script is easily modifiable to obtain any of the parameters of the interfaces and it works on Windows 7 also.
Get output of IP config in LineNumber | Line format
$ip_config = $(ipconfig /all | % {$_ -split "rn"} | Select-String -Pattern ".*" | select LineNumber, Line)
Get list of interfaces (+ last line of ipconfig output) in LineNumber | Line format
$interfaces = $($ip_config | where {$_.Line -notmatch '^\s*$'} | where {$_.Line -notmatch '^\s'}) + $($ip_config | Select -last 1)
Filter through the interfaces list for the specific interface you want
$LAN = $($interfaces | where {$_.Line -match 'Wireless Network Connection:$'})
Get the start and end line numbers of chosen interface from output
$i = $interfaces.IndexOf($LAN)
$start = $LAN.LineNumber
$end = $interfaces[$i+1].LineNumber
Pick the lines from start..end
$LAN = $ip_config | where {$_.LineNumber -in ($start..$end)}
Get IP(v4) address field (returns null if no IPv4 address present)
$LAN_IP = #($LAN | where {$_ -match 'IPv4.+:\s(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})'})
$LAN_IP = &{If ($LAN_IP.Count -gt 0) {$Matches[1]} Else {$null}}

$a = ipconfig
$result = $a[8] -replace "IPv4 Address. . . . . . . . . . . :",""
Also check which index of ipconfig has the IPv4 Address

Related

Which command to use for getting Bytes per cluster and Bytes per File record segment data for multiple servers?

I would like to generate Bytes per cluster and Bytes per File record segment data for over 50 servers into an excel sheet (for a drive D)
I know the command "Fsutil fsinfo ntfsinfo [drive letter:]" provides this info but only for local system.
i tried writing this but it did not work.
"Enter-PSSession Server1
Fsutil fsinfo ntfsinfo D:
Exit-PSSession"
I then executed each command manually and it was working.
Can anyone please help me create a script to get the above mentioned data at one go for 50 servers.
Thank you
Continuing from my comment, you can use cmdlet Invoke-Comand for that:
# you may already have admin permissions on each of the servers, but if not, get craedentials for someone that has
$adminCreds = Get-Credential -Message 'Please add your admin credentials to get server information'
# your list of server names here
$servers = 'Server01', 'Server02' # etc.
# next use 'Invoke-Command' to have each server run the code
$result = Invoke-Command -ComputerName $servers -Credential $adminCreds -ScriptBlock {
# have each server run the Fsutil command, and return that as PsCustomObject for convenience
# instead of an array of lines.
# to use ConvertFrom-StringData in PowerShell < 7.x, you need to replace the first colon with a equals sign
# PowerShell versions above 5.1 can use parameter -Delimiter '='
[PsCustomObject]((Fsutil fsinfo ntfsinfo D:) -replace '(?<!:.*):', '=' -join "`r`n" | ConvertFrom-StringData)
}
Now you can save the entire result to CSV or limit to the properties you need like
$result | Select-Object PSComputerName, 'Bytes Per Cluster', 'Bytes Per FileRecord Segment' | Export-Csv -Path 'X:\serverInfo.csv' -NoTypeInformation
If you are not sure all of the servers can be reached, do a loop:
$result = foreach ($server in $servers) {
# test if the server can be reached
if (Test-Connection -ComputerName $server -Count 1 -Quiet) {
Invoke-Command -ComputerName $server -Credential $adminCreds -ScriptBlock {
# have each server run the Fsutil command, and return that as PsCustomObject for convenience
# instead of an array of lines.
# to use ConvertFrom-StringData in PowerShell < 7.x, you need to replace the first colon with a equals sign
# PowerShell versions above 5.1 can use parameter -Delimiter '='
[PsCustomObject]((Fsutil fsinfo ntfsinfo D:) -replace '(?<!:.*):', '=' -join "`r`n" | ConvertFrom-StringData)
}
}
else {
Write-Warning "Server $server is off-line!"
}
}
Regex details:
(?<! Assert that it is impossible to match the regex below with the match ending at this position (negative lookbehind)
: Match the character “:” literally
. Match any single character
* Between zero and unlimited times, as many times as possible, giving back as needed (greedy)
)
: Match the character “:” literally

Parsing Netsh output

I need to parse the output given by the netsh command in powershell.
Below is the command i'm using
Netsh advfirewall show private
It's proving the below output
Private Profile Settings:
----------------------------------------------------------------------
State ON
Firewall Policy BlockInbound,AllowOutbound
LocalFirewallRules N/A (GPO-store only)
LocalConSecRules N/A (GPO-store only)
InboundUserNotification Enable
RemoteManagement Disable
UnicastResponseToMulticast Enable
Logging:
LogAllowedConnections Disable
LogDroppedConnections Disable
FileName %systemroot%\system32\LogFiles\Firewall\pfirewall.log
MaxFileSize 4096
My requirement is to access each and every value in the above output. Something like $result.state / $result.InboundUserNotification
I'm pretty new to PowerShell and i have searched on google about this and wasn't able to find anything.
The obligatory recommendation:
It's always better to find a PowerShell cmdlet to call, so you can take advantage of objects getting output, whose properties you can robustly access - but it sounds like the candidate cmdlet, Get-NetFirewallProfile doesn't work as expected for your use case (domain-joined computers).
Text parsing is always less robust than an object-based solution, though PowerShell offers many powerful features, if needed, notably in this case the switch statement with its -Regex option:
$result = [ordered] #{} # initialize the (ordered) result hashtable.
# Process each line output by netsh, and if it is a line
# containing a property/value-pair, add an entry to the hashtable.
switch -Regex (netsh advfirewall show private) {
'^(.+?) {2,}(.+)' { $result[$Matches.1] = $Matches.2 }
}
# Now you can access $result.State, $result.'Firewall Policy', ...
Note the assumption that the property name and its value are separated by at least two spaces
( {2,}); lines that don't match the property/value pattern are simply skipped.
An alternative is to assume a fixed column width with a single space separating the columns, which does seem to be the case here:
$result = [ordered] #{} # initialize the (ordered) result hashtable.
# Process each line output by netsh, and if it is a line
# containing a property/value-pair, add an entry to the hashtable.
switch -Regex (netsh advfirewall show private) {
'^(.{37}) (.+)' { $result[($Matches.1).TrimEnd()] = $Matches.2 }
}
Note the (...) (parentheses) around $Matches.1, which is unexpectedly required in order to call .TrimEnd() on the value; the parentheses wouldn't be necessary if index syntax ([1]) rather than property syntax .1 were used (that is, $Matches[1].TrimEnd() would work). The problem seems to be specific to property / key names that are numbers. See GitHub issue #14036
If you must parse this output, you can do the following:
$netsh = (Netsh advfirewall show private |
Select-String -Pattern "\s{2,}") -replace '\s{2,}','=' -replace '\\','\\' -join [System.Environment]::NewLine
$result = [pscustomobject](ConvertFrom-StringData $netsh)
The problem with the ConvertFrom-StringData method is the hash table output is not ordered. If order matters, you can just create your hash table by splitting each line into property/value pairs:
$hash = [ordered]#{}
Netsh advfirewall show private | Select-String -Pattern "\s{2,}" |
Foreach-Object {
$key,$value = $_ -split '\s{2,}'
$hash[$key] = $value
}
$result = [pscustomobject]$hash
Here's a similar approach to AdminOfThings answer utilizing ConvertFrom-StringData as well as Foreach-Object's -Begin and -End parameters.
Netsh advfirewall show private |
ForEach-Object -Begin{$ht = [ordered]#{}} {
if($_ -match '\s{10,}')
{
$ht += $_ -replace '\\','\\' -replace '\s{10,}','=' | ConvertFrom-StringData
}
} -End{[PSCustomObject]$ht} -OutVariable result
And a slight variation
Netsh advfirewall show private | Where-Object {$_ -match '\s{10,}'} |
ForEach-Object -Begin{$ht = [ordered]#{}} {
$ht += $_ -replace '\\','\\' -replace '\s{10,}','=' | ConvertFrom-StringData
} -End{[PSCustomObject]$ht} -OutVariable result

Get local port numbers in windows 7 [duplicate]

This question already has answers here:
Get foreign address name using NETSTAT for established active TCP connections
(3 answers)
Closed 6 years ago.
I am trying to get all local ports that are in listening state. Using
netstat -a -n
I get the following output:
Proto Local Address Foreign Address State
TCP 0.0.0.0:8080 0.0.0.0:0 LISTENING //for example, demo data is given
But I only wan't to get the port numbers.
1111 //for ex, this is in listening state.
In Windows 10, I can use
Get-NetTCPConnection -State Listen | group localport -NoElement
Which works but this command isn't available on Windows 7
Not sure whether there is a Windows 7 cmdlet available but you could parse the netstat result:
$objects = netstat -a -n |
select -Skip 4 |
ForEach-Object {
$line = $_ -split ' ' | Where-Object {$_ -ne ''}
if ($line.Count -eq 4)
{
New-Object -TypeName psobject -Property #{
'Protocol'=$line[0]
'LocalAddress'=$line[1]
'ForeignAddress'=$line[2]
'State'=$line[3]}
}
}
Then you can retrieve the ports using something like this:
$objects | Where State -eq LISTENING | Select LocalAddress | Foreach {
$_ -replace '.*:(\d+).*', '$1'
}

Powershell: Get FQDN Hostname

I want to retrieve the FQDN name of windows server via powershell script. I have found 2 solution so far:
$server = Invoke-Command -ScriptBlock {hostname}
Above line will print just the short name of the server
$sysinfo = Get-WmiObject -Class Win32_ComputerSystem
$server = “{0}.{1}” -f $sysinfo.Name, $sysinfo.Domain
Above two line will get me the FQDN but this looks really nasty code to retrieve just the hostname :(
So, My question is, is there an easier way to get the FQDN in powershell. I am a bash/perl coder and recently picked up powershell.. so finding it difficult.
Thanks.
To get FQDN of local computer:
[System.Net.Dns]::GetHostByName($env:computerName)
or
[System.Net.Dns]::GetHostByName($env:computerName).HostName
To get FQDN of Remote computer:
[System.Net.Dns]::GetHostByName('mytestpc1')
or
For better formatted value use:
[System.Net.Dns]::GetHostByName('mytestpc1').HostName
For remote machines make sure host is reachable.
How about: "$env:computername.$env:userdnsdomain"
This actually only works if the user is logged into a domain (i.e. no local accounts), logged into the same domain as the server, and doesn't work with disjointed name space AD configurations.
Use this as referenced in another answer:
$myFQDN=(Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain ; Write-Host $myFQDN
Local Computer FQDN via dotNet class
[System.Net.Dns]::GetHostEntry([string]$env:computername).HostName
or
[System.Net.Dns]::GetHostEntry([string]"localhost").HostName
Reference:
Dns Methods (System.Net)
note: GetHostByName method is obsolete
Local computer FQDN via WMI query
$myFQDN=(Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain
Write-Host $myFQDN
Reference:
Win32_ComputerSystem class
[System.Net.Dns]::GetHostByName((hostname)).HostName
$env:computerName returns NetBIOS name of the host, so that both previous examples return
netbioshostname.domainsuffix (not FQDN!)
instead of
dnshostname.domainsuffix (FQDN)
for example, host has
FQDN
aa-w2k12sv-storage.something.com
and NetBIOS name
aa-w2k12sv-stor (an easy case, I usually change NetBIOS name)
the hostname utility returns dnshostname, i.e., the first part of FQDN and code
[System.Net.Dns]::GetHostByName((hostname)).HostName
returns the right FQDN
Comment: never use the same NetBIOS and DNS names of AD domains and hosts. If your or 3rd party application writes to the log: "cannot connect to hostname.domainsuffix", what name it tries to resolve? If you see in the log "cannot connect to netbiosname.domainsuffix", no doubt, a lazy programmer added domain suffix to the NetBIOS name and you are sure, this is a bug, and can open a ticket to force them to fix the issue...
This worked in PS and PS Core on Windows (Tested on Versions 5.1 and 7.2)
[System.Net.Dns]::Resolve($null).HostName
(Get-ADComputer $(hostname)).DNSHostName
Here's the method that I've always used:
$fqdn= $(ping localhost -n 1)[1].split(" ")[1]
It can also be retrieved from the registry:
Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters' |
% { $_.'NV HostName', $_.'NV Domain' -join '.' }
to get the fqdn corresponding to the first IpAddress, it took this command:
PS C:\Windows\system32> [System.Net.Dns]::GetHostByAddress([System.Net.Dns]::GetHostByName($env:computerName).AddressList[0]).HostName
WIN-1234567890.fritz.box
where [System.Net.Dns]::GetHostByName($env:computerName).AddressList[0] represents the first IpAddress-Object and [System.Net.Dns]::GetHostByAddress gets the dns-object out of it.
If I took the winning solution on my standalone Windows, I got only:
PS C:\Windows\system32> (Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain
WIN-1234567890.WORKGROUP
that's not what I wanted.
I use the following syntax :
$Domain=[System.Net.Dns]::GetHostByName($VM).Hostname.split('.')
$Domain=$Domain[1]+'.'+$Domain[2]
it does not matter if the $VM is up or down...
If you have more than one network adapter and more than one adapter is active (f.e WLAN + VPN) you need a bit more complex check. You can use this one-liner:
[System.Net.DNS]::GetHostByAddress(([System.Net.DNS]::GetHostAddresses([System.Environment]::MachineName) | Where-Object { $_.AddressFamily -eq "InterNetwork" } | Select-Object IPAddressToString)[0].IPAddressToString).HostName.ToLower()
A cleaner format FQDN remotely
[System.Net.Dns]::GetHostByName('remotehost').HostName
How about this
$FQDN=[System.Net.Dns]::GetHostByName($VM).Hostname.Split('.')
[int]$i = 1
[int]$x = 0
[string]$Domain = $null
do {
$x = $i-$FQDN.Count
$Domain = $Domain+$FQDN[$x]+"."
$i = $i + 1
} until ( $i -eq $FQDN.Count )
$Domain = $Domain.TrimEnd(".")
Here is a way to determine the FQDN of a server based on the "Name" and "DistinguishedName". Works for multiple domains:
$server = Get-ADComputer serverName -Server domainName -Properties * | select Name, DistinguishedName
$domain = $server.DistinguishedName -split ","
$domain = $domain | ? {$_ -like 'DC=*'}
$domain = $domain -join "."
$domain = $domain -replace "DC="
$FQDN = $server.Name + "." + $domain
I have the following add.. I need to separate out the dns suffix from the hostname.. and I only "know" the servers alias shortname... and want to know what the dns suffix is
#example:
#serveralias: MyAppServer.us.fred.com
#actualhostname: server01.us.fred.com
#I "know": "MyAppServer" .. I pass this on as an env var called myjumpbox .. this could also be $env:computername
$forname = $env:myjumpbox
$fqdn = [System.Net.Dns]::GetHostByName($forname).Hostname
$shortname = $fqdn.split('.')[0]
$domainname = $fqdn -split $fqdn.split('.')[0]+"."
$dnssuf = $domainname[1]
" name parts are- alias: " + $forname + " actual hostname: " + $shortname + " suffix: " + $dnssuf
#returns
name parts are- alias: MyAppServer actual hostname: server01 suffix: us.fred.com
"$env:computername.$env:userdnsdomain"
will work if separated out like this
"$env:computername"+"$env:userdnsdomain"

How to check window's firewall is enabled or not using commands

I am adding a windows firewall rule using netsh advfirewall firewall command in a setup program. My code is giving an error message if the system has windows firewall disabled.
So I need to check the window's firewall status before executing the command netsh advfirewall firewall add. ie, if firewall is disabled, no need to add the rule.
I am checking if the firewall is enabled or not by using the window registry value "EnableFirewall".
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile
I am not sure this is the right way. There can be domain firewall profile(?) also.
Thanks in advance.
Another option is to use netsh itself to check if firewall is enabled or not. Execute the command netsh advfirewall show private|public|domain. It will give the state on/off.
Invoke-Command -ComputerName <servername> -Credential <username> -ScriptBlock {[Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey("LocalMachine",$env:COMPUTERNAME).OpenSubKey("System\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile").GetValue("EnableFirewall")}
1 means enabled.
Try this for a Compliance and Non-Compliance check:
$FirewallStatus = 0
$SysFirewallReg1 = Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\DomainProfile" -Name EnableFirewall | Select-Object -ExpandProperty EnableFirewall
If ($SysFirewallReg1 -eq 1) {
$FirewallStatus = 1
}
$SysFirewallReg2 = Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\PublicProfile" -Name EnableFirewall | Select-Object -ExpandProperty EnableFirewall
If ($SysFirewallReg2 -eq 1) {
$FirewallStatus = ($FirewallStatus + 1)
}
$SysFirewallReg3 = Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile" -Name EnableFirewall | Select-Object -ExpandProperty EnableFirewall
If ($SysFirewallReg3 -eq 1) {
$FirewallStatus = ($FirewallStatus + 1)
}
If ($FirewallStatus -eq 3) {Write-Host "Compliant"}
ELSE {Write-Host "Non-Compliant"}
I just had to do something similar for an environment I took over. I used the below to check state for all three profiles.
invoke-command -computername $computer -scriptblock {
try{ get-netfirewallprofile | select name,enabled }
catch{ netsh advfirewall show all state }
}
the try block will work with server 2012 or windows 8 and newer systems. if that fails when it throws an error about not having the cmdlet that will be caught and instead of giving you an error it will fall back to using netsh to display the information.
I've used this on server 2008 R2, 2012 R2 and 2016 with good results. Hope it works for you!
Written as a one-liner:
if (((Get-NetFirewallProfile | select name,enabled) | where { $_.Enabled -eq $True } | measure ).Count -eq 3) {Write-Host "OK" -ForegroundColor Green} else {Write-Host "OFF" -ForegroundColor Red}
What it does?
Iterates through each Firewall settings item: [Domain, Private, Public]
Check if each item is enabled and set to TRUE
There are 3 items, so we count all TRUES and compare to 3
Print Green OK or Red OFF
NOT using netsh or registry
Requires a working NetSecurity Module for the Get-NetFirewallProfile cmdlet.
Make sure to also check the GPO policies for firewalls, they are not stored in the registry, but in another store, see this question as well:
Windows Firewall state different between Powershell output and GUI
$Compliance = 'Non-Compliant'
$Check = get-netfirewallprofile | Where-Object {$_.Name -eq 'Domain' -and $_.Enabled -eq 'True'}
$Check = get-netfirewallprofile | Where-Object {$_.Name -eq 'Public' -and $_.Enabled -eq 'True'}
$Check = get-netfirewallprofile | Where-Object {$_.Name -eq 'Private' -and $_.Enabled -eq 'True'}
if ($Check) {$Compliance = 'Compliant'}
$Compliance
I am new to this but how ever i used reg query to get the details.
type this in command line and hit enter.
reg query \\IP_Address\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\SharedAccess\Parameters\FirewallPolicy\StandardProfile
I was using it in my works and also was using the command below.
reg query \\ip_address\path

Resources