Search code examples
powershellscriptingpowershell-2.0powershell-3.0

Unexpected token in expression or statement


So i'm working on a script that is Dynamic to Static IP

# Identify all adapters that recieved an address via DHCP
   $adapters = Get-WmiObject Class Win32_NetworkAdapterConfiguration | Where-Object {($_.IPAddress) -and $_.DHCPEnabled -eq 'True' }
   # Iterate through each adapter
   foreach($adapter in $adapters) {
       # Get current adapter and IP information
       $adapIndex = $adapter.InterfaceIndex
       $ipAddress = $adapter.IPAddress[0]
       $subnetMask = $adapter.IPSubnet[0]
       $defaultGateway = $adapter.DefaultIPGateway[0]
       $prefix = (Get-NetIPAddress InterfaceIndex $adapIndex AddressFamily IPv4).PrefixLength
       $dnsServers = $adapter.DNSServerSearchOrder
       [ipaddress]$netAddr = ([ipaddress]$ipAddress).Address -band([ipaddress]$subnetMask).Address
       # Identify the DHCP server
       $dhcpServer = $adapter.DHCPServer
       $dhcpName = ([System.Net.DNS]::GetHostEntry($dhcpServer)).HostName
       # Add an exclusion to DHCP for the current IP address
       Invoke-Command ComputerName $dhcpName ScriptBlock{
           Add-DhcpServerv4ExclusionRange –ScopeId $args[0] -StartRange
           $args[1] -EndRange $args[1]
       } -ArgumentList $netAddr.IPAddressToString, $ipAddress
       # Release the DHCP address lease
       Remove-NetIPAddress InterfaceIndex $adapIndex -Confirm:$false
       # Statically assign the IP and DNS information
       New-NetIPAddress InterfaceIndex $adapIndex -AddressFamily IPv4 IPAddress $ipAddress PrefixLength $prefix DefaultGateway $defaultGateway

    Set-DnsClientServerAddress InterfaceIndex $adapIndex ServerAddresses $dnsServers
}

I get this error in the last block

At DynamicTOStatic.ps1:19 char:21
+            $args[1] -EndRange $args[1]
+                     ~~~~~~~~~
Unexpected token '-EndRange' in expression or statement.
At DynamicTOStatic.ps1:19 char:31
+            $args[1] -EndRange $args[1]
+                               ~~~~~
Unexpected token '$args' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : UnexpectedToken

I tried to debug it as much as I can, but i simply do not understand what is required to fix it. Any sort of rearrangement results in the same error.


Solution

  • Remove the line break preceding $args[1]:

    Add-DhcpServerv4ExclusionRange –ScopeId $args[0] -StartRange $args[1] -EndRange $args[1]
    

    Or escape the new line with `:

    Add-DhcpServerv4ExclusionRange –ScopeId $args[0] -StartRange `
    $args[1] -EndRange $args[1]