简体   繁体   中英

How to convert GCI DirectoryName to string for .Substring()

Trying to output just the immediate parent folder from this as the full path is too big. The ultimate goal is to output duplicate files from different folders ordered by modify date.

I think I need to cast the gci DirectoryName output as a string so I can .Substring($LenRootPath) as per below:

I've tried -Expand , but it can't convert System.Object to System.String . I also tried [string[]] , which is ignored, and tried .Substring($rootPath.Length) , but still get a System.Object .

Cast gci directoryname as string?

$rootPath = "c:\test" 
$array = @(Join-Path $rootPath "\1111\", 
           Join-Path $rootPath "\2222\", 
           Join-Path $rootPath "\3333\")

Get-ChildItem -Path $array -Filter "*.doc" -Recurse |
  where {!$_.PSIsContainer} | 
  Select-Object DirectoryName, Name, LastWriteTime | 
  Sort-Object Name, LastWriteTime -Desc |
  Format-Table @{
    Name="LastWriteTime";
    Expression={$_.LastWriteTime.ToString("yyyy-MM-dd HH:mm")}
  }, DirectoryName -GroupBy Name

The problem with your code is in the definition of $array . You need to add brackets around each so that the cmdlet executes before it's interpreted as a string in the array. Eg:

$array = @((join-path $rootPath "\1111\"), 
           (join-path $rootPath "\2222\"), 
           (join-path $rootPath "\3333\"))

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