Expression中的Hashtable条件语句

时间:2017-05-26 03:11:54

标签: powershell math expression conditional hashtable

我目前正在尝试从System.Object []中提取信息,但我希望只从n中获取Col1Col2,因为它有很多不必要的内容列。 设置:

$var

所需:

    $var = 
   ..     Col1  Col2     
   ..     1     2147483648    
   ..     2     524288000 
   ..     3     268435456000     
   ..     4     268435456000  

我可以使用下面的代码获得所需的Col3:

   $res= 
   ..     Col1  Col2          Col3
   ..     1     2147483648    2 GB
   ..     2     524288000     500 MB
   ..     3     268435456000  250 GB 
   ..     4     268435456000  250 GB

然而,这只是显示Col3而不是其他列,我想要的是通过选择列和使用列表达式来获得某种哈希表但是如果我将条件语句放在一个列表中,我就无法得到任何东西IF和一个ELSE在下面的代码中的表达式中:

foreach($t in $var)
{
    if($t.Col2% ([math]::pow(1024,3)))
    {
        $t.Col2/([math]::pow(1024,2))" MB"
    }
    else
    {
        $t.Col2/([math]::pow(1024,3))" GB"
    }
}

我的主要目标是提取这些列并将它们大量插入到SQL中的表中,但我无法使用ELSE表达式,但如果我只指定IF条件,那么它似乎可以工作。

我想知道这是否是对powershell中哈希表的表达式中的IF-ELSE语句的限制。

2 个答案:

答案 0 :(得分:2)

您应该在对象中添加ScriptProperty来计算它,然后将其称为常规属性。定义脚本属性使用Add-Member和脚本块,但使用$this代替$_来引用当前对象。

$var | Add-Member -MemberType ScriptProperty -Name DisplaySize -Value {
        if($this.Col2 % ([math]::pow(1024,3)))
        {
            $this.Col2/([math]::pow(1024,2))"MB"
        }
        else
        {
            $this.Col2/([math]::pow(1024,3))"GB"
        }
    }
} -Force

$var[0].DisplaySize

您也知道,PowerShell包含KB / MB / GB /等的简写语法:

1MB  # equivalent to writing 1048576
3TB  # equivalent to writing 3298534883328

答案 1 :(得分:0)

#Solution 1, with column builded in select,  condensed
$var | select *, @{N="DisplaySize";E={ "{0} {1}" -f @(if($this.Col2 % ([math]::pow(1024,3))) {($this.Col2/1MB), "MB"} else {($this.Col2/1GB), "GB"} ) }}

#Solution 2, with column builded in select, explain
$var | select *, @{N="DisplaySize";E={

    if($this.Col2 % ([math]::pow(1024,3))) 
    {
        "{0} MB" -f ($this.Col2/1MB)
    } 
    else 
    {
        "{0} GB" -f ($this.Col2/1GB)
    } 

}} 

#Solution 3, with column builded, logique to take 2 columns
$var | select *, @{N="DisplaySizeMB";E={$this.Col2/1MB}}, @{N="DisplaySizeGB";E={$this.Col2/1GB}}
相关问题