Call scripts from a folder from a script

So I’ve got a bunch of Posh scripts in a folder, I want to call them all from a “caller” script at once. Something like the below:

$folder = "C:\Users\SameerMhaisekar\OneDrive - SquaredUp\Documents\PowerShell\MyScripts"
$scripts = $folder | Get-ChildItem | select name
foreach ($script in $scripts){
$output = $PSScriptRoot+"\$script"
&$output
}

The error I get is

& : The term ‘@{Name=master.ps1}’ is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:5 char:2

  • &$output
  •  + CategoryInfo          : ObjectNotFound: (\@{Name=master.ps1}:String) [], CommandNotFoundException
     + FullyQualifiedErrorId : CommandNotFoundException

Its because $scripts is not a string array but an object array, its property name is name (header when seen in console as a table). So you will have to Expand it like ...| Select-Object -ExpandProperty FullName to make it as a string.

I suggest to use full name as it will have full path.

other option is to use $script.name inside the loop like "$PSScriptRoot + $($script.Name)".
Proper way of joining path is using Join-Path cmdlet like

$ScriptPath = Join-Path -Path $PSScriptRoot -ChildPath $Script.Name
& $ScriptPath
1 Like