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

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 :)

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

PowerShell :: How to filter worker processes list by User Name

Basically as per screen-shot there are multiple worker processes are running on machine in IIS but we need w3wp which is running under Sitecore User Username.
We tried below PS script but getting blank value in User Name column
$processlist = get-process | where {$_.cpu -gt 5 -and $_.Name -eq 'w3wp'} |select Name, #{l="User name";e={$_.getowner().user}} | ft -AutoSize
foreach($proc in $processlist){
if($proc -eq "Sitecore User" ){
C:\Users\Administrator\Documents\someexe.exe $proc.Id "C:\Users\Administrator\Documents\output.dmp"
}
}
and finally we need to perform some action on process Id.
I suggest the following PoSh-Script that should give you all the necessary info and more:
# Ensure to import the WebAdministration module
Import-Module WebAdministration
# Declare the variables
$server = "localhost"
$search = "*"
$wmiQuery=[wmisearcher]"SELECT * FROM __Namespace where NAME like 'WebAdministration' or NAME like 'MicrosoftIISv2'"
$wmiQuery.Scope.Path = "\\" + $server + "\root"
$WebNamespace = $wmiQuery.Get()
# Checking if the the server has IIS installed
if($WebNamespace -like '*WebAdministration*')
{
"IIS found on $server"
$WPlist=Get-WmiObject -NameSpace 'root\WebAdministration' -class 'WorkerProcess' -ComputerName 'LocalHost'
# Loop through the list of active IIS Worker Processes w3wp.exe and fetch the PID, AppPool Name and the startTime
forEach ($WP in $WPlist)
{
if ($WP.apppoolname -like$search)
{
write-host "Found:""PID:"$WP.processid "AppPool_Name:"$WP.apppoolname
(get-process -ID $WP.processid|select starttime)
}
}
}
Else
{
write-host"WARNING: IIS not detected."
}
Ref: https://blogs.msdn.microsoft.com/webtopics/2015/11/28/query-the-active-worker-process-information-in-iis-7-x-using-powershell/

How to Verify Reserved IP with 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
}

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"}

Changing an IP Address in Powershell

I am trying to get an IP address from the computer and then check the address to see if it is in a certain range. However I'm really unsure of how exactly to do this. I have figured out how to get the IP address form the computer but then checking it against the range is another story...
This is what I have so far:
Get-WMIObject win32_NetworkAdapterConfiguration | Where-Object { $_.IPEnabled -eq $true } | Foreach-Object { $_.IPAddress } | Foreach-Object { [IPAddress]$_ } | Where-Object { $_.AddressFamily -eq 'Internetwork' } | Foreach-Object { $_.IPAddressToString }
If ($_.IPAddressToString -eq 192.168.0.10 - 192.168.0.50)
{Write-host $_.IPAddressToString}
else ($_.IPAddressToString -ne 192.168.0.10 - 192.168.0.50)
{$_.IPAddressToString = 192.168.0.15}
The first line is what I am using to get the IP address. I was looping up if statements so that if the address was in the range then it won't do anything but output the address. I made an else statement for the IP address to be changed if the IP is not in the right range.
There isn't anything that I found that is in between. I don't know how to script out 192.168.0.10 - 192.168.0.50. I also couldn't really find anything that allows me to check that the IP address is in that range, so I just used equal to and not equal. Needless to say it obviously didn't work.
Try this, change to fit your low and high.
$ipLow = [IPAddress] "192.168.9.10"
$ipHigh = [IPAddress] "192.168.9.60"
[Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | ? {$_.OperationalStatus -eq "Up"} | % {
$addrs = $_.GetIPProperties().UnicastAddresses
if ($addrs) {
foreach ($addr in $addrs) {
if ($addr.Address.AddressFamily -eq 'InterNetwork') {
if ($addr.Address.Address -ge $ipLow.Address -and $addr.Address.Address -le $ipHigh.Address) {
$addr.Address
}
}
}
}
}