Why is Get-DnsClientServerAddress | select AddressFamily output not IPv4 and IPv6 - powershell

When I type the cmdlet Get-DnsClientServerAddress I get all the interfaces my PC has like for example
InterfaceAlias Interface Address ServerAddresses
Index Family
-------------- --------- ------- ---------------
Ethernet 7 IPv4 {10.10.15.40, 10.10.25.44}
So when I type in Get-DnsClientServerAddress | where AddressFamily -Like "4" I would expect to see the Ethernet Adapter.
But for any reason it didn't show up. So I typed Get-DnsClientServerAddress | select AddressFamily and what I got was
AddressFamily
-------------
2
23
2
23
Can anyone explain this to me ?

As you found, the AddressFamily is categorised internally using a (not obvious) numbering scheme, where IPv4 addresses are type '2'. This comes from the underlying WMI type (MSFT_DNSClientServerAddress) and is not an issue with PowerShell.
The default display helps you out by translating this to IPv4, etc, but you can't filter on that as it's for display only. You can, however, still filter if you use the correct value:
Get-DnsClientServerAddress | Where-Object AddressFamily -Like 2
This formatting of data for display purposes happens all the time in PowerShell and is acheived through Format.ps1xml files. For example, compare the output of the Working Set values from Get-Process in table and list format:
PS C:\> Get-Process powershell
Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
------- ------ ----- ----- ------ -- -- -----------
662 31 97928 110256 1.27 11452 2 powershell
PS C:\> Get-Process powershell | Format-List *
Handles : 705
VM : 2204040044544
WS : 113082368
PM : 100356096
NPM : 31512
The property (itself added by PowerShell for convenience) is called WS, but is shown as WS(K) in the table and the actual value is stored in bytes, but is displayed in KB, so some manipulation is going on for the default output.

Following from my comment, I would use Get-NetIPAddress instead.
Get-NetIPAddress -InterfaceAlias "Ethernet" | Select-Object FamilyAddress

Related

Fetching values from Net Use command using powershell

I am trying to get network mapped drives using below commands.
Get-WmiObject -Class Win32_MappedLogicalDisk | %{$_.Name}
Get-WmiObject -Class Win32_MappedLogicalDisk | %{$_.ProviderName}
This works in some system however does not in other systems(may be powershell version issue) So I thought of using net use command. However, I am unable to fetch the values or not sure how to get the values displays when i type 'net use'
when I type net use I get status, Local, Remote and Network column. I tried to use the below command to get the field values.
net use | select local.
but I get blank or nothing
Used below command.
net use | select local.
Need to get Local and Remote values from net use command.
See this for parsing legacy console output ---
How to Convert Text Output of a Legacy Console Application to PowerShell Objects
Yet, along with what LotPings gave you already. Your query could be a duplicate of this ...
Equivalent of net use (to list computer's connections) in powershell?
... and it's accepted answer
# For the mapped logical drive you can use WMI class Win32_MappedLogicalDisk :
Get-WmiObject Win32_MappedLogicalDisk
# Here is another way with Win32_LogicalDisk :
PS C:\> Get-WmiObject -Query "Select * From Win32_LogicalDisk Where DriveType = 4"
DeviceID : V:
DriveType : 4
ProviderName : \\jpbdellf1\c$
FreeSpace :
Size :
VolumeName :
# Edited
# You are right, you can get what you need with Win32_NetworkConnection :
Get-WmiObject Win32_NetworkConnection
LocalName RemoteName ConnectionState Status
--------- ---------- --------------- ------
\\jpbasusf1\temp Connected OK
# On Seven or W2K8 be careful to call this with the same user that run the NET USE because it's a session information.
How about using get-psdrive (the root header actually matches the displayroot property)?
get-psdrive | where displayroot -like '\\*'
Name Used (GB) Free (GB) Provider Root
---- --------- --------- -------- ----
Y 91.84 7.82 FileSystem \\server....
Depending on the PowerShell versions available you might encounter similar problems with
Get-SmbMapping which wraps the CimClass: ROOT/Microsoft/Windows/SMB:MSFT_SmbMapping.
But has otherwise an output resembling net use.
To process the real net use output and convert to an object with properties,
you may use:
$SmbMapping = (net use) -like '* \\*' | ForEach-Object {
$Status,$Local,$Remote,$Null = $_ -split ' +',4
[PSCustomObject]#{
Status = $Status
Local = $Local
Remote = $Remote
}
}
This works at least in my German locale Win10.
(Not sure about different status messages in other locales.)

VMWare PowerCLI Get DiskUsage of powered off vm's

I'm creating a script that gets all vm's and shows the DiskSpace. THe Problem is, that if a vm is powered off, it won't show the uesed Space of a disk.
Here are two examples: First one with an VM that is powered on:
PowerCLI C:\> Get-VM sluwv0039
Name PowerState Num CPUs MemoryGB
---- ---------- -------- --------
sluwv0039 PoweredOn 2 4.000
PowerCLI C:\> $VM = Get-VM sluwv0039
PowerCLI C:\> $VM.guest.disks
CapacityGB FreeSpaceGB Path
---------- ----------- ----
49.997 5.417 C:\
Example two where the VM is powered off:
PowerCLI C:\> Get-VM sluwv0012
Name PowerState Num CPUs MemoryGB
---- ---------- -------- --------
sluwv0012 PoweredOff 4 8.000
PowerCLI C:\> $VM = Get-VM sluwv0012
PowerCLI C:\> $VM.guest.disks
PowerCLI C:\>
Note: The Last line is the output. There is no "CapacityGB" etc.
Correct, that property is reading from the guest file system to see how much space is left on the partition. In your case, the C:\ drive. If the VM is off, there's no way for PowerCLI to find that property.
Alternatively, you could look at the $vm.ExtensionData.Summary.Storage properties and do some rough conversions. Note: the output of those are in byte, so you'll want to convert them to GB. Example: $tempVM.ExtensionData.Summary.Storage.Committed / 1GB
It won't be exact, but it will be better than no output at all.
here is example of script to show vm specification:
Get-Vm | Select-Object Name,PowerState,VMHost,NumCPU,MemoryGB,ProvisionedSpaceGB,#{N="HostName";E={#($.guest.HostName)}},#{N="Gateway";E={#($.ExtensionData.Guest.IpStack.IpRouteConfig.IpRoute.Gateway.IpAddress[0])}},#{N="DNS";E={$.ExtensionData.Guest.IpStack.DnsConfig.IpAddress}},#{N="IPAddress";E={#($.guest.IPAddress -like "192.168.*")}},#{N="Nics";E={#($.guest.Nics)}},#{N="Datastore";E={#($ | Get-DataStore)}},#{N="Disks";E={#($.guest.Disks)}},Version,#{N="State";E={#($.guest.State)}},#{N="OS";E={#($_.guest.OSFullName)}}
the sample output is like this:
Name State VMHost NumCpu MemoryGB PowerState ProvisionedSpaceGB Version IPAddress HostName OS Nics Disks VMwareTools Gateway DNS
test Running 192.168.32.100 2 1 PoweredOn 43.1085147 v8 192.168.122.1 Elenoon Ubuntu Linux (64-bit) Network adapter 1:VM Network Network adapter 2:local : : Capacity:17167286272, FreeSpace:14212493312, Path:/ Capacity:15188623360, FreeSpace:15154872320, Path:/media/files Capacity:10724835328, FreeSpace:10672824320, Path:/var/log Capacity:973770752, FreeSpace:690139136, Path:/boot guestToolsRunning 127.0.0.1
hope to be useful ;)

Determining internet connection using Powershell

Is there a simple cmdlet I can run in PowerShell to determine if my Windows machine is connected to the internet through Ethernet or through the wireless adapter? I know you can determine this on the GUI, I just want to know how this can be managed in PowerShell.
The PowerShell cmdlet Get-NetAdapter can give you a variety of info about your network adapters, including the connection status.
Get-NetAdapter | select Name,Status, LinkSpeed
Name Status LinkSpeed
---- ------ ---------
vEthernet (MeAndMahVMs) Up 10 Gbps
vEthernet (TheOpenRange) Disconnected 100 Mbps
Ethernet Disconnected 0 bps
Wi-Fi 2 Up 217 Mbps
Another option is to run Get-NetAdapterStatistics which will show you stats only from the currently connected device, so we could use that as a way of knowing who is connected to the web.
Get-NetAdapterStatistics
Name ReceivedBytes ReceivedUnicastPackets SentBytes SentUnicastPackets
---- ------------- ---------------------- --------- ------------------
Wi-Fi 2 272866809 323449 88614123 178277
Better Answer
Did some more research and found that if an adapter has a route to 0.0.0.0, then it's on the web. That leads to this pipeline, which will return only devices connected to the web.
Get-NetRoute | ? DestinationPrefix -eq '0.0.0.0/0' | Get-NetIPInterface | Where ConnectionState -eq 'Connected'
ifIndex InterfaceAlias AddressFamily InterfaceMetric Dhcp ConnectionState
------- -------------- ------------- --------------- ------- ---------------
17 Wi-Fi 2 IPv4 1500 Enabled Connected
Get-NetConnectionProfile
will return something like this for each connected network adapter using the Network Connectivity Status Indicator (the same indicator as used in the properties of a network device):
Name : <primary DNS suffix>
InterfaceAlias : Ethernet
InterfaceIndex : 9
NetworkCategory : DomainAuthenticated
IPv4Connectivity : Internet
IPv6Connectivity : LocalNetwork
Name : <primary DNS suffix>
InterfaceAlias : WiFi
InterfaceIndex : 12
NetworkCategory : DomainAuthenticated
IPv4Connectivity : Internet
IPv6Connectivity : LocalNetwork
You should be able to use the IPv4Connectivity or IPv6Connectivity to give you a true/false value what you want. The following will check if Windows thinks any network device is connected to the Internet via either IPv4 or IPv6:
$AllNetConnectionProfiles = Get-NetConnectionProfile
$AllNetConnectionProfiles.IPv4Connectivity + $AllNetConnectionProfiles.IPv6Connectivity -contains "Internet"
I wrote a function that does this. It should work on all versions of PowerShell, but I have not tested it on XP / Server 2003.
function Test-IPv4InternetConnectivity
{
# Returns $true if the computer is attached to a network that has connectivity to the
# Internet over IPv4
#
# Returns $false otherwise
# Get operating system major and minor version
$strOSVersion = (Get-WmiObject -Query "Select Version from Win32_OperatingSystem").Version
$arrStrOSVersion = $strOSVersion.Split(".")
$intOSMajorVersion = [UInt16]$arrStrOSVersion[0]
if ($arrStrOSVersion.Length -ge 2)
{
$intOSMinorVersion = [UInt16]$arrStrOSVersion[1]
} `
else
{
$intOSMinorVersion = [UInt16]0
}
# Determine if attached to IPv4 Internet
if (($intOSMajorVersion -gt 6) -or (($intOSMajorVersion -eq 6) -and ($intOSMinorVersion -gt 1)))
{
# Windows 8 / Windows Server 2012 or Newer
# First, get all Network Connection Profiles, and filter it down to only those that are domain networks
$IPV4ConnectivityInternet = [Microsoft.PowerShell.Cmdletization.GeneratedTypes.NetConnectionProfile.IPv4Connectivity]::Internet
$internetNetworks = Get-NetConnectionProfile | Where-Object {$_.IPv4Connectivity -eq $IPV4ConnectivityInternet}
} `
else
{
# Windows Vista, Windows Server 2008, Windows 7, or Windows Server 2008 R2
# (Untested on Windows XP / Windows Server 2003)
# Get-NetConnectionProfile is not available; need to access the Network List Manager COM object
# So, we use the Network List Manager COM object to get a list of all network connections
# Then we check each to see if it's connected to the IPv4 Internet
# The GetConnectivity() method returns an integer result that can be bitwise-enumerated
# to determine connectivity.
# See https://msdn.microsoft.com/en-us/library/windows/desktop/aa370795(v=vs.85).aspx
$internetNetworks = ([Activator]::CreateInstance([Type]::GetTypeFromCLSID([Guid]"{DCB00C01-570F-4A9B-8D69-199FDBA5723B}"))).GetNetworkConnections() | `
ForEach-Object {$_.GetNetwork().GetConnectivity()} | Where-Object {($_ -band 64) -eq 64}
}
return ($internetNetworks -ne $null)
}
Test-Connection -ComputerName $servername
Where $servername is a web address. Use the -Quiet switch to return true/false.

What is the -view parameter of Format-List?

Format-List apparently has a string parameter named "view", as can be seen here. What does it do, and how does it work? I cannot find any documentation beyond "The name of an alternate format or 'view.'"
The '-View' parameter on the various Format-* cmdlets allows you to get various different "views" or formattings of the data e.g.:
PS> Get-Process
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
672 56 272684 220692 975 141.45 8480 powershell
692 34 47184 60156 234 23.73 17048 powershell
751 82 217624 162780 1047 157.73 13336 powershell_ise
versus
PS> Get-Process | Format-Table -View StartTime
StartTime.ToShortDateString(): 1/14/2013
ProcessName Id HandleCount WorkingSet
----------- -- ----------- ----------
powershell 8480 672 225988608
StartTime.ToShortDateString(): 2/6/2013
ProcessName Id HandleCount WorkingSet
----------- -- ----------- ----------
powershell 17048 624 92418048
StartTime.ToShortDateString(): 1/17/2013
ProcessName Id HandleCount WorkingSet
----------- -- ----------- ----------
powershell_ise 13336 771 166686720
As for determining which commands support alternate views, you can usually find such info in the docs. Here's an excerpt from the Get-Process help:
You can also use the built-in alternate views of the processes
available with Format-Table, such as "StartTime" and "Priority", and
you can design your own views. For more information, see
T:Microsoft.PowerShell.Commands.Format-Table.
The PowerShell Community Extensions also includes a command called Get-ViewDefinition that can get this info when the docs aren't available (or of much help in this regards.

PowerShell: Getting Help on Get-Process -Property CPU

With PowerShell 3, I tried to get help on what properties are available for CPU; while using Get-Process. I just tried a shot in the dark, as below:
Help Get-Process -Property CPU
But, failed. Any help, please!
What are you looking for? Information about your processor? Get-Process list running processes(e.g. internet explorer) on your computer, not info about your processor-chips(CPU). Ex:
Get-Process
Output:
Handles NPM(K) PM(K) WS(K) VM(M) CPU(s) Id ProcessName
------- ------ ----- ----- ----- ------ -- -----------
284 25 7128 8748 103 1608 AppleMobileDeviceService
75 7 1136 1528 44 1588 armsvc
703 82 6612 7732 114 1,25 4212 AsusAudioCenter
Information about your processor can be found using:
Get-WmiObject Win32_Processor
Output:
Caption : Intel64 Family 6 Model 42 Stepping 7
DeviceID : CPU0
Manufacturer : GenuineIntel
MaxClockSpeed : 3400
Name : Intel(R) Core(TM) i7-2600 CPU # 3.40GHz
SocketDesignation : LGA1155
To get all properties about your CPU use Get-WmiObject Win32_Processor | fl *. To get a list of avaiable properties, use the Get-Member cmdlet to examine the object that Get-WmiObjectreturns:
Get-WmiObject Win32_Processor | Get-Member
Your shot in the dark missed. Also, since your description of what went wrong is nothing more than "But, failed.", I can only guess at what your problem might be. In order to better help you use help you need to help us by providing pertinent information about your problem such as error messages.
Firstly, Help (or the Get-Help cmdlet) does not have a -Property parameter. -Parameter might be what you looking for, however running Help Get-Process -Parameter CPU will reveal that the Get-Process cmdlet does not have a CPU parameter.
Secondly, Get-Process returns instances of the System.Diagnostics.Process class. The documentation or running Get-Process | Get-Member will show you what properties that class exposes. You can retrieve them by running something like...
Get-Process | Select-Object -Property (
'ProcessName',
'Id',
'ProcessorAffinity',
'UserProcessorTime',
'PrivilegedProcessorTime',
'TotalProcessorTime'
);
Finally, unlike previous versions PowerShell 3.0 does not install local help content. You need to run the Update-Help cmdlet to download and install help content. Alternatively, when running Get-Help you can pass the -Online parameter which will open the help content from MSDN in a web browser.