简体   繁体   中英

Passing path to function makes Get-ChildItem return more files

I have a simple command which lists all files in the scriptfolder

$files = Get-ChildItem -Path $PSScriptRoot
foreach ($file in $files)
{
    Write-Host $file
}

It gives me the following output:

PS C:\Users\ivu> D:\jenkins\workspace\DeploymentInstaller\usemod.ps1
functions.psm1
installClient.ps1
installClientParams.ps1
usemod.ps1

Question: Now the behaviour which i can not explain happens, when I wrap the code by a function and a filter Get-ChildItem suddenly returns much more files.
Can someone explain this behaviour?

Function funct($path, $regex){
    Write-Host $path
    Write-Host $regex

    $files = Get-ChildItem -Path $path -Filter $regex
    foreach ($file in $files)
    {
        Write-Host $file
    }
}
funct($PSScriptRoot, "*")

Output

PS C:\Users\ivu> D:\jenkins\workspace\DeploymentInstaller\usemod.ps1
functions.psm1
installClient.ps1
installClientParams.ps1
usemod.ps1
C:\Users\ivu\.dbvis
C:\Users\ivu\.eclipse
C:\Users\ivu\.squirrel-sql
C:\Users\ivu\.swt
C:\Users\ivu\Citrix
C:\Users\ivu\Contacts
C:\Users\ivu\Desktop
C:\Users\ivu\Documents
C:\Users\ivu\Downloads
C:\Users\ivu\faab
C:\Users\ivu\Favorites
C:\Users\ivu\Links
C:\Users\ivu\Music
C:\Users\ivu\Pictures
C:\Users\ivu\Saved Games
C:\Users\ivu\Searches
C:\Users\ivu\Tracing
C:\Users\ivu\transfer
C:\Users\ivu\Videos
C:\Users\ivu\workspace
C:\Users\ivu\.jboss-cli-history
C:\Users\ivu\bla.txt
C:\Users\ivu\Icc.state

You're calling the function incorrectly. By using a comma in the arguments you actually end up passing an array, so you're basically saying:

Get-ChildItem D:\jenkins\workspace\DeploymentInstaller
Get-ChildItem C:\Users\ivu

If you were to call as follows, you'll get the expected result:

funct $PSScriptRoot "*"

And I say "expected result" as in that will list the files at

D:\\jenkins\\workspace\\DeploymentInstaller

because the script you're calling is in that directory and thus $PSScriptRoot will contain that value.

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