Get-NetIPAddress
Getting an IP Address from a machine is something we need to do often, for many reasons. Typically, you would employ the CLI tool IPCONFIG to get it, and if you wanted to quickly get just the IP Addresses for your machine, you might use:
ipconfig -all | findstr IPv4
The output of which would look like:
C:\>ipconfig -all | findstr IPv4
IPv4 Address. . . . . . . . . . . : 129.168.34.233(Preferred)
IPv4 Address. . . . . . . . . . . : 129.168..93.194(Preferred)
Which is fine but doesn't give you the flexibility to use that information within a powershell script to do other things, so where's the fun in that? Also, getting it with powershell is a necessary skill for anyone that administers servers (at least to my way of thinking). I wrote the following code and saved it as "Get-IpAddress.ps1" on all my machines. It gives me the output I want in the format I want for most of my quick needs:
$strComputer ="."
$colItems = Get-WmiObject Win32_NetworkAdapterConfiguration -Namespace "root\CIMV2" | where{$_.IPEnabled -eq “True”}
Write-Host " "
Write-Host "********************************************"
Write-Host " "
foreach($objItem in $colItems) {
Write-Host "Adapter:" $objItem.Description
Write-Host " DNS Domain:" $objItem.DNSDomain
Write-Host " IPv4 Address:" $objItem.IPAddress[0]
Write-Host " IPv6 Address:" $objItem.IPAddress[1]
Write-Host " "
}
Write-Host "********************************************"
Write-Host " "
I can then run it from any powershell prompt by invoking the script. The output of the above script is:
PS C:\scripts> .\Get-IpAddress
********************************************
Adapter: Intel(R) Centrino(R) Advanced-N 6205
DNS Domain: global.mydomain.com
IPv4 Address: 192.10.93.194
IPv6 Address: fe99::68a8:5ac:89b2:ffff
Adapter: Intel(R) 82579LM Gigabit Network Connection
DNS Domain: global.mydomain.com
IPv4 Address: 192.168.34.233
IPv6 Address: fe99::d191:bbb1:a067:ffff
********************************************
PS C:\scripts>
Now, the basis of the script can be used as a function in other scripts. Say, for example you wanted to use a script to determine whether you were working from the office, home or a remote location at start-up and act on the location by starting or not starting certain applications. You might want to, say, start outlook and lync only if you're in the office at start-up, and leave them offline if you're working from home, at least until you've had the chance to VPN in (Yes, some companies will not allow Outlook Anywhere or Lync Edge Connections or split tunneling). You could accomplish this with a script that looks something like this:
No comments:
Post a Comment
Thanks for reading and commenting. I look forward to it.