I am trying to create a powershell script to enable Jumpframe on Openstack windows VM's. The command to find active network card and also the current MTU value also the command to change MTU value all below.
From the below command I am first finding the active network card , then trying to find the MTU value of that NIC and if I found MTU value less than 1600 I need that to be changed to 9000.
PS C:\> **wmic nic where "netconnectionid like '%'" get netconnectionid**
NetConnectionID
Ethernet
PS C:\> **netsh.exe int ipv4 show subint**
MTU MediaSenseState Bytes In Bytes Out Interface
------ --------------- --------- --------- -------------
4294967295 1 0 1400 Loopback Pseudo-Interface 1
1200 1 1335974344 5867793 Ethernet
PS C:\> **netsh int ipv4 set subint "Ethernet" mtu=9000 store=persistent**
Can anyone let me know how can I write a condition to accomplish what I am looking for ?
Try the following:
$enabledAdaptersNames = Get-NetAdapter |? {$_.status -eq "Up" -or $_.status -eq "Disconnected"} | Select -ExpandProperty name
Get-NetIPInterface |? { $enabledAdapterNames -contains $_.InterfaceAlias -and $_.NlMtu -lt 1600} | Set-NetIPInterface -NlMtuBytes 9000
Related
Not sure why but my if statement not go on the proper direction, in the following example one interface is disabled but it still shows the True value, however it should show the False one.
I have the following interfaces:
get-netadapter
Name InterfaceDescription ifIndex Status MacAddress LinkSpeed
---- -------------------- ------- ------ ---------- ---------
Embedded FlexibleLOM ...2 HPE FlexFabric 10Gb 4-port 536FLR-...#2 10 Disabled 08-xxx-62 10 Gbps
Embedded FlexibleLOM ...1 HPE FlexFabric 10Gb 4-port 536FLR-...#4 11 Up 08-xxx-60 10 Gbps
You can see one is disabled.
This is the script:
$vmswitch1stinterface = (Get-VMSwitchTeam -Name "Teaming").NetAdapterInterfaceDescription|select -first 1
$vmswitch2ndinterface = (Get-VMSwitchTeam -Name "Teaming").NetAdapterInterfaceDescription|select -last 1
$1stinterfacestatus = Get-NetAdapter -InterfaceDescription $vmswitch1stinterface|select Status
$2ndinterfacestatus = Get-NetAdapter -InterfaceDescription $vmswitch2ndinterface|select Status
if (($1stinterfacestatus -and $2ndinterfacestatus) -eq 'up')
{
Write-Host "OK: NIC ports are up (VMSwitch)"
Exit 0
} else
{
Write-Host "WARNING: An interface is down! Please check in the list which one is not UP:"
Get-NetAdapter -InterfaceDescription $vmswitch1stinterface|Select-Object InterfaceDescription, Status
Get-NetAdapter -InterfaceDescription $vmswitch2ndinterface|Select-Object InterfaceDescription, Status
Exit 1
}
The values are as follow for easy determination:
$vmswitch1stinterface: HPE FlexFabric 10Gb 4-port 536FLR-T Adapter #4
$vmswitch2ndinterface: HPE FlexFabric 10Gb 4-port 536FLR-T Adapter #2
$1stinterfacestatus
Status
------
Up
$2ndinterfacestatus
Status
------
Disabled
The result of this script is the following which is not correct:
OK: NIC ports are up (VMSwitch)
What I'm missing in the logic?
$1stinterfacestatus and $2ndinterfacestatus are PSCustomObjects and it can have properties. In your case both objects has Status property which you can access it using . notation.(ie, $yourPSCustomObject.Status).
I think you intended to test if both interfaces are up, which you can do by
if (($1stinterfacestatus.status -eq 'up' -and $2ndinterfacestatus.status -eq 'up')) {
Write-Output "Both interfaces are up"
}
I have a powershell command with below output, The command output shows the active NIC adapter and NIC adapter name differ in each machine. But what I am looking here is, in one server active NIC adapter is Local Area Connection and in another one it is Ethernet.This will differ in all VM's
PS C:\> netsh interface ipv4 show interface |where { $_ -match '\sconnected' -and $_ -notmatch 'loopback'}
12 5 1500 connected **Local Area Connection**
PS C:\>
PS C:\> netsh interface ipv4 show interface |where { $_ -match '\sconnected' -and $_ -notmatch 'loopback'}
12 5 1500 connected **Ethernet**
PS C:\>
I want only the adapter name to be captured (eg: Local Area Connection\Ethernet etc).
Can anyone help me modifying the command so that I will get the NIC adapter name without any white space as output?
The output should be like below
Local Area Connection
Ethernet
Ethernet 2
If you are running this on a Windows 8 or Server 2012 or newer operating system you can use the Get-NetAdapter cmdlet instead to get the result you want:
Get-NetAdapter | Where {$_.Status -eq 'Up'} | Select -ExpandProperty Name
On an older OS you could try this, which splits the text for each interface by the word "connected" and it's trailing whitespace using the regex special character \s and then return the second item of that split:
$Interfaces = netsh interface ipv4 show interface | where { $_ -match '\sconnected' -and $_ -notmatch 'loopback'}
$Interfaces | ForEach-Object {
($_ -Split 'connected\s+')[1]
}
Or here is another option that avoids using the -split operator and instead uses a regex lookbehind to match 'connected' followed by 5 spaces in the string before what we want to return:
$Interfaces = netsh interface ipv4 show interface | where { $_ -notmatch 'loopback'}
$Interfaces | ForEach-Object {
[regex]::matches($_, '(?<=connected\s{5})(.*)').value
}
I'm trying to get the content from the boot order list with the following command but $pr is empty and there is no error message:
$pr = Get-HPBIOSUEFIBootOrder $conObj | select -Expand UEFIBootOrder |select -Expand DeviceName| Where DeviceName -contains "*Target:0, Lun:0)"^
Where's my mistake?
When I run this:
$pr = Get-HPBIOSUEFIBootOrder $conObj | select -Expand UEFIBootOrder |select -Expand DeviceName
It returns this:
Generic USB Boot
Embedded LOM 1 Port 1 : HP Ethernet 1Gb 4-port 331i Adapter - NIC (PXE IPv6)
Embedded LOM 1 Port 1 : HP Ethernet 1Gb 4-port 331i Adapter - NIC (PXE IPv4)
Slot 3 Port 1 : HP Ethernet 10Gb 2-port 530T Adapter - NIC (PXE IPv6)
Embedded RAID 1 : Smart Array P440ar Controller - 279.43 GiB, RAID 1 Logical Drive(Target:0, Lun:1)
Windows Boot Manager
Internal USB 1 : HPE Dual 8GB MicroSD EM USB Kit - USB RAID LUN
Embedded RAID 1 : Smart Array P440ar Controller - 279.37 GiB, RAID 1 Logical Drive(Target:0, Lun:0)
Embedded FlexibleLOM 1 Port 1 : HP FlexFabric 10Gb 2-port 533FLR-T Adapter - NIC (PXE IPv6)
Embedded RAID 1 : Smart Array P440ar Controller - 279.37 GiB, RAID 1 Logical Drive(Target:0, Lun:2)
Embedded FlexibleLOM 1 Port 1 : HP FlexFabric 10Gb 2-port 533FLR-T Adapter - NIC (PXE IPv4)
Slot 3 Port 1 : HP Ethernet 10Gb 2-port 530T Adapter - NIC (PXE IPv4)
Use -like instead of -contains.
Contains should be used when you want to determine if a value is in a collection of values. Like should be used (with wildcard characters) when you want to partially match a string. This is a common PowerShell misconception.
You've also used -ExpandProperty on DeviceName after which have a collection of strings without that property name. As such you need to do this in your Where:
| Where {$_ -like "*Target:0, Lun:0)"}
$_ is a special placeholder that represents the current item in the pipeline, which with a system.string object is (by default) its string value.
Here is a bigger picture of my little project.
And what i´ve reached so far.
It will find more makings in the near future.
##
# The following Script is checking the current HPPowerProfile Setting on the local Server
# and set it to Maximum_Performance if its not already set.
#
# Also it set´s the UEFIBootOrder to HDD firts (Target:0, Lun:0)
##
# Read-Host -AsSecureString | ConvertFrom-SecureString | Out-File C:\mysecurestring.txt
# Set Access Credentials
$username = "*******"
$password = cat C:\mysecurestring.txt | Convertto-SecureString
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username, $password
# Set ILO Hostname
$sv = hostname
$ri = $sv.replace("YY","XX")
# Connect to HPBios
$conObj = Connect-HPBIOS $ri -Credential $cred -DisableCertificateAuthentication
# Check current BootMode (depending on Boot Mode, other cmdlet´s will be executed)
$bm = $conObj | Get-HPBIOSBootMode | select -Expand BootMode
if ( $bm -eq "UEFI Mode")
{echo "UEFI"}
else
{echo "echo $bm"}
# Check current Server Power Profile
$pr = Get-HPBIOSPowerProfile $conObj | select -Expand HPPowerProfile
if (-not( $pr -eq "Maximum Performance"))
{$conObj | Set-HPBIOSPowerProfile -HPPowerProfile Maximum_Performance}
else
{echo "No change needed"}
# Find HDD and move it to Boot Order #1
$bo = Get-HPBIOSUEFIBootOrder $conObj | select -Expand UEFIBootOrder | Where DeviceName -like "*Drive(Target:0, Lun:0)" | select -Expand Index
if (-not( $bo -eq "1"))
{$conObj | Set-HPBIOSUEFIBootOrder -UEFIBootOrder "$bo,1"}
else
{echo "No change needed"}
I am creating a script which will run through a lot of the basic tasks when commissioning a new server. Now most servers have multiple NICs these days and I need to question the user (using the script) what NIC they want to assign the IP to.
At the moment I have:
$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration -ComputerName $env:COMPUTERNAME | where{$_.IPEnabled -eq $true -and $_.DHCPEnabled -eq $true}
Which will put the NICs into $NICs I believe. However from here I want to print them out to the user, and then somehow assign a value to each NIC, like an index, so the user can type in, "1" or "2" so tell the script what NIC to apply the Ip configuration to which will be done like:
If($ipQuestion -eq "Y") {
$ipAddr = Read-Host "Enter IP Address: "
$subnet = Read-Host "Enter Subnet: "
$dns = Read-Host "Enter DNS: "
Write-Host "Multiple DNS servers?" -ForegroundColor Green
$multipleDNSServersQuestion = Read-Host
If($multipleDNSServersQuestion -eq 'Y'){
$dns2 = Read-Host "Enter Secondary DNS: "
}
$dGateway = Read-Host "Enter Default Gateway: "
}
$NIC.EnableStatic($ipAddr, $subnet)
$NIC.SetGateways($dGateway)
$NIC.SetDNSServerSearchOrder($dns, $dns2)
$NIC.SetDynamicDNSRegistration("TRUE")
Any ideas?
If you ensure $NICS is always an array, you can use the array index to specify each NIC. To ensure it is always an array do this:
$NICs = #(Get-WMIObject Win32_NetworkAdapterConfiguration -ComputerName $env:COMPUTERNAME | where{$_.IPEnabled -eq $true -and $_.DHCPEnabled -eq $true})
Then print out the info like so:
PS> $NICS = #(Get-WMIObject Win32_NetworkAdapterConfiguration)
PS> $NICS | Foreach {$i=-1}{$i++;$_} | ft #{n='index';e={$i}},Description,ServiceName
index Description ServiceName
----- ----------- -----------
0 WAN Miniport (L2TP) Rasl2tp
1 WAN Miniport (SSTP) RasSstp
2 WAN Miniport (IKEv2) RasAgileVpn
3 WAN Miniport (PPTP) PptpMiniport
4 WAN Miniport (PPPOE) RasPppoe
5 WAN Miniport (IP) NdisWan
6 WAN Miniport (IPv6) NdisWan
7 WAN Miniport (Network Monitor) NdisWan
8 Microsoft Kernel Debug Network Adapter kdnic
9 RAS Async Adapter AsyncMac
10 Broadcom NetXtreme Gigabit Ethernet b57nd60a
11 Microsoft ISATAP Adapter tunnel
12 Microsoft Teredo Tunneling Adapter tunnel
13 Microsoft 6to4 Adapter tunnel
14 Microsoft ISATAP Adapter tunnel
Then access each NIC like so:
$NICS[$selectedIndex]
$NICs = #(Get-WMIObject Win32_NetworkAdapterConfiguration ...)
will make $NICs an array, which can be accessed by (zero-based) index:
$NICs[0] # <-- first interface
$NICs[1] # <-- second interface
...
The way I would do it. If you have a look to the network connexions panel in the internet connexions. You can see the string the user know for his devices :
So in a dialog with the user I would give this name retreiving it with win32_NetworkAdapter joinning Win32_NetworkAdapterConfiguration with Index.
$NICs = Get-WMIObject Win32_NetworkAdapterConfiguration -ComputerName $env:COMPUTERNAME | where{$_.IPEnabled -eq $true -and $_.DHCPEnabled -eq $true}
$NICs | % {$i = (Get-WmiObject win32_NetworkAdapter -Filter "index=$($_.index)").NetConnectionID; $_} | ft #
{n='index';e={$i}},Description,ServiceName
index Description ServiceName
----- ----------- -----------
NET1 Intel(R) 82567LM Gigabit Network Conne... e1yexpress
I am trying to get the ipaddress from a hostname using Powershell, but I really can't figure out how.
Any help?
You can get all the IP addresses with GetHostAddresses like this:
$ips = [System.Net.Dns]::GetHostAddresses("yourhosthere")
You can iterate over them like so:
[System.Net.Dns]::GetHostAddresses("yourhosthere") | foreach {echo $_.IPAddressToString }
A server may have more than one IP, so this will return an array of IPs.
this is nice and simple and gets all the nodes.
$ip = Resolve-DNSName google.com
$ip
also try inputting an ip instead of a domain name and check out those results too!
Use Resolve-DnsName cmdlet.
Resolve-DnsName computername | FT Name, IPAddress -HideTableHeaders | Out-File -Append c:\filename.txt
PS C:\> Resolve-DnsName stackoverflow.com
Name Type TTL Section IPAddress
---- ---- --- ------- ---------
stackoverflow.com A 130 Answer 151.101.65.69
stackoverflow.com A 130 Answer 151.101.129.69
stackoverflow.com A 130 Answer 151.101.193.69
stackoverflow.com A 130 Answer 151.101.1.69
PS C:\> Resolve-DnsName stackoverflow.com | Format-Table Name, IPAddress -HideTableHeaders
stackoverflow.com 151.101.65.69
stackoverflow.com 151.101.1.69
stackoverflow.com 151.101.193.69
stackoverflow.com 151.101.129.69
PS C:\> Resolve-DnsName -Type A google.com
Name Type TTL Section IPAddress
---- ---- --- ------- ---------
google.com A 16 Answer 216.58.193.78
PS C:\> Resolve-DnsName -Type AAAA google.com
Name Type TTL Section IPAddress
---- ---- --- ------- ---------
google.com AAAA 223 Answer 2607:f8b0:400e:c04::64
You could use vcsjones's solution, but this might cause problems with further ping/tracert commands, since the result is an array of addresses and you need only one.
To select the proper address, Send an ICMP echo request and read the Address property of the echo reply:
$ping = New-Object System.Net.NetworkInformation.Ping
$ip = $($ping.Send("yourhosthere").Address).IPAddressToString
Though the remarks from the documentation say:
The Address returned by any of the Send overloads can originate from a malicious remote computer. Do not connect to the remote computer using this address. Use DNS to determine the IP address of the machine to which you want to connect.
Working one liner if you want a single result from the collection:
$ipAddy = [System.Net.Dns]::GetHostAddresses("yahoo.com")[0].IPAddressToString;
hth
If you know part of the subnet (i.e. 10.3 in this example), then this will grab any addresses that are in the given subnet:
PS C:\> [System.Net.Dns]::GetHostAddresses("MyPC") | foreach { $_.IPAddressToString | findstr "10.3."}
This worked well for my purpose
$ping = ping -4 $env:COMPUTERNAME
$ip = $ping.Item(2)
$ip = $ip.Substring(11,11)
$computername = $env:computername
[System.Net.Dns]::GetHostAddresses($computername) | where {$_.AddressFamily -notlike "InterNetworkV6"} | foreach {echo $_.IPAddressToString }
The Test-Connection command seems to be a useful alternative, and it can either provide either a Win32_PingStatus object, or a boolean value.
Documentation:
https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.management/test-connection
You can use this code if you have a bunch of hosts in text file
$a = get-content "C:\Users\host.txt"(file path)
foreach ($i in $a )
{
$i + "`n" + "==========================";[System.Net.Dns]::GetHostAddresses($i)
}
The simplest way:
ping hostname
e.g.
ping dynlab938.meng.auth.gr
it will print:
Pinging dynlab938.meng.auth.gr [155.207.29.38] with 32 bytes of data
try
$address = 'HOST NAME'
Resolve-DnsName $address | Select-Object Name, IPAddress | Export-csv "C:\Temp\CompleteNSLookup.csv" -append -NoType