为什么我的PowerShell Invoke SQLCMD InputFile出现错误?

为什么我的PowerShell Invoke SQLCMD InputFile出现错误?,powershell,sqlcmd,invoke-sqlcmd,Powershell,Sqlcmd,Invoke Sqlcmd,我试图从PowerShell脚本调用SQLCMD,但PowerShell似乎不喜欢我传递-InputFile来调用SQLCMD的方式。我的代码如下所示: $files = Get-ChildItem -Path $PSScriptRoot -Recurse | Where-Object { $_.Name -match $regex}; Invoke-Sqlcmd -InputFile $files[0].FullName 打印$files[0]时,$files从不为空。FullName输出类

我试图从PowerShell脚本调用SQLCMD,但PowerShell似乎不喜欢我传递-InputFile来调用SQLCMD的方式。我的代码如下所示:

$files = Get-ChildItem -Path $PSScriptRoot -Recurse | Where-Object { $_.Name -match $regex};
Invoke-Sqlcmd -InputFile $files[0].FullName
打印$files[0]时,$files从不为空。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,但我收到一个错误,说文件路径不受支持。

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

这个

$files = Get-ChildItem -Path $PSScriptRoot -Recurse 
。。。当然,在其他任何事情发生之前都会被填充。不管你以后做什么

仅供参考,关于这个

Where-Object { $_.Name -match $regex};
。。。在PowerShell中,您真的不需要那个分号,除非在特定情况下。分号是一个代码终止符,通常在consolehost窗口中用于将内容保持在一行,但在大多数情况下,脚本或模块并不需要分号

你会看到它被其他语言的人使用,因为习惯,还有那些试图把所有东西都塞进一行,并称之为一行的人,但事实并非如此

换个办法试试

(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]

这是脚本中的命令导致的错误,可以从
SqlError
中识别出来,因此它可能与您在PowerShell中的操作无关。例如,您可以使用
选择1,其中1
,因为
1
作为条件无效。