嗨,大家好,感谢您的帮助,真的很感激。 我刚接触到PowerShell,使用powershell iam访问sql server的数据 我的查询正在执行,但查询输出为10表示数据正在填充数据集 我希望在$ version
中的10,20路径中连接数据$select=Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\'$version'\Setup Bootstrap\Log\Summary.txt' #|Out-File c:\pattern.txt
请在下面找到代码
param([string]$servername)
$filePath = "c:\temp\result.txt"
try
{
$SqlQuery = "select SUBSTRING(CONVERT(sysname, SERVERPROPERTY('ProductVersion')),0,CHARINDEX('.',convert(sysname,SERVERPROPERTY('ProductVersion')),0))"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $Servername; Database = master; Integrated Security = SSPI;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$version = $DataSet.Tables[0].rows[0].data
#$version=System.Data.DataSet.Tables[1].Rows[0][0]
Write-Host $version
$DataSet.Tables[0] | out-file "C:\temp\version.csv"
$defaultdata = $DataSet.Tables[0].rows[0].data
Write-Host $defaultdata
$select=Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\'$version'\Setup Bootstrap\Log\Summary.txt' #|Out-File c:\pattern.txt
$select1=Select-String -Pattern "Final result:" -Path 'C:\Program Files\Microsoft SQL Server\'$version'\Setup Bootstrap\Log\Summary.txt' |Out-File D:\temp\pattern.txt
write-host($select.Line.Length)
if( $select.Line.Length -gt 0 )
{
Write-Host 'Contains String'
$select2=Select-String -Pattern "Passed" -Path 'D:\temp\pattern.txt'
if($select.Line.Length -gt 0)
{
#out-File c:\temp\result.txt $filePath -Append
New-Item $filePath -ItemType file
'Success'| Out-File -FilePath $filePath -Append
}
else
{
New-Item $filePath -ItemType file
'Failed'| Out-File -FilePath $filePath -Append
}
}
else
{
Write-Host 'Does not contain String'
}
}
catch
{
Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
$errText = $Error[0].ToString()
if ($errText.Contains("network-related"))
{Write-Host "Connection Error. Check server name, port, firewall."}
Write-Host $errText
continue
}
我希望$ version = 10,因为查询输出10,不知何故我无法得到它, 虽然我在csv文件中获得相同的数据,但我想在$ version变量中获得相同的数据。
答案 0 :(得分:1)
当你调用数据时,有一个问题是数据集中没有数据列你可以做两件事 1: $ version = $ DataSet.Tables [0] .rows [0] .data
替换
$ version = $ DataSet.Tables [0] .rows [0] .Column1
或 2: 您可以更改SQLquery并为您选择的列命名,如下所示: $ SqlQuery =“选择SUBSTRING(CONVERT(sysname,SERVERPROPERTY('ProductVersion')),0,CHARINDEX('。',convert(sysname,SERVERPROPERTY('ProductVersion')),0))作为数据”