如何读取带有长字符串的.sql文件,如下所示,并执行下面演示的powershell命令。问题是它需要一行"
$Q = Get-Content C:\Charms\t-sql\AdUserCreation.sql
$CH=Get-SqlServerData -SqlServerInstanceName "server" -DbName "mydatabase" -SqlQuery $Q
$ SqlQuery类
SELECT DISTINCT
p.PersonId AS EmployeeIdentification,
Si.SiteInitials,
LOWER((LEFT(p.FirstName,1) + p.SurName)) AS UserName,
p.FirstName,
p.SurName As Lastname,
p.SurName + ', ' + p.FirstName + ' (MSH)@DSH' AS DisplayName,
A.[Address1],
A.City,
'CA' AS CA,
A.PostalCode As ZipCode,
'%ProfilesFolder%\%USERNAME%\' AS ProfilePath,
'DSH' AS Department,
LOWER((LEFT(p.FirstName,1) + p.SurName)) AS SamAccountName,
(CASE WHEN charindex('-', rtrim(ltrim(p.SurName))) > 0 THEN LOWER(LEFT(rtrim(ltrim(p.FirstName)),
1)) + LOWER(SUBSTRING(p.SurName, CHARINDEX('-', p.SurName) + 1, LEN(p.SurName))) + '@dsh.ca.gov' WHEN charindex(' ', rtrim(ltrim(p.SurName)))
> 0 THEN LOWER(LEFT(ltrim(rtrim(p.FirstName)), 1)) + LOWER(SUBSTRING(p.SurName, CHARINDEX(' ', p.Surname) + 1, LEN(p.SurName)))
+ '@dsh.ca.gov' ELSE LOWER(LEFT(ltrim(rtrim(p.FirstName)), 1) + rtrim(ltrim(p.SurName))) + '@dsh.ca.gov' END) AS UserPrincipalName,
class.ClassificationNumber AS ClassCode,
class.ClassificationTitle AS JobTitle,
p.PersonId AS EmployeeIdentification,
'Created Date : ' + CAST(GETDATE() AS varchar(100)) AS MyDescription
FROM dbo.Person AS p INNER JOIN
dbo.Staff AS s ON p.PersonId = s.PersonId INNER JOIN
dbo.Employee AS e ON s.StaffId = e.StaffId INNER JOIN
dbo.EmployeePosition AS ep ON e.EmployeeId = ep.EmployeeId
ect...
答案 0 :(得分:4)
这是一个文件(c:\temp\abc.txt
)
AA
BB
CC
使用简单Get-Content
给出
PS C:\Temp> $a = Get-Content C:\temp\abc.txt
PS C:\Temp> $a.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array
所以你可以试试这个:
PS C:\Temp> $a = Get-Content C:\temp\abc.txt -Raw
PS C:\Temp> $a.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
或者
PS C:\Temp> $a = Get-Content C:\temp\abc.txt | out-string
PS C:\Temp> $a.GetType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True String System.Object
答案 1 :(得分:0)
所有建议都未能运行。我是这样做的
$query = @"
SELECT TOP 1 *
FROM PERSON
"@
Function Get-SqlServerData
{
#required paramaters
param(
[string] $SqlServerInstanceName,
[string] $DbName,
[string] $SqlQuery
)
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$DataSet = New-Object System.Data.DataSet
$SqlConnection.ConnectionString ="Server = $SqlServerInstanceName ; Database = $DbName; Integrated Security = True"
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter.SelectCommand = $SqlCmd
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close();
Return $DataSet.Tables[0]
}
$data=Get-SqlServerData -SqlServerInstanceName "myseever" -DbName "mydatabasename" -SqlQuery $query