【问题标题】:PowerShell: What's wrong with "... ${_.Name} ..."?PowerShell:“... ${_.Name} ...”有什么问题?
【发布时间】:2013-11-05 11:07:28
【问题描述】:

为什么我不能在文本中使用 $_,因为可以使用其他变量?

    Get-ChildItem -Path $path -filter *.mp3 | foreach { 
        $count++;
        write-host "File${count}=${_.Name}"; 
    }

我知道我可以这样写:

    Get-ChildItem -Path $path -filter *.mp3 | foreach { 
        $count++;
        write-host "File${count}=$($_.Name)"; 
    }

【问题讨论】:

    标签: string powershell concatenation


    【解决方案1】:

    当您编写${_.Name} 时,您实际上是在请求名为_.Name 的变量,而不是$_ 变量的Name 属性。

    PS > ${_.Name} = "test"
    PS > Get-Variable _*
    
    Name                           Value
    ----                           -----
    _.Name                         test  
    

    $($_.Name) 起作用的原因是因为$() 的意思是“首先处理这个”,所以你可以在里面指定你想要的任何东西。在这种情况下,您只需指定一个变量名称和所需的属性,但您也可以使其更复杂,例如:

    PS > $a = 1
    PS > "A's value is 1(true or false?): $(if($a -eq 1) { "This is TRUE!" } else { "This is FALSE!" })"
    
    A's value is 1(true or false?): This is TRUE!
    
    PS > $a = 2
    PS > "A's value is 1(true or false?): $(if($a -eq 1) { "This is TRUE!" } else { "This is FALSE!" })"
    
    A's value is 1(true or false?): This is FALSE!
    

    【讨论】:

      猜你喜欢
      • 2020-01-01
      • 2015-04-06
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 1970-01-01
      • 2011-01-28
      • 2019-06-10
      • 1970-01-01
      相关资源
      最近更新 更多