问题
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