How to Verify Reserved IP with Powershell - powershell

I am working on a little powershell 3.0 GWMI script that pulls computer information for use in an enterprise environment (ip, mac address, etc).
I'm trying to go through the WMI properties for NetworkAdapterConfiguration to see if there is a way to check for a reserved IP vs. a dynamically assigned one.
Would anyone have advice on how to pull this from WMI or elsewhere? Does (preferred) always indicate that an IP is reserved on the network?
I'm finding a lot of information for powershell and Azure but not a ton for figuring this out on a local box.

As Ron Maupin noted, Host computers will only know whether they were assigned an addressed from the DHCP, not if there was a reservation. But they will report which DHCP server they received their address from. So you can query that server (assuming you have read permissions).
Here is a script that after retrieving the information from a computer over WMI will check with the DHCP server if a reservation exists.
$ComputerName = "ExampleComputer"
$NetAdapters = Get-WmiObject Win32_NetworkAdapterConfiguration -ComputerName $ComputerName | ? {$_.DHCPEnabled -eq $True -and $null -ne $_.IPAddress}
If ($NetAdapters) {
Foreach ($Adapter in $NetAdapters) {
foreach ($IP in $Adapter.IPAddress) {
$Reservation = Get-DhcpServerv4Reservation -ScopeId $IP -ComputerName $Adapter.DHCPServer | ? {$_.ScopeId -eq $_.IPAddress}
If ($Reservation) {
Write-Output "$IP is reserved on $($Adapter.DHCPServer)."
} Else {
Write-Output "$IP does not have a reservation."
}
}
}
} Else {
Write-Output "No DHCP Enabled NetAdapters with IPAddresses exist on host, likely Static"
}

Using the above script provided by BenH I was able to cobble together a script that worked across my fleet of AWS servers from SSM using the AWS-RunPowerShellScript run document which would give me a fail status if any of my instances weren't configured for DHCP. We had a few lingering out there which were using our DHCP Options Set in our VCP and this helped uncover them. Thanks!
$NetAdapters = Get-WmiObject Win32_NetworkAdapterConfiguration | ? {$_.DHCPEnabled -eq $True -and $null -ne $_.IPAddress} | Select Description
If ($NetAdapters) {
Foreach ($Adapter in $NetAdapters.Description) {
Write-Output "DHCP is enabled on $Adapter"
exit 0
}
} Else {
Write-Output "DHCP is not enabled on any adapters on host, likely Static"
exit 1
}

Related

How to see the hostname when you ping the server?

I pinged the servers and it is working (it shows me the ip address that could be pinged) but I want it to show the hostname and the ip address.
I tried to incorporate [System.Net.Data.Dns]::GetHostName(), but I don't know where to put it. I am a beginner using PowerShell. I also tried to used -and, but it doesn't work.
I understand how to do it python I just don't know how to translate it to PowerShell.
$columnC = "n1-1mon-i3fp04","n1-1mon-i3fp06","n1-1mon-i3fp07","n1-r-1mon-i3fp09","n1-r-1mon-i3fp10","n1-1mon-i3fp08","n1-1mon-i3fp03","n1-1mon-i3fp02","n1-1mon-i3fp111"
$columnC | % $_ {$Device = Resolve-DnsName -Name $_
$Device.[System.Net.Data.Dns]::GetHostName()
if (test-connection $Device.("IPAddress")) {write-host Device.("IPAddress") "Ping succeeded." -foreground green}
else {write-host $Device.("IPAddress") "Ping failed." -foreground red}}
The result shows an error message like the syntax is wrong. I want it to show both ip address and the hostname.
[edit - Theo pointed out that GetHostByName has been deprecated in favor of GetHostEntry. when i tested that, it gave more consistent results, so i swapped them.]
this will get the ComputerName, HostName, and Online status. then save those into a custom object, send the object to the $Results collection, and - finally - show what is in the collection. [grin]
# fake reading in a text file
# in real life use Get-Content
$ComputerList = #'
BetterNotBeThere
LocalHost
10.0.0.1
127.0.0.1
'# -split [environment]::NewLine
$Results = foreach ($CL_Item in $ComputerList)
{
try
{
$HostName = [System.Net.Dns]::GetHostEntry($CL_Item).HostName
}
catch
{
$HostName = '__Not Found__'
}
[PSCustomObject]#{
ComputerName = $CL_Item
HostName = $HostName
Online = Test-Connection -ComputerName $CL_Item -Count 1 -Quiet
}
}
$Results
output ...
ComputerName HostName Online
------------ -------- ------
BetterNotBeThere __Not Found__ False
LocalHost [MySysName] True
10.0.0.1 __Not Found__ False
127.0.0.1 [MySysName] True

Difference between "RenewDHCPLease()" and "IPConfig /renew"?

I am using RenewDHCPLease() to renew the IP address of the system.
What is the exact difference between RenewDHCPLease() and ipconfig /renew?
Which one is better to use in Powershell?
Is it necessary to use ReleaseDHCPLease() before RenewDHCPLease()? If so why?
Below is my code:
try {
$ips = Get-WmiObject -Class Win32_NetworkAdapterConfiguration | Where { $_.IpEnabled -eq $true -and $_.DhcpEnabled -eq $true} -ErrorAction Stop
if (!$ips) {
Write-Output "`nDHCP is not Enabled on this system"
Exit
}
foreach ($ip in $ips) {
Write-Output "`nRenewing IP Addresses"
$ip.RenewDHCPLease() | Out-Null
if ($?) {
Write-Output "IP address has been renewed for this system"
}
else {
Write-Error "IP Address Could not be renewed"
}
}
}
catch {
$_.Exception.Message
}
ReleaseDHCPLease releases the IP address bound to a specific DHCP enabled network adapter
RenewDHCPLease Renews the IP address on a specific DHCP enabled network adapter
There is no need to use ReleaseDHCPLease before RenewDHCPLease since the old address is released and a new one is automatically acquired when using RenewDHCPLease
Get-WmiObject Win32_NetworkAdapterConfiguration -Filter 'IpEnabled=True AND DhcpEnabled=True' | Foreach-Object{
$_.RenewDHCPLease()
}
You could also use the RenewDHCPLeaseAll method to renew them all at once. Hope this helps :)

powershell - storing cmdlet Get-DhcpServerv4Reservation into a variable and then printing it, doesn't give expected output

I'm running a DHCP server in Windows Server 2012 R2 with an active scope and I've made a script which asks the user for a MAC address and will then reserve an available ip from the scope to the user's MAC.
The actual reservation works without a problem but I've introduced an IF ELSE statement, with the hope that the conditional expression is evaluated as TRUE when a reservation is successful and to FALSE otherwise.
But the expression always evaluates to FALSE because storing the execution of the cmdlet Get-DhcpServerv4Reservation into a variable and then printing it, yields a really messed up output: basically it will print "DHCPServerv4Reservation" as many times as reservations present in the scope, instead of the output given when directly executing the cmdlet.
Here's the code:
clear-host
$mac=read-host -prompt "Please type the MAC address for the host "
$freeip=Get-DhcpServerv4FreeIPAddress -scopeid 10.10.10.0
Add-DhcpServerv4Reservation -ScopeId 10.10.10.0 -ClientId $mac -IPAddress $freeip
$reservedips=Get-DhcpServerv4Reservation -ScopeId 10.10.10.0
if ($reservedips -match $freeip) {
write-host "The ip $freeip has been succesfully reserved for the host with the MAC address $mac"
}
else {write-host "I'm sorry but there are no free ip addresses to be reserved"}
# this is just to see what's inside $reservedips
write-host $reservedips
Why is this happening? Thanks
The result of Get-DhcpServerv4Reservation is a reservation object.
The -match operator is for matching a string against a regular expression.
You might be looking to something like:
if (($reservedips | Where-Object { $_.IPAddress -eq $freeip })) {
# success
}
I think you consider restructuring your code to look something like this:
$mac=read-host -prompt "Please type the MAC address for the host "
$freeip=Get-DhcpServerv4FreeIPAddress -scopeid 10.10.10.0
try {
Add-DhcpServerv4Reservation -ScopeId 10.10.10.0 -ClientId $mac -IPAddress $freeip -ErrorAction Stop
} catch {
Write-Host "An error has occurred while trying to add a reservation for '$mac' with IP '$freeip'."
}
Adding -ErrorAction Stop forces all exceptions to be caught by the try/catch block.
This is the alternative I have come up with, which works
clear-host
$mac=read-host -prompt "Please type the MAC address for the host "
$freeip=Get-DhcpServerv4FreeIPAddress -scopeid 10.10.10.0
Add-DhcpServerv4Reservation -ScopeId 10.10.10.0 -ClientId $mac -IPAddress $freeip
$reservedips=Get-DhcpServerv4Reservation -ScopeId 10.10.10.0 | Where-Object ipaddress -eq $freeip
if ($reservedips -eq "") {write-host "I'm sorry but there are no free ip addresses to be reserved"}
else {write-host "The ip $freeip has been succesfully reserved for the host with the MAC address $mac"}

How to verify whether a windows server has mountpoint or not using WMI

I am generating a report where I need to find which servers has mountpoints configured on it..
can you help how to get that infor using WMI or powershell.
I mean I need to identify the servers, if mountpoints exists in it.. and also their names....
Get a list of all servers from textfile, AD, etc. and run a foreach loop with something like this:
Get-Wmiobject -query “select name,driveletter,freespace from win32_volume where drivetype=3 AND driveletter=NULL” -computer servername
A quick google search for "windows mount point wmi" would return THIS (source).
Then export the results to CSV, HTML or whatever you need. Your question is lacking a lot of details and any sign of effort from your part, so I can't/won't go any further.
UPDATE: Does this help? It lists mount points(folder paths, not driveletters).
$servers = #("server1","server2","server3","server4","server5")
$servers | % {
$mountpoints = #(Get-WmiObject Win32_MountPoint -ComputerName $_ | Select-Object -ExpandProperty Directory | ? { $_ -match 'Win32_Directory.Name="(\w:\\\\.+)"' }) | % { [regex]::Match($_,'Win32_Directory.Name="(\w:\\\\.+)"').Groups[1].Value -replace '\\\\', '\' }
if($mountpoints.Count -gt 0) {
New-Object psobject -Property #{
Server = $_
MountPoints = $mountpoints
}
}
}
Server MountPoints
------ -----------
{server1} {D:\SSD, C:\Test}

How to find IpAddress of a virtual machine programmatically from hypervisor?

I am using HyperV WMI provider to to update virtual machine's configuration/settings (like hard ware, disks etc..)
How can I get IpAddress of a VM from HyperV?
How to do the same thing in VMWare?
Regards,
Dreamer!
This article describes how to get the IP address of a virtual
machine from Hyper-V (Windows 2008 R2 Hyper-V) using Powershell.
Using the PowerCli: (get-vm <name of your vm>).guest.ipaddress
For Hyper-V, this is how I usually pull an IP from a host box.
$vm = Get-WmiObject -computerName "." -NameSpace "Root\Virtualization" -query "SELECT * FROM Msvm_KvpExchangeComponent" #pulls VM WMI object ExchangeComponents
$vmitems = $vm.GuestIntrinsicExchangeItems
$ipitem = $vmitems[-4]#yay! a hack that relies on XML schemas!
$xmlip = [xml]$ipitem #convert string format to XML
$ipaddr = $xmlip.INSTANCE.PROPERTY[1].VALUE #playing with XML schemas again hopefully reliably
It's not the neatest/cleanest/nicest code, but it is a way to get that information.
Here's an alternate variation that I cooked up to demonstrate a more robust approach at finding the value for a given name. This doesn't rely on a specific relative ordering inside the schema of Caption, Data, Description, ElementName, Name or Source
$vmParams = #{
NameSpace = 'Root\Virtualization';
Query = 'SELECT * FROM Msvm_KvpExchangeComponent' #pulls VM WMI object ExchangeComponents
}
Get-WmiObject #vmParams |
% {
$xml = [Xml]"<properties>$($_.GuestIntrinsicExchangeItems)</properties>"
$xml.properties.INSTANCE.Property |
% {
$value = ($_.ParentNode.Property | ? { $_.Name -eq 'Data' }).VALUE
if ($_.Value -eq 'FullyQualifiedDomainName')
{
Write-Host "Host: $($value)"
}
if ($_.Value -eq 'RDPAddressIPv4')
{
Write-Host "RDP Address: $($value)"
}
}
}