Home > database >  How to print a specific part of directory path in powershell
How to print a specific part of directory path in powershell

Time:02-04

My script is running in a loop on files and I display the path for each file but the path is too long and I want to display only the relevant directory. the path build always the same examlpe for output path:

$File.DirectoryName
C:\Users\Bandit\AppData\Local\Temp\9c86ee608bb9477ebb11914c36a5a76d\638110173610123239\IDUDatabase_4.0.0.119\IDUDatabase

I am creating the temp folder and the sub folder as below:

$tempFolder = Join-Path ([IO.Path]::GetTempPath()) (New-GUID).ToString('n')
$subTemp = Join-Path -Path $tempFolder -ChildPath ([datetime]::Now.Ticks)

So this part is constant C:\Users\Bandit\AppData\Local\Temp\9c86ee608bb9477ebb11914c36a5a76d\638110173610123239

I want to display only the 'IDUDatabase_4.0.0.119\IDUDatabase' The structure is always the same except the user name (C:\User\UserName)

CodePudding user response:

If you want to remove a prefix from a string you can use the Substring method…

$subTemp = "C:\Users\Bandit\AppData\Local\Temp\9c86ee608bb9477ebb11914c36a5a76d\638110173610123239"

$mypath = Join-Path -Path $subTemp -ChildPath "IDUDatabase_4.0.0.119\IDUDatabase"

$displayPath = $mypath.Substring($subTemp.Length 1)

$displayPath
# IDUDatabase_4.0.0.119/IDUDatabase

Note the 1 is there to remove the path separator immediately after the folder prefix.

CodePudding user response:

You might use the Resolve-Path -Relative parameter for this:

Set-Location $subtemp
GCI $subtemp -Recurse |Foreach-Object { Resolve-Path -Relative $_.FullName }

.\IDUDatabase_4.0.0.119
.\New folder
.\IDUDatabase_4.0.0.119\IDUDatabase
.\New folder\New Text Document.txt
  • Related