I am attempting to write a function to quickly swap my ip address but have not had luck.
Please tear apart what I have written and let me know how I can improve!
Thanks!
function set-ip {
[CmdletBinding()]
PARAM(
[parameter(mandatory=$true,
Position=0,
HelpMessage="Enter the ip address you want, like 192.168.1.11")]
[String]$ip,
[parameter(mandatory=$true,
HelpMessage="Enter the ip of the gateway, like 192.168.1.1 or 10.10.10.254")]
[String]$gateway
)
process {
#This works fine from an interactive session on its own, and I want to try to get this automatically
$target = (Get-NetIPInterface | ? {$_.ifAlias -like '*ethernet*' -and $_.AddressFamily -eq 'IPv4'})
#Just a heads up
Write-Verbose "Beginning work on the following adapter"
start-sleep -Seconds 1
#Goal was to spit out the variable, and check the result
write-output "$target"
Write-Warning "Confirm $target looks correct" -WarningAction Inquire
#Ideally this should not require anymore input at this point
New-NetIPAddress -IPAddress $ip -InterfaceAlias $target -DefaultGateway $gateway -PrefixLength 24
}
}
This only seems to “work fine” interactively because you’re perhaps not understanding what’s going in $target. It’s a NetIPInterface object; looking at the output of the command in the console is a little misleading because the console has to format the object into a text display, which can make you think you’ve got something you don’t. However, when you just try to use $target in Write-Output, you’re triggering a slightly different process, where it’s just showing you its Name property. Honestly, you should probably be doing Write-Verbose there, too - Write-Output is going to feed the “output” of your function, which isn’t what you want.
-InterfaceAlias doesn’t want an entire NetIPInterface object, but that’s what you’re feeding it. You probably need to use something like ($target.alias) or something. That is, rather than jamming the entire object and all its properties into -InterfaceAlias, you need to feed it the ONE property that contains the information the parameter needs.