SebMa
SebMa

Reputation: 4709

Passing $args as a string to my function does not work

I wrote this little function to simplify the reading of IPv4 routes :

function showRoute {
    echo "=> args = " $args
    Get-NetRoute -AddressFamily IPv4 $args | findstr -v "224.0.0.0/4 /32"
}

Now, when I call my function with command line arguments, here is what happens :

> . $PROFILE;showRoute -InterfaceAlias LAN
=> args =
-InterfaceAlias
LAN
Get-NetRoute : No matching MSFT_NetRoute objects found by CIM query for instances of the ROOT/StandardCimv2/MSFT_NetRoute class on the  CIM server: SELECT * FROM MSFT_NetRoute  WHERE ((DestinationPrefix LIKE
'-InterfaceAlias') OR (DestinationPrefix LIKE 'LAN')) AND ((AddressFamily = 2)). Verify query parameters and retry.
At C:\Users\sebastien.mansfeld\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:164 char:2
+     Get-NetRoute -AddressFamily IPv4 $args | findstr -v "224.0.0.0/4  ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (MSFT_NetRoute:String) [Get-NetRoute], CimJobException
    + FullyQualifiedErrorId : CmdletizationQuery_NotFound,Get-NetRoute

> . $PROFILE;showRoute -DestinationPrefix X.Y.Z.T/32
=> args =
-DestinationPrefix
X.Y.Z.T/32
Get-NetRoute : No matching MSFT_NetRoute objects found by CIM query for instances of the ROOT/StandardCimv2/MSFT_NetRoute class on the  CIM server: SELECT * FROM MSFT_NetRoute
WHERE ((DestinationPrefix LIKE '-DestinationPrefix') OR (DestinationPrefix LIKE 'X.Y.Z.T/32')) AND ((AddressFamily = 2)). Verify query parameters and retry.
At C:\Users\sebastien.mansfeld\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1:164 char:2
+     Get-NetRoute -AddressFamily IPv4 $args | findstr -v "224.0.0.0/4  ...
+     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (MSFT_NetRoute:String) [Get-NetRoute], CimJobException
    + FullyQualifiedErrorId : CmdletizationQuery_NotFound,Get-NetRoute

>

I also tried replacing $args by ($args -join ' ') but it does not work either.

EDIT0 : I've found one solution : If I pass @args instead of $args, it works.

Upvotes: 0

Views: 111

Answers (1)

Alex R.
Alex R.

Reputation: 467

Try to use Invoke-Expression

function showRoute {
param([string]$parameter)
    if($parameter) {
        $stringToExecute = "Get-NetRoute -AddressFamily IPv4 $parameter | findstr -v '224.0.0.0/4 /32'"
        Write-Output "Command to Execute: $stringToExecute"
        Invoke-Expression $stringToExecute
        break
    }
    Get-NetRoute -AddressFamily IPv4 | findstr -v "224.0.0.0/4 /32"
}

showRoute -parameter "-InterfaceAlias LAN"

Upvotes: 1

Related Questions