1

I have this bellow command to check is folder contains name "AAA_*" in path "C:\Test" exist and if so - make from it name variable:

$DirPath = "C:\Test"
$DirName = "AAA"
If (Test-Path -Path ($DirPath + "\" + $DirName + "_*")) {                                               
C:;cd\;cd ($DirPath + "\" + $DirName + "_*")
$NameFromDir = pwd | Select-Object | %{$_.ProviderPath.Split("\")[-1]}
cd $PSScriptRoot}

I have to double write it path, and also i need to go to inside of it to set is as variable.

Is this can be done in another shorten or easier way?

MikeZetPL
  • 97
  • 5
  • 1
    `$NameFromDir = (Get-ChildItem C:\Test\AAA_*).Name`? – mklement0 Nov 12 '22 at 15:45
  • 1
    How could the folder name contain `*` ? That's not an allowed character in Windows – Santiago Squarzon Nov 12 '22 at 16:44
  • 1
    @mklement0 This command is very short and fine. Just need to change it little bit, because .Name get me whole path (eg. C:\Test\AAA_BBB), and I was needed only name (AAA_BBB). So I finally used: **$NameFromDir = (Get-ChildItem C:\Test\AAA_*).Basename** Anyway - Thanks again for your help! :) – MikeZetPL Nov 12 '22 at 19:44
  • Glad to hear it, @MikeZetPL, but note that `.Name` is only ever the file or directory _name_, not a full path (only `.FullName` is); for _directories_, `.BaseName` is the same as `.Name` (for _files_, it is the name with the extension removed). – mklement0 Nov 12 '22 at 19:51

1 Answers1

2

Try this ($NameFromDir will be empty if path does not exist):

$DirPath = "C:\Test"
$DirName = "AAA"
$NameFromDir = (Get-Item "$DirPath\$DirName_*").FullName

If you need to restrict the result to a single element you can add

| select-object -First 1
matandra
  • 91
  • 4
  • Thanks also for your command - its also working version, and FullName need to be changed to Basename - then I will get only foldername without full path: **$NameFromDir = (Get-Item "$DirPath\$DirName_*").Basename** – MikeZetPL Nov 12 '22 at 19:48