【发布时间】:2020-11-20 21:00:59
【问题描述】:
我正在尝试编写一个脚本,该脚本使用 powershell cmdlet get-content tail 并将新行插入到 sql server 表中。我无法获得将尾部通过管道传递到处理表插入的 sqlinsert.ps1 文件的语法。
我正在寻找有关如何将“get-content tail”通过管道传输到 sqlinsert.ps1 文件以执行 sql 数据库插入语句的帮助:
$startTime = get-date
Write-Host "\\iisserver\logs\Logs-$("{0:yyyyMMdd}" -f (get-date)).txt"
get-content "\\iisserver\logs\Logs-$("{0:yyyyMMdd}" -f (get-date)).txt" -tail 1 -wait | & "sqlinsert.ps1" -stmp $("{0:yyyy-MM-dd hh:mm:ss.fff}" -f (get-date)) -method "Error" -msg $_
# % { "$_ read at $(Get-Date -Format "hh:mm:ss")" }
在 sqlinsert.ps1 中:
param ([string]$stmp, [string]$method, [string]$msg )
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$serverName';database='$databaseName';User ID = $uid; Password = $pwd;"
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$sql = "insert into [tbl_iiserrors] (errstamp, method, msg) values (@stmp , @method, @msg) "
。 . .
我得到的错误:
& : 术语“sqlinsert.ps1”未被识别为 cmdlet、函数、脚本文件或可运行的程序。检查拼写 的名称,或者如果包含路径,请验证该路径是 正确并重试。在 C:\Temp\ob\iislog\tst_tail.ps1:3 char:95
- ... Mdd}" -f (get-date)).txt" -tail 1 -wait | & "sqlinsert.ps1" -stmp $ ...
~~~~~~~~~~~~~~~
- CategoryInfo : ObjectNotFound: (sqlinsert.ps1:String) [], CommandNotFoundException
- FullyQualifiedErrorId : CommandNotFoundException
建议[3,General]:找不到命令sqlinsert.ps1,但是 确实存在于当前位置。 Windows PowerShell 不加载 默认情况下来自当前位置的命令。如果你相信这个 命令,而是键入:“.\sqlinsert.ps1”。请参阅“获取帮助 about_Command_Precedence”了解更多详情。
当我从 powershell 命令运行 sqlinsert.ps1 时,它可以工作: PS c:\temp> .\sqlinsert -stmp 2020-11-20 00:00:00 -method 'eek' -msg 'uh hello'
【问题讨论】:
-
错误提示在当前目录下找不到文件。尝试使用完整路径:
& 'C:\temp\sqlinsert.ps1' -
在管道之后,我将其更改为 .\sqlinsert.ps1 -stmp $("{0:yyyy-MM-dd hh:mm:ss.fff}" -f (get-date) ) -method "Error" -msg $_ 它看起来像是在运行,但看起来不像是正确通过?我没有看到任何插入。
标签: powershell