检查变量

时间:2015-12-02 00:30:31

标签: powershell

创建会话后,我将调用以下内容:

Invoke-Command -Session $s -ScriptBlock $Function:ReaddRoutes -ArgumentList $Global:_DeviceNumberInfoIP.ServiceNetGW

以上在远程服务器上运行以下功能:

function ReaddRoutes {
  if ($Global:datacentre -like '(PINK3)') {
    route delete 10.252.0.0
    route delete 10.191.192.0

    route add -p 10.252.0.0 mask 255.255.255.0 $args[0]
    route add -p 10.191.192.0 mask 255.255.192.0 $args[0]
  }
}

现在问题是,如果我删除if语句,该函数将运行。但是我有相当多的数据中心要进行比较并相应地添加路由。我尝试了-like运算符的许多变体。

变量$global:datacentre包含类似于'Panther(Pink3)'的内容。

可能是因为我从调用命令调用它并且它的行为有所不同吗?

2 个答案:

答案 0 :(得分:2)

-like是一个通配符匹配运算符。要查找以(PINK3)结尾的任何内容的匹配项,请使用:

if ($Global:datacentre -like '*(PINK3)')

匹配参数中没有任何通配符,您基本上需要完全匹配。

if ($Global:datacentre -like '(PINK3)')

在功能上等同于

if ($Global:datacentre -eq '(PINK3)')

答案 1 :(得分:1)

我明白了!

由于在远程服务器上调用此函数,我必须解析数据中心变量。

经过一段美好的睡眠并再次尝试后,它确实有意义......所以在远程服务器上运行的任何函数都需要在-argument列表中。

Invoke-Command -Session $s -ScriptBlock $Function:ReaddRoutes -ArgumentList $Global:_DeviceNumberInfoIP.ServiceNetGW,$Global:datacentre

对于功能:

if ($args[1] -like '*(LON3)'){


        route delete 10.252.0.0
        route delete 10.191.192.0

        #Arg[0] is the Servicenet GW
        Route add -p 10.252.0.0 mask 255.255.255.0 $args[0]
        Route add -p 10.191.192.0 mask 255.255.192.0 $args[0]

       } 

希望这有助于其他人!