0

我正在尝试从 PowerShell 脚本调用 SQLCMD,但 Powershell 似乎不喜欢我如何将 -InputFile 传递给 Invoke-Sqlcmd。我的代码看起来像这样:

$files = Get-ChildItem -Path $PSScriptRoot -Recurse | Where-Object { $_.Name -match $regex};
Invoke-Sqlcmd -InputFile $files[0].FullName

$files 永远不会为空,因为打印 $files[0].FullName 会输出类似“D:\foo\foo.sql”的字符串。当我的应用程序到达这一行时,它会抛出一个错误,指向我使用 Invoke-Sqlcmd 和“$files”中的“$”字符的同一行。

我收到这两条错误消息:

Invoke-Sqlcmd : The pipeline has been stopped.
    + CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], PipelineStoppedException
    + FullyQualifiedErrorId : SqlExectionError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

Invoke-Sqlcmd : An expression of non-boolean type specified in a context where a condition is expected
    + CategoryInfo          : InvalidOperation: (:) [Invoke-Sqlcmd], SqlPowerShellSqlExecutionException
    + FullyQualifiedErrorId : SqlError,Microsoft.SqlServer.Management.PowerShell.GetScriptCommand

我如何提供要运行的脚本的文件路径有问题吗?什么是正确的格式。我也尝试使用 .PSPath 而不是 .FullName 但我收到一条错误消息,指出不支持文件路径。

4

1 回答 1

0

该消息非常具体,并说 Invoke-SqlCmd 不喜欢您传入的内容。传递使用的变体类型很重要。

这个 ...

$files = Get-ChildItem -Path $PSScriptRoot -Recurse 

...当然,在其他任何事情发生之前就被填充了。不管你后来做什么。

仅供参考,至于这个...

Where-Object { $_.Name -match $regex};

...在 PowerShell 中,您真的不需要那个分号,除非在特定情况下。分号是代码终止符,通常在控制台主机窗口中用于将内容保持在一行,但在大多数情况下并不是脚本或模块真正需要的东西。

你会看到它被来自其他语言的人使用,因为习惯,以及那些试图将所有东西都塞在一条线上的人,并称它为单线,但实际上并非如此。

试试这种方式。

(Get-ChildItem -Path $PSScriptRoot -Filter $RegEx).FullName[0]

所以,你最终会得到像这样更直接的东西......

$regex = '*.sql'
(Get-ChildItem -Path $PSScriptRoot -Filter $RegEx).FullName[0] | 
Invoke-Sqlcmd -InputFile $PSItem

因此,没有理由在 Invoke-Sqlcmd 调用中添加额外的变量和添加 Where-Object 和点符号。

你也可以这样做...

Invoke-Sqlcmd -InputFile $files[0].FullName

... 这边走

Invoke-Sqlcmd -InputFile ($files.FullName)[0]
于 2020-01-17T17:31:36.960 回答