简体   繁体   中英

Passing the path in variable in Get-ChildItem

When I use * in string then Get-ChildItem returns the value.

$Files = Get-ChildItem "C:\PROD\Logs\exec_package_OrderAnalytics_EXTR.dtsx*"

But when I store the path in a variable including * then it shows an error:

$PackageName = "OrderAnalytics_EXTR.dtsx"
$PackagePath = "\\pdw01rasci001\SSISPackages\PROD\Logs\exec_package_$($PackageName)*"
$Files = Get-ChildItem "$PackagePath"

Error message:

Get-ChildItem : Illegal characters in path.
At line:25 char:10
+ $Files = Get-ChildItem $PackagePath | Sort-Object -Property CreationT ...`

So how should I use * as well as variable name in Get-ChildItem to get the result?

Your script logic and syntax works fine, the issue with your code is likely to do with the path that you have specified. a little bit of debugging of $PackagePath should help.

Try the following script:

1. Which will create a directory at "C:\\Stackoverflow\\Scripts"

2. Creates 3 text files within the directory

3. Stores the path in a variable including * as per your requirement

New-Item -ItemType Directory -Path "C:\Stackoverflow\Scripts" -Force
New-Item -ItemType File -Path "C:\Stackoverflow\Scripts\Untitled1.txt", "C:\Stackoverflow\Scripts\Untitled2.txt", "C:\Stackoverflow\Scripts\Untitled3.txt"


$FileName = "led"
$FilePath = "C:\Stackoverflow\Scripts\\Untit${FileName}*"
$Files = Get-ChildItem -Name "$FilePath"
echo "$Files"

A quick pointer

To help debug the path try Get-ChildItem -LiteralPath and echo the result, Literal Path takes in the path as it is and be sure not to include any wild cards

 $Files = Get-ChildItem -Name -LiteralPath "\\\\pdw01rasci001\\SSISPackages\\PROD\\Logs\\exec_package_OrderAnalytics_EXTR.dtsx" echo "$Files" 

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