'Navigate to a folder in powershell
I have a folder named
degtf-ithuju\syntg-backup\@GMT-2022.02.18-02.00.10
The last 6 characters of this folder changes daily. I need to navigate to it.
I created the string up to degtf-ithuju\syntg-backup\@GMT-2022.02.18. Now I need to use a wild card so that the path is reachable and I can get the content of the
degtf-ithuju\syntg-backup\@GMT-2022.02.18-02.00.10
folder.
So I hardcoded degtf-ithuju\syntg-backup\@GMT-2022.02.18 in a variable but now how do I add that remaining name to it? It can't be hard coded.
$YD = (get-date -format "yyyy.MM.dd").ToString()
$v1= "C:\Ps\degtf-ithuju\syntg-backup\@GMT-"
$v2= $v1 + $YD
$v2
I Tried * and % but its not working.
cd c:\Ps\$v2% or cd C:\Ps\$v*
Up to $V2 it is fine, but after that it's not working.
Thank you!
Solution 1:[1]
The following (partially commented) script shows possible approach:
$YD = Get-Date -format "yyyy.MM.dd-"
$v1= "C:\Ps\degtf-ithuju\syntg-backup\@GMT-"
$v2= $v1 + $YD + '*'
$fldrs = @(Get-ChildItem -Path $v2 -Directory)
switch ($fldrs.Count){
0 { "no such folder: $v2"
# create one as follows?
$fldrName = $v1 + (Get-Date -format "yyyy.MM.dd-hh.mm.ss")
New-Item -Path $fldrName -ItemType Directory -WhatIf
break
}
1 { $fldrName = $fldrs[0].FullName
"found folder: $fldrName"
break
}
Default {
"found $($fldrs.Count) folders: $v2"
# choose one e.g. the last one as follows?
$fldrName = $fldrs[-1].FullName
}
}
Explanation:
- Array subexpression operator @( ): Returns the result of one or more statements as an array. The result is always an array of 0 or more objects. Used in
$fldrs = @( … ). - Subexpression operator $( ): Returns the result of one or more statements. … For example, to embed the results of command in a string expression. Used in
"found $($fldrs.Count) folders: $v2". - about_Switch
- Powershell-3.0 accepts the
-Directoryswitch parameter used inGet-ChildItem -Path $v2 -Directory
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | JosefZ |
