通过PowerShell将MSSQL作为其他用户启动时出错

时间:2014-11-10 13:03:15

标签: sql-server powershell

工作中有一个我需要经常进入的数据库,但你需要运行MSSQL2005作为一个不同的Windows帐户才能进入它。我厌倦了查找密码,右键单击快捷方式并告诉它以不同的用户身份运行,因此我创建了一个powershell脚本来启动MSSQL作为必需的用户。它成功启动程序并向您显示数据库中的表,但是当您打开表或尝试运行查询时,它会出现以下错误:

“Microsoft SQL Server Management Studio - 系统找不到指定的文件。(SQLEditors)”

如果我按正常方式操作(右键单击快捷方式并以其他用户身份运行),它可以正常工作。只有当我从powershell脚本打开它时才会出现问题。

我发现powershell脚本在该帐户登录到节点时有效,但是第二次注销它会再次死亡。我注意到的另一件事是我第一次使用powershell脚本加载MSSQL时,它询问了DB名称,即使它之前通过工作方式保存为最近的连接。这就像它没有找到正确的配置或者其他东西......我在过去的实际项目中使用过这个确切的脚本,所以它已经可以工作了,所以我假设这个问题与MSSQL2005有关。

剧本:

function Get-ScriptDirectory
    {
    $Invocation = (Get-Variable MyInvocation -Scope 1).Value;
    if($Invocation.PSScriptRoot)
    {
        $Invocation.PSScriptRoot;
    }
    Elseif($Invocation.MyCommand.Path)
    {
        Split-Path $Invocation.MyCommand.Path
    }
    else
    {
        $Invocation.InvocationName.Substring(0,$Invocation.InvocationName.LastIndexOf("\"));
    }
}
$curDir = Get-ScriptDirectory
$encpwd = Get-Content $curDir\password.bin
$passwd = ConvertTo-SecureString $encpwd

$exeLoc = "D:\Program Files\Microsoft SQL Server (x86)\90\Tools\Binn\VSShell\Common7\IDE\SqlWb.exe"
$cred = new-object System.Management.Automation.PSCredential '[username]' , $passwd
Start-Process $exeLoc -Cred $cred

编辑:SveinFidjestøl的评论解决了这个问题。 Start-Process在其末尾需要一个“-LoadUserProfile”。

1 个答案:

答案 0 :(得分:1)

许多Windows应用程序和服务都隐含要求必须加载用户配置文件。这似乎是SQL Server 2005的情况。

在PowerShell中,要在调用进程时加载用户配置文件,请将-LoadUserProfile参数传递给Start-Process cmdlet。因此,在您的示例中,您将像这样调用SQL Server

Start-Process $exeLoc -Cred $cred -LoadUserProfile
相关问题