由于某些原因,InvokeQuery模块中的Invoke-SqlServerQuery使用错误的用户名来实现集成安全性。示例:
PS C:\> whoami
desktop-7htqmm0\horizon-vm
PS C:\> $env:USERNAME
HORIZON-VM
PS C:\> [System.Security.Principal.WindowsIdentity]::GetCurrent().Name
DESKTOP-7HTQMM0\HORIZON-VM
PS C:\> Invoke-SqlServerQuery -Sql "SELECT * FROM table1" -ConnectionString "server=DESKTOP-7HTQMM0\SQLEXPRESS;database=test1;integrated security=sspi;"
Invoke-SqlServerQuery : Cannot open database "test1" requested by the login. The login failed.
Login failed for user 'MicrosoftAccount\<redacted_email>@gmail.com'.
At line:1 char:1
+ Invoke-SqlServerQuery -Sql "SELECT * FROM table1" -ConnectionString " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Invoke-SqlServerQuery], SqlException
+ FullyQualifiedErrorId : System.Data.SqlClient.SqlException,InvokeQuery.InvokeSqlServerQuery
但是,SqlPs模块的功能很好:
PS C:\> Invoke-Sqlcmd -ServerInstance DESKTOP-7HTQMM0\SQLEXPRESS -Database test -Query "SELECT * FROM table1"
pk someint somestring somedatetime
-- ------- ---------- ------------
7a836fe1-dda6-4496-8af8-065cf45e4922 213 hey hey hey 9/10/2018 9:09:50 PM
7cb4a34d-74be-4c4b-9ffe-35a076d1c018 321 yo yo yo 9/10/2018 9:09:50 PM
92bae90e-8101-428e-bea3-69c520f6c1d8 123 blah blah blah 9/10/2018 9:09:50 PM
表是在创建数据库后通过此查询生成的(来自InvokeQuery's Github):
use [test]
GO
CREATE TABLE [dbo].[table1](
[pk] [uniqueidentifier] NOT NULL,
[someint] [bigint] NOT NULL,
[somestring] [nvarchar](500) NOT NULL,
[somedatetime] [datetime2](7) NOT NULL,
CONSTRAINT [PK_table1] PRIMARY KEY CLUSTERED ([pk] ASC)
)
GO
--Seed data
insert into table1 values (NEWID(), 123, 'blah blah blah', GETDATE())
insert into table1 values (NEWID(), 321, 'yo yo yo', GETDATE())
insert into table1 values (NEWID(), 213, 'hey hey hey', GETDATE())
除非为此目的创建SQL用户的变通办法,否则我想使集成安全性正常工作。如何获取当前用户的正确名称?