ForEach-Object OutString, Powershell Awk Equivalents

筅森魡賤 提交于 2021-01-04 13:03:51

问题


I'm a long time Bash enthusiast trying to get my bearings with Powershell. I'm trying to do something that could easily be accomplished with Awk, but I can't seem to find a solution in Powershell documentation. I'm essentially trying to select the third value from the output of the command delimited by /

Get-ADOrganizationalUnit -Properties CanonicalName -Filter * | Select-Object -ExpandProperty CanonicalName | Select-String ".*/Example/.*"

example.local/Example/ExampleOU1
example.local/Example/ExampleOU2

I just want to select the last value shown here. In Bash land this could easily be accomplished by an awk -F "/" '{print $3}' however I'm struggling to find the equivalent in Powershell. I found Out-String | %{ $_.Split('/')[2]; }' which is nice, but only works if there's one object. I'm assuming I need to ForEach-Object, then convert to a string, then split, but I'm not sure how.


回答1:


I almost never use out-string. Canonicalname is a property of the object, so you need to reference that property. This would work:

[pscustomobject]@{canonicalname = 'example.local/Example/ExampleOU1'} | 
  % { $_.canonicalname.Split('/')[2] }

ExampleOU1

There's also -split which uses regex:

[pscustomobject]@{canonicalname = 'example.local/Example/ExampleOU1'} | 
  % { ($_.canonicalname -split '/')[2] }

Paths come up so often there's a command for it:

[pscustomobject]@{canonicalname = 'example.local/Example/ExampleOU1'} | 
  % { split-path -leaf $_.canonicalname }


来源:https://stackoverflow.com/questions/63570778/foreach-object-outstring-powershell-awk-equivalents

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!