简体   繁体   中英

Out-String a result of a CMDLET and manipulate it in PowerShell

I have a variable that gives me the canocical name of an object in Active Directory:

$LastOU = Get-ADOrganizationalUnit -Filter * -Properties * |
          Sort { $_.WhenCreated } -Descending |
          Select -First 1 {$_.CanonicalName} |
          Out-String

If I run the command as Write-Host $LastOU it indeeds gives me the result I expected:

@{$_.CanonicalName=domain.local/Microsoft/Userz}

What I'm trying to do now is to manipulate the string to only have

Microsoft

selected.

I used the Out-String method to have the result of the command as a string.

After, what I do is use the .Split() -function to manipulate my result.

I do this like $CompName = $LastOU.Split(...) .

However I get the error:

Method invocation failed because [Selected.Microsoft.ActiveDirectory.Management.ADOrganizationalUnit] does not contain a method named 'Split'.

This means that my result is not a string? But what is wrong in my command?

Change your select statement to include -ExpandProperty, which should just give you the string back instead of an object.

Change this

Select -First 1 {$_.CanonicalName} |Out-String

to this

Select -ExpandProperty CanonicalName -first 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM