Powershell: get DHCP status with Get-NetIPConfiguration? - windows

I'm a powershell newbie.
If I run Get-NetIPConfiguration -Detailed I can see the IPv4 DHCP status. This is a good start - took me a lot of googling to get this far:
PS C:\Windows\system32> Get-NetIPConfiguration -Detailed
ComputerName : VM-172-26-39-24
InterfaceAlias : Ethernet
InterfaceIndex : 6
InterfaceDescription : Red Hat VirtIO Ethernet Adapter
NetCompartment.CompartmentId : 1
NetCompartment.CompartmentDescription : Default Compartment
NetAdapter.LinkLayerAddress : FA-16-3E-FF-0D-60
NetAdapter.Status : Up
NetProfile.Name : Network
NetProfile.NetworkCategory : Public
NetProfile.IPv6Connectivity : NoTraffic
NetProfile.IPv4Connectivity : Internet
IPv6LinkLocalAddress : fe80::x:x:x:x
IPv4Address : 172.26.39.249
IPv6DefaultGateway :
IPv4DefaultGateway : 172.26.36.1
NetIPv6Interface.NlMTU : 9000
NetIPv4Interface.NlMTU : 9000
NetIPv6Interface.DHCP : Enabled
NetIPv4Interface.DHCP : Disabled
DNSServer : x.x.x.x
x.x.x.x
But if I run something like
Get-NetIPConfiguration -Detailed | select InterfaceAlias,NetIPv4Interface.DHCP
I get an empty field?
PS C:\Windows\system32> Get-NetIPConfiguration -Detailed | `
select InterfaceAlias, NetIPv4Interface.DHCP
InterfaceAlias NetIPv4Interface.DHCP
-------------- ---------------------
Ethernet
Am I doing something wrong?
If I remove the trailing .DHCP ("what's in there?") I see nothing recognisable
PS C:\Windows\system32> Get-NetIPConfiguration -Detailed | select InterfaceAlias, NetIPv4Interface
InterfaceAlias NetIPv4Interface
-------------- ----------------
Ethernet MSFT_NetIPInterface (Name = "#55?55;", CreationClassName = "", SystemCreationClassName = "", SystemName = "")

You need to calculate the sub property when used in a Select statement:
Get-NetIPConfiguration -Detailed | `
select InterfaceAlias, #{N="DHCP";E={$_.NetIPv4Interface.DHCP}}
Or try this:
Get-NetIPConfiguration | Select -ExpandProperty NetIPv4Interface | Select InterfaceAlias,DHCP
...or you could just retrieve the config, put it in a variable then get the desired sub-properties:
$Config = Get-NetIPConfiguration
$Config | forEach {
[pscustomobject]#{InterFaceAlias=$_.InterFaceAlias;DHCP=$_.NetIPv4Interface.DHCP}
}

Related

Unexpected output from where-object

In PowerShell, this command:
Get-NetIPConfiguration | where-object {$_.IPv4Address.IPAddress -match '172.20'}
Is yielding this output:
InterfaceAlias : Wi-Fi
InterfaceIndex : 24
InterfaceDescription : Intel(R) Wi-Fi 6 AX201 160MHz
NetProfile.Name : Identifying...
IPv6Address : 2601:19b:c00:15c3:d80:ee8c:3679:1fe5
1::1
IPv4Address : 172.20.4.93
IPv6DefaultGateway : fe80::be98:dfff:feff:4acd
IPv4DefaultGateway : 172.20.4.1
DNSServer : fe80::be98:dfff:feff:4acd
InterfaceAlias : Local Area Connection 3
InterfaceIndex : 22
InterfaceDescription : TAP-Windows Adapter V9 #3
NetAdapter.Status : Disconnected
Whereas I would only expect to see this output:
InterfaceAlias : Wi-Fi
InterfaceIndex : 24
InterfaceDescription : Intel(R) Wi-Fi 6 AX201 160MHz
NetProfile.Name : Unidentified network
IPv6Address : 2601:19b:c00:15c3:d80:ee8c:3679:1fe5
1::1
IPv4Address : 172.20.4.93
IPv6DefaultGateway : fe80::be98:dfff:feff:4acd
IPv4DefaultGateway : 172.20.4.1
DNSServer : fe80::be98:dfff:feff:4acd
This is the full output from Get-NetIPConfiguration:
InterfaceAlias : VirtualBox Host-Only Network
InterfaceIndex : 11
InterfaceDescription : VirtualBox Host-Only Ethernet Adapter
IPv4Address : 169.254.249.136
IPv6DefaultGateway :
IPv4DefaultGateway :
DNSServer : fec0:0:0:ffff::1
fec0:0:0:ffff::2
fec0:0:0:ffff::3
InterfaceAlias : Local Area Connection
InterfaceIndex : 18
InterfaceDescription : TAP-Windows Adapter V9
NetProfile.Name : somerandomcompany.com
IPv4Address : 10.251.10.13
IPv6DefaultGateway :
IPv4DefaultGateway :
DNSServer : 10.255.0.9
10.255.0.8
InterfaceAlias : Wi-Fi
InterfaceIndex : 24
InterfaceDescription : Intel(R) Wi-Fi 6 AX201 160MHz
NetProfile.Name : PS-118 Guest
IPv6Address : 2601:19b:c00:15c3:d80:ee8c:3679:1fe5
1::1
IPv4Address : 192.168.0.208
IPv6DefaultGateway : fe80::be98:dfff:feff:4acd
IPv4DefaultGateway : 192.168.0.1
DNSServer : fe80::be98:dfff:feff:4acd
fe80::be98:dfff:feff:4acd
192.168.0.1
InterfaceAlias : Bluetooth Network Connection
InterfaceIndex : 9
InterfaceDescription : Bluetooth Device (Personal Area Network)
NetAdapter.Status : Disconnected
InterfaceAlias : Local Area Connection 3
InterfaceIndex : 22
InterfaceDescription : TAP-Windows Adapter V9 #3
NetAdapter.Status : Disconnected
InterfaceAlias : Local Area Connection 2
InterfaceIndex : 27
InterfaceDescription : TAP-Windows Adapter V9 #2
NetAdapter.Status : Disconnected
InterfaceAlias : OpenVPN Wintun
InterfaceIndex : 25
InterfaceDescription : Wintun Userspace Tunnel
NetAdapter.Status : Disconnected
I get the same result with PowerShell 7.2.5 and PowerShell 5.1.19041.1682, on Windows 10
Please let me know if I can provide any other information, and thank you for any help!

getting log from telnet session and writing relevant info to file but line gets overwritten by timestamp variable in expect script

Here is a sample remote session that I am automating
[sample-session]
$telnet 172.16.11.2
Trying 172.16.11.2...
Connected to 172.16.11.2.
Escape character is '^]'.
BCM96858 Broadband Router
Login: user
Password:
> voice show
Global Parameters:
------------------
BoundIfName : bronu8.2501
IP address family : IPv4
BoundIpAddr : 172.16.11.2
Voice Log Levels : general=3,cmgr=3,disp=3,sipcctk=3,bos=3,ept=3,cms=3,prov=3,lhapi=3,istw=3,dsphal=3,slicslac=3
Management Protocol : OMCI
Voice DNS Server Enable : Off
Voice DNS Server Primary : 0.0.0.0
Voice DNS Server Secondary : 0.0.0.0
Service Provider 0:
--------------------
Associated Voice Profile: 1
Locale : IND
DTMFMethod : InBand
HookFlashMethod : None
DigitMap : x+T
Log Server Addr : 0.0.0.0
Log Server Port : 0
T38 : on
V18 : on
RTPDSCPMark : 46
European flash : Off
SIP:
SIP mode : RFC3261
Domain :
Port : 5060
Transport : UDP
SIP URI for TLS calls: Off
RegExpires : 300
RegRetryInterval : 60
DSCPMark : 46
Registrar Addr : 172.16.11.201
Registrar Port : 5060
Proxy Addr : 172.16.11.201
Proxy Port : 5060
OutBoundProxy Addr : 172.16.11.201
OutBoundProxy Port : 5060
Music Server Addr : 0.0.0.0
Music Server Port : 0
Conferencing URI :
Conferencing Option : Local
Failover Enable : Off
Sip OPTIONS Enable : Off
Back-to-primary cfg : Disabled
Secondary Domain :
Secondary Registrar Addr : 0.0.0.0
Secondary Registrar Port : 5060
Secondary Proxy Addr : 0.0.0.0
Secondary Proxy Port : 5060
Secondary Outbound Proxy Addr : 0.0.0.0
Secondary Outbound Proxy Port : 5060
To Tag Matching : On
Timer B ( in ms ) : 32000
Timer F ( in ms ) : 32000
SRTP Usage Option : Disabled
Account 0:
-----------
ActivationStatus : Enabled
VoipServiceStatus : Up
CallStatus : Idle
Associated LineInst : 1
PhysEndpt : 0
Extension : 122
DisplayName :
AuthName : 122
AuthPwd : 0000
TxGain : 0 dB
RxGain : 0 dB
CALLFEATURES:
MWI : off
Caller ID number : on
Caller ID name : on
CallWaiting : on
CFWDNum :
CallFwdAll : off
CallFwdBusy : off
CallFwdNoans : off
AnonymousOutgoingCall: off
AnonymousCallRcvBlock: off
DoNotDisturb : off
CallCompOnBusy : off
SpeedDial : off
WarmLine : off
WarmLineNum :
CallBarring : off
CallBarringMode : None
CallBarringPin : 9999
CallBarringDigitMap :
NetPrivacy : on
CODECSETTINGS:
VAD : on
pTime : 20
CodecList : (0) G.711MuLaw
(1) G.711ALaw
(2) G.723.1
(3) G.726_16
(4) G.726_24
(5) G.726_32
Account 1:
-----------
ActivationStatus : Enabled
VoipServiceStatus : Up
CallStatus : Idle
Associated LineInst : 2
PhysEndpt : 1
Extension : 121
DisplayName :
AuthName : 121
AuthPwd : 0000
TxGain : 0 dB
RxGain : 0 dB
CALLFEATURES:
MWI : off
Caller ID number : on
Caller ID name : on
CallWaiting : on
CFWDNum :
CallFwdAll : off
CallFwdBusy : off
CallFwdNoans : off
AnonymousOutgoingCall: off
AnonymousCallRcvBlock: off
DoNotDisturb : off
CallCompOnBusy : off
SpeedDial : off
WarmLine : off
WarmLineNum :
CallBarring : off
CallBarringMode : None
CallBarringPin : 9999
CallBarringDigitMap :
NetPrivacy : on
CODECSETTINGS:
VAD : on
pTime : 20
CodecList : (0) G.711MuLaw
(1) G.711ALaw
(2) G.723.1
(3) G.726_16
(4) G.726_24
(5) G.726_32
> exit
Bye bye. Have a nice day!!!
Connection closed by foreign host.
[/sample-session]
My aim is to obtain lines containing ActivationStatus and VoipServiceStatus.
So I wrote this script
#!/usr/bin/expect -f
set timeout 2
set ip_addr [lindex $argv 0]
set OUTFILE "voip_status.log"
spawn telnet 172.16.11.$ip_addr
expect {
timeout { send_user "\nFailed to get login prompt for $ip_addr\n"; exit 1 }
eof { send_user "\ntelnet failure for server $ip_addr\n"; exit 2 }
"*Login:"
}
#expect "*Login:"
send -- "user\r"
expect "*Password:"
send -- "user\r"
expect ">"
send -- "voice show\r"
expect ">"
set voice_full_output $expect_out(buffer)
set voice_stat_lines [ split $voice_full_output "\n" ]
foreach line $voice_stat_lines {
if {[string match "*VoipServiceStatus*" $line]} {
set timestamp [timestamp -format %Y-%m-%d_%H:%M:%S]
set chan [open $OUTFILE a+]
#puts "ok - MATCH $line"
puts $chan "$line $timestamp"
close $chan
}
if {[string match "*ActivationStatus*" $line]} {
set chan [open $OUTFILE a+]
#puts "ok - MATCH $line"
puts $chan "$line"
close $chan
}
}
send -- "exit\r"
expect eof
Here is my output
$ cat voip_status.log
ActivationStatus : Enabled
2021-03-17_11:32:35tus : Up
ActivationStatus : Enabled
2021-03-17_11:32:35tus : Up
As you can see that time stamp has overwritten the line I had filtered out.
I wanted timestamp to appear at the end of line .
Why is this happening ?
Here I made an experimental setup which anybody can run to see this behaviour.
Contents of 'output-voice-log-for-experiment.sh' follow
[file to give input]
#!/usr/bin/perl
print "
Account 0:
-----------
ActivationStatus : Enabled
VoipServiceStatus : Up
CallStatus : Idle
Associated LineInst : 1
PhysEndpt : 0
Extension : 122
DisplayName :
AuthName : 122
AuthPwd : 0000
TxGain : 0 dB
RxGain : 0 dB
CALLFEATURES:
MWI : off
Caller ID number : on
Caller ID name : on
CallWaiting : on
CFWDNum :
CallFwdAll : off
CallFwdBusy : off
CallFwdNoans : off
AnonymousOutgoingCall: off
AnonymousCallRcvBlock: off
DoNotDisturb : off
CallCompOnBusy : off
SpeedDial : off
WarmLine : off
WarmLineNum :
CallBarring : off
CallBarringMode : None
CallBarringPin : 9999
CallBarringDigitMap :
NetPrivacy : on
CODECSETTINGS:
VAD : on
pTime : 20
CodecList : (0) G.711MuLaw
(1) G.711ALaw
(2) G.723.1
(3) G.726_16
(4) G.726_24
(5) G.726_32
Account 1:
-----------
ActivationStatus : Enabled
VoipServiceStatus : Up
CallStatus : Idle
Associated LineInst : 2
PhysEndpt : 1
Extension : 121
DisplayName :
AuthName : 121
AuthPwd : 0000
TxGain : 0 dB
RxGain : 0 dB
CALLFEATURES:
MWI : off
Caller ID number : on
Caller ID name : on
CallWaiting : on
CFWDNum :
CallFwdAll : off
CallFwdBusy : off
CallFwdNoans : off
AnonymousOutgoingCall: off
AnonymousCallRcvBlock: off
DoNotDisturb : off
CallCompOnBusy : off
SpeedDial : off
WarmLine : off
WarmLineNum :
CallBarring : off
CallBarringMode : None
CallBarringPin : 9999
CallBarringDigitMap :
NetPrivacy : on
CODECSETTINGS:
VAD : on
pTime : 20
CodecList : (0) G.711MuLaw
(1) G.711ALaw
(2) G.723.1
(3) G.726_16
(4) G.726_24
(5) G.726_32
> exit
"
[/file to give input]
Contents of 'process-experimental-echo.sh' follow
[file to process input]
#!/usr/bin/expect -f
spawn ./output-voice-log-for-experiment.sh
set timeout 20
set OUTFILE "experimental_voip_status.log"
expect ">"
set voice_full_output $expect_out(buffer)
set voice_stat_lines [ split $voice_full_output "\n" ]
foreach line $voice_stat_lines {
if {[string match "*VoipServiceStatus*" $line]} {
set timestamp [timestamp -format %Y-%m-%d_%H:%M:%S]
set chan [open $OUTFILE a+]
puts "ok - MATCH $line"
puts $chan "$line $timestamp"
close $chan
}
if {[string match "*ActivationStatus*" $line]} {
set chan [open $OUTFILE a+]
puts "ok - MATCH $line"
puts $chan "$line"
close $chan
}
}
[/file to process input]
Now simply run ./process-experimental-echo.sh and see this behaviour yourself.
Here is the output file you will get
$ cat experimental_voip_status.log
ActivationStatus : Enabled
2021-03-17_12:27:11tus : Up
ActivationStatus : Enabled
2021-03-17_12:27:11tus : Up
Thanks.
If you look at the output file using cat -vet it shows the non-printing control characters, tabs, and end-of-line, and you get:
ActivationStatus : Enabled^M$
VoipServiceStatus : Up^M 2021-03-17_09:02:53$
You can see ^M in the middle of a line, which is carriage-return. On a terminal this makes the cursor go back to the start of the line, and start overprinting.
This is the typical result of spawn, which runs a command through a pty, which alters each output newlines into carriage-return and newline. This is normal and desired for a pty. You can either turn it off (see stty -onlcr), or knowing that it is likely to be there, you can remove it in your script: after the foreach ... line, trim the variable $line to remove \r:
set line [string trimright $line "\r"]

What is the Powershell equivalent of "Use the following IP Address" in the IPv4 properties UI?

I am looking for a Powershell command that disables DHCP and sets the machine's private IP as a static IP; basically, I'm looking for the Powershell equivalent of following actions in the UI.
Control panel -> Network and Sharing Center -> Ethernet -> Properties -> IPv4 -> Properties -> toggle off "Obtain an IP address automatically" and toggle on "Use the following IP address" -> fill out IPv4 address, default gateway, and subnet mask.
The following commands, taken from this guide, seems to describe what I'm after, but Remove-NetIPAddress results in kicking me off the server and locking me out.
$IP = "10.10.10.10"
$MaskBits = 24 # This means subnet mask = 255.255.255.0
$Gateway = "10.10.10.1"
$Dns = "10.10.10.100"
$IPType = "IPv4"
# Retrieve the network adapter that you want to configure
$adapter = Get-NetAdapter | ? {$_.Status -eq "up"}
# Remove any existing IP, gateway from our ipv4 adapter
If (($adapter | Get-NetIPConfiguration).IPv4Address.IPAddress) {
$adapter | Remove-NetIPAddress -AddressFamily $IPType -Confirm:$false
}
If (($adapter | Get-NetIPConfiguration).Ipv4DefaultGateway) {
$adapter | Remove-NetRoute -AddressFamily $IPType -Confirm:$false
}
# Configure the IP address and default gateway
$adapter | New-NetIPAddress `
-AddressFamily $IPType `
-IPAddress $IP `
-PrefixLength $MaskBits `
-DefaultGateway $Gateway
I'm unable to create a new IPv4 address so long as the existing one is still around, but removing the existing one borks the connection to the server.
That is incorrect. You can set multiple IPs on the same interface. So you simply add the new one with New-NetIPAddress and then remove the previous one.
$currentIP = Get-NetIPAddress | where ipaddress -eq '192.168.43.96'
New-NetIPAddress -InterfaceAlias $currentIP.InterfaceAlias -IPAddress 192.168.43.20 -PrefixLength 24
Remove-NetIPAddress -InterfaceAlias $currentIP.InterfaceAlias -IPAddress $currentIP.IPAddress
The DNS and Gateway are separate things. Just don't change those if you don't need to. To avoid the confirmation prompt, simply add -Confirm:$false to the Remove-NetIPAddress command.

How to parse the output in powershell?

The command Get-Process gives output like below:
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
65 6 1152 840 59 77.50 6048 Appx
78 8 2233 444 61 10.11 7878 Application
but I need a solution like below:
PM(K)=1152, ProcessName=Appx ; PM(K)=2233, ProcessName=Application
How do I parse output like above mentioned?
you can use -f to format your string :
PS>$resu=""
PS>gps | foreach {$resu+=("PM(K)= {0},appName={1};" -f ($_.pm/1KB),$_.name) }
PS>$resu
Try something like this:
$p = Get-Process | select #{n='PM(K)';e={$_.PM/1KB}}, ProcessName
($p | fl | Out-String) -replace "`n`n", ' ; ' -replace "`n", ', '

PowerShell equivalent of BASH (etc) 'type' command?

On *nix, using BASH (etc) you ask the system where a command is located (etc) by using the 'type' shell built-in like this:
$ type cat
cat is /bin/cat
Is there an equivalent of this 'type' command in Microsoft PowerShell 2.0 ?
An equivalent is Get-Command.
PS C:\> Get-Command ls
CommandType Name Definition
----------- ---- ----------
Alias ls Get-ChildItem
Application ls.exe D:\usr\local\wbin\ls.exe
Application ls.exe C:\Program Files (x86)\Git\bin\ls.exe
Windows 10 Update:
Since I've posted this answer, it appears that the behavior of Get-Command has changed. To include all results (in the style of Un*x) type), now I need to pass the -All flag, like so:
PS C:\> Get-Command -All ls
CommandType Name Version Source
----------- ---- ------- ------
Alias ls -> Get-ChildItem
Application ls.exe 0.0.0.0 C:\Program Files (x86)\Git\usr\bin\ls.exe
As noted in a comment, this doesn't include the Definition column as was the previous behavior. I can't determine a command-line argument to add the definition column, but as noted by #voutasaurus in the comment below, one can use:
PS C:\> (Get-Command -All ls).Definition
Get-ChildItem
C:\Program Files (x86)\Git\usr\bin\ls.exe
Version information for reference (I odn't have the version information associated with the original answer text, but I'm guessing that it was Windows 7):
PS C:\> [System.Environment]::OSVersion.Version
Major Minor Build Revision
----- ----- ----- --------
10 0 15063 0
Get-Command has a -ShowCommandInfo parameter that does this. It also works for functions defined in $profile :
PS C:\Users\vp937ll> Get-Command l -ShowCommandInfo
Name : l
ModuleName :
Module : #{Name=}
CommandType : Function
Definition : Get-ChildItem | Sort-Object -Property LastWriteTime -Descending
ParameterSets : {#{Name=__AllParameterSets; IsDefault=False; Parameters=System.Management.Automation.PSObject[]}}
Since you tagged this with Shell, in addition to PowerShell's Get-Command, there's where.exe:
PS C:\> where.exe notepad
C:\Windows\System32\notepad.exe
C:\Windows\notepad.exe
The command just looks for a file with the specified name through the path:
PS C:\> where.exe readme.*
C:\Python31\README.txt
C:\Program Files (x86)\wget\README
C:\Program Files (x86)\SysinternalsSuite\readme.txt
Note that when calling this command from PowerShell, you must call it as where.exe because Where-Object is aliased to where.
Get-Command seems right, aliased as gcm
Just pipe it to Select-Object * aliased as select *
E.g., in $profile I have a function that opens total commander from pwd (it silently kills the existing instance first)
function start-totalCommanderhere {
$here = (Get-Location).path
kill -n TOTALCMD64 -ErrorAction Ignore
start "c:\totalcmd\TOTALCMD64.EXE" $here
}
Set-Alias tc start-totalCommanderhere
Here is all the info about the function — it however does not tell you directly that it is a function, you would need to query its proper name not alias to get that information from CommandType attribute. (than it would be same as type in bash which tells you hello_world is a function in case it is one)
▶ gcm tc | select *
HelpUri :
ResolvedCommandName : start-totalCommanderhere
DisplayName : tc -> start-totalCommanderhere
ReferencedCommand : start-totalCommanderhere
ResolvedCommand : start-totalCommanderhere
Definition : start-totalCommanderhere
Options : None
Description :
OutputType : {}
Name : tc
CommandType : Alias
Source :
Version :
Visibility : Public
ModuleName :
Module :
RemotingCapability : PowerShell
Parameters : {}
ParameterSets :
gcm <module_name> | select * gives you the path if you ask for a CommandType which is Application
▶ gcm ping | select *
HelpUri :
FileVersionInfo : File: C:\Windows\system32\PING.EXE
InternalName: ping.exe
OriginalFilename: ping.exe.mui
FileVersion: 10.0.19041.320 (WinBuild.160101.0800)
FileDescription: TCP/IP Ping Command
Product: Microsoft® Windows® Operating System
ProductVersion: 10.0.19041.320
Debug: False
Patched: False
PreRelease: False
PrivateBuild: False
SpecialBuild: False
Language: English (United States)
Path : C:\Windows\system32\PING.EXE
Extension : .EXE
Definition : C:\Windows\system32\PING.EXE
Source : C:\Windows\system32\PING.EXE
Version : 10.0.19041.1
Visibility : Public
OutputType : {System.String}
Name : PING.EXE
CommandType : Application
ModuleName :
Module :
RemotingCapability : PowerShell
Parameters :
ParameterSets :
But with gcm you do not get paths for imported modules — for that you need to use Get-Module | Select-Object Name, Path aliased as gmo | select name,path
▶ gmo | select name, path
Name Path
---- ----
assign-vault-keys-to-env-vars C:\Users\Admin\Documents\workspace\work.log\kb\powershell\assign-vault-keys-to-env-vars.ps1
CimCmdlets C:\Program Files\PowerShell\7\Microsoft.Management.Infrastructure.CimCmdlets.dll
decode-base64 C:\Users\Admin\Documents\workspace\work.log\kb\powershell\decode-base64.ps1
DnsClient C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\DnsClient\DnsClient.psd1
...

Resources