Access Script property - powershell

I am looking to run a DNS lookup for a local server, select both the hostname and IP address and output to a text file.
[System.Net.Dns]::GetHostEntry('server1') |
Select-Object 'HostName', 'IPAddressToString' |
Out-File -Path 'c:\temp\DnsIpAddress.txt'
I can access HostName but cannot select IPAddressToString. I can
access IPAddressToString if I save the results to a variable this way:
$result.AddressList.IpAddressToString
Can I use Select-Object to select hostname and IPAddressToString? Or should I do this another way?

Use a calculated property with Select-Object:
[System.Net.Dns]::GetHostentry('server1') |
Select-Object HostName,#{Name = 'IPAddress';Expression={$_.AddressList.IPAddressToString}} |
Out-File -Path 'C:\temp\DnsIpAddress.txt'

It may also be worth mentioning that there's a cmdlet Resolve-DnsName that may yield more "PowerShelly" code:
Resolve-DnsName -name www.stackoverflow.com | Select-Object Name,IPAddress

Related

Piping parameters into cmdlet

This was done for testing and we have the solution but I would like to dig deeper.
I have a file list.txt that contains names of computers:
name
computer1
computer2
computer3
...
when I try
Import-Csv .\list.txt | Select-Object -property #{n="computername";e={$_.name}} | Get-Service
we get an error "Get-Service : Cannot find any service with service name '#{computername=computer1}'." Which I understand as Get-Service trying to map computername=computer1 to the parameter "name" (name="computername=computer1") even though the parameter "computername" is specified.
My solution was to add the "name" parameter and it works as expected
Import-Csv .\list.txt | Select-Object -property #{n="computername";e={$_.name}} | Get-Service -name *
My question is, why? Get-Service should accept pipeline input byPropertyName and it recognizes computername. Why doesn't it bind it unless I specify another parameter? Neither "name", nor "computername" is required. Also
Get-Service
and
Get-Service -computername "computer1"
both work without specifying "name".

Merge Powershell Output - Get-VM, Get-VHD

I would like to export some Server Statistics from a Failover Cluster System.
My plan is to show with the Get-VHD command all VHD used on the VMs on my host.
So I was Trying to use:
Get-VM | select-object VMID |get-vhd |ft
This gives me a list the
"ComputerName, Path, VHDFormat,VHDType,FileSize,MinimumSize, LogicalSectorSize, PhysicalSectorSize"
Sadly the ComputerName is not the VMName but just the Name of the Host.
Now when I run the Get-VM command I get the Name and here it is actually the VMName.
Is there a nice way to get the real VMnames in the Output of Get-VHD?
I am fairly new to Powershell and I could not find a solution that worked... Most of the "sniplets" found here did not work at all or did not return the VMname...
Thank you for your suggestions =)
Sorry, I think my Title is not that well described, I was not sure how this funktion is called.
Untested, but you could use a ForEach-Object loop and capture the Name property from the Get-VM cmdlet. Then go on with Get-VHD and combine the output:
Get-VM | ForEach-Object {
$name = $_.Name
$_ | Get-VHD | Select-Object #{Name = 'Name'; Expression = {$name}}, *
} | Format-Table -AutoSize

How do i Filter the DHCP Lease information that i export

I just wrote a powershell script that will export dhcp lease information but i want to export specific information like export only IP and mac addresses in the dhcp. Instead of exporting every lease information. The one line of code i have written that exports everything is bellow.
Get-DhcpServerv4Lease -ComputerName "HW2009-11" | Export-Csv -Path ("C:\log\new.csv")
To adress only certain properties of an object, you can use Select-Object. This way you can only choose the ipand mac-address like this:
Get-DhcpServerv4Lease -ComputerName "HW2009-11" | Select-Object -Property IP, mac-address
You can then pipe this to Export-Csv and it will create a .csv file with only those properties:
Get-DhcpServerv4Lease -ComputerName "HW2009-11" | Select-Object -Property IP, mac-address | Export-Csv -Path "C:\log\new.csv"
If you don't know the specific properties of an object, you can just pipe the command to Get-Member:
Get-DhcpServerv4Lease | Get-Member

DHCP Powershell sort

Ok, so this is more of a basic Powershell question I'm pretty sure, but here's what I am trying to do:
I am writing a quick script that reads all DHCP leases on a given scope, finds any matches for client names (in this case with 'iphone' in the name), then removes those leases from DHCP. Here's what I have so far:
$leases = Get-DhcpServerv4Lease -ScopeId 192.168.1.0 | select hostname, clientid
#Find all hostnames w/ 'android' or 'iphone' in name, delete lease
$trouble = $leases | select-string -Pattern "android","iphone","ipad"
Remove-DhcpServerv4Lease -ScopeId 192.168.1.0 -ClientId $trouble
The issue is that the output of $trouble now looks like this:
#{hostname=Someones-iPhone.domain.com; clientid=00-00-00-00-c7-cc}
Since I can't remove a lease based on host name (since that isn't globally unique, I assume), I need to pass the MAC, aka client ID.
How can I get the output to slim down to just have the clientid, without all the other data? I've googled my heart out, and it's not helping. Thanks in advance!
You don't need to use Select-String in order to filter by a property name - use Where-Object:
$Troubles = Get-DhcpServerv4Lease -ScopeId 192.168.1.0 | Where-Object {
$_.Hostname -match "android" -or
$_.Hostname -match "iphone" -or
$_.Hostname -match "ipad"
} | Select-Object ClientId
If you just want the value of ClientId, use Select-Object -ExpandProperty ClientId

How to get the default gateway from powershell?

If a computer has multiple gateways, how can I determine which is the default gateway using the PowerShell?
If you're on PowerShell v3, you can use Get-NetIPConfiguration e.g.:
Get-NetIPConfiguration | Foreach IPv4DefaultGateway
I think this will be more cross platform:
Get-NetRoute |
where {$_.DestinationPrefix -eq '0.0.0.0/0'} |
select { $_.NextHop }
You need to know which of the multiple gateways are used? If so. From what I remember, when multiple gateways are available the gateway with the lowest metric("cost" based on link speed) is used. To get this, run the following command:
Get-WmiObject -Class Win32_IP4RouteTable |
where { $_.destination -eq '0.0.0.0' -and $_.mask -eq '0.0.0.0'} |
Sort-Object metric1 | select nexthop, metric1, interfaceindex
if there are multiple default gateways with the same cost, I think it's decided using the binding order of the network adapters. The only way I know to get this is using GUI and registry. To include binding order you could save the output of the script over, get the settingsid from Win32_networkadapterconfiguration (identify using interfaceindex), and read the registry key HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Tcpip\Linkage\Bind. This key lists the binding order it seems, and the settingsid you get from win32_networkadapterconfiguration is the GUID they identify the device with. Then sort the gateways with equal metrics using their order in the Bind reg.key and you got your answer.
Explained in: Technet Social - NIC adapter binding
I found it as the below which lists all active gateways, correct me if I am wrong
(Get-wmiObject Win32_networkAdapterConfiguration | ?{$_.IPEnabled}).DefaultIPGateway
Use the WMI queries to pull the data that you're looking for. Below is a fairly simple example to pull the default gateway for a device specified in the first line variable. This will query the device for network adapters and display the found information (for each adapter) to the console window - pulls adapter index, adapter description, and default gateway
Shouldn't take much to expand this to process multiple devices, or process based on a list fed via an input file.
$computer = $env:COMPUTERNAME
Get-WmiObject win32_networkAdapterConfiguration -ComputerName $computer |
Select index,description,defaultipgateway |
Format-Table -AutoSize
$ActiveNet = Get-NetAdapter –Physical |Where-Object {$_.status -eq "Up"} | select name
$Network = Get-NetIPAddress |Where-Object EnabledDefault -EQ 2 | Where-Object InterfaceAlias -EQ $ActiveNet.name | Where-Object IPv4Address -NE $null | select *
$DefautGateway = Get-NetRoute -InterfaceIndex $Network.InterfaceIndex -DestinationPrefix "0.0.0.0/0" | select NextHop
$DefautGateway.NextHop