【问题标题】:Shorten a Powershell cmdlet Output property result缩短 Powershell cmdlet 输出属性结果
【发布时间】:2019-01-08 01:20:12
【问题描述】:

我在 Powershell 中有一个示例查询;

Get-AzureRmDisk -ResourceGroupName $resourceGroupName | 
Format-Table -Property Name, Managed By

结果

Name      : OsDisk_1_dfa60a
ManagedBy : /subscriptions/resourceGroups/Company/Microsoft.Compute/vms/Server1

由属性管理的输出太长。 我想将其缩短为最后一个 / 之后的字符(正斜杠) 预期结果

Name      : OsDisk_1_dfa60a
ManagedBy : Server1

到目前为止,我已经尝试使用子字符串和 Last index of 来计算“/”的索引并从那里开始子字符串,然后以 ManagedBy 属性字符串的全长结束子字符串;

Get-AzureRmDisk -ResourceGroupName $resourceGroupName | 
Format-List -Property Name, 
ManagedBy.SubString(ManagedBy.LastIndexOf('/'),ManagedBy.length)

错误随之而来:ManagedBy.LastIndexOf :术语“ManagedBy.LastIndexOf”未被识别为 cmdlet、函数、脚本文件的名称,


解决方案

   Get-AzureRmDisk -ResourceGroupName $resourceGroupName | 
Format-Table -Property Name, 
@{Name='ManagedBy';Expr={$_.ManagedBy.Split('/')[-1]}} 

【问题讨论】:

    标签: powershell


    【解决方案1】:

    这应该给你你想要的......

    Format-List -Property Name, 
    @{Name='ManagedBy';Expr={$_.ManagedBy.Split('/')[-1]}}
    

    【讨论】:

    【解决方案2】:

    如果...

    $ManagedBy = "/subscriptions/resourceGroups/Company/Microsoft.Compute/vms/Server1"
    

    那么……

    $LastResult = $ManagedBy.Split("/")[$ManagedBy.Split("/").Length - 1]
    

    仅返回数组中的最后一个值,在本例中为 Server1 本身。数组从 0(零)的位置开始,因此您只需从数组的 Length 的末尾走 1 步即可。

    在这种情况下,将ManagedBy 属性更改为$LastResult 的值,您应该可以将其合并到其余代码中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2016-01-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多