I have this code, which gets all *.sql files in the current directory and for every child directory runs them on a specified $server
and $database
:
$dirs = Get-ChildItem | ?{ $_.PSIsContainer }
foreach ($d in $dirs)
{
$Result = Get-ChildItem ./ -Filter *.sql
Foreach($item in $Result)
{
echo $item.Name
sqlcmd /S $server /d $database -E -i $item
}
}
This code works just fine but it is just a stepping stone towards a script that should get all the *.sql files in the child directories and run them on the server.
This code is the same with the difference of ./
being replaced by $d
and it doesn't work:
$dirs = Get-ChildItem | ?{ $_.PSIsContainer }
foreach ($d in $dirs)
{
$Result = Get-ChildItem $d -Filter *.sql
Foreach($item in $Result)
{
echo $item.Name
sqlcmd /S $server /d $database -E -i $item
}
}
Instead I get the error:
SQLCMD.EXE : Sqlcmd: 'INSERT Script1.sql': Invalid filename.
At E:\dir\Run all SQL in dir.ps1:23 char:12
+ sqlcmd <<<< /S $server /d $database -E -i $item
+ CategoryInfo : NotSpecified: (Sqlcmd: 'INSERT...valid filename.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
As far as I could tell from testing $item
is the same in both cases and $Result
looks the same.
I have no idea why the second version does not work. I want the script to iterate over all child directories of the current directory it is located in, get all *.sql files in each one, print the name of the file and run it against the set $server
and $database
.