Create Sql DB with powershell searching for dacpac and naming db with Folder its located in
我正在尝试通过在文件夹中搜索 *.dacpac 文件来在 Sql Server 中创建数据库,对于找到的每个 .dacpac,我需要使用找到 .dacpac 的文件夹的名称创建一个数据库。
例子
C:\\\\\\\\文件夹\\\\\\\\包含
- C:\\\\\\\\文件夹\\\\\\\\Project1\\\\\\\\mydatabase.dacpac
- C:\\\\\\\\文件夹\\\\\\\\Project2\\\\\\\\mydatabase.dacpac
- C:\\\\\\\\文件夹\\\\\\\\Project3\\\\\\\\mydatabase.dacpac
创建 Db 的脚本
1 2 | cd"C:\\Program Files (x86)\\Microsoft SQL Server\\130\\DAC\\bin" $createDB = .\\sqlpackage.exe /Action:Publish /SourceFile:"c:\\Folder\\Project1\\mydatabase.dacpac" /TargetDatabaseName:"Project1" /TargetServerName:"(LocalDB)\\MSSQLLocalDB" |
我可以使用以下
获取要用作 TargetDatabaseName 的文件夹名称
1 2 3 4 5 | PS C:\\> $FolderName = Get-ChildItem C:\\Folder | select -ExpandProperty Name $FolderName Project1 Project2 Project3 |
我正在尝试使用 foreach 循环来查找 dacpac 文件并将它们用作 SourceFile,然后查找 FolderName 以用作 TargetDatabaseName
1 2 3 4 | $FolderName = Get-ChildItem C:\\Folder | select -ExpandProperty Name $dacpacfile = Get-ChildItem C:\\Folder -Recurse -Include *.dacpac foreach ($dacpac in $dacpacfile){ $createDB = .\\sqlpackage.exe /Action:Publish /SourceFile:$dacpacfile /TargetDatabaseName:$FolderName /TargetServerName:"(LocalDB)\\MSSQLLocalDB"} |
收到的错误是:
.\\sqlpackage.exe : * Could not load package from
'C:\\Folder\\Project1\\mydatabase.dacpac
C:\\Folder\\Project2\\mydatabase.dacpac
C:\\Folder\\Project3\\mydatabase.dacpac'. At line:4 char:21
+ ... $createDB = .\\sqlpackage.exe /Action:Publish /SourceFile:$dacpacfile ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (* Could not l...tabase.dacpac'.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
我希望我需要创建两个数组并尝试一起逐步完成它们但是无法做到这一点,任何帮助将不胜感激。
来,试试这个:
1 2 3 4 5 6 7 8 | $dacpacFiles = Get-ChildItem C:\\project -Recurse -Include *.dacpac cd"C:\\Program Files (x86)\\Microsoft SQL Server\\140\\DAC\\bin" foreach ($dacpacFile in $dacpacFiles) { $dir = Split-Path $dacpacFile.Directory -Leaf $filePath = $dacpacFile.FullName $createDB = .\\sqlpackage.exe /Action:Publish /SourceFile:$filePath /TargetDatabaseName:$dir /TargetServerName:"." } |