带-Credential的InitializationScript

时间:2017-10-05 14:35:44

标签: powershell powershell-v2.0 start-job

我在启动作业中遇到初始化函数问题。我正在尝试调用cmd-let start-job中的函数, 以便在scriptBlock中无需重复它们 这就是我想要的。这基本上是没有尝试和捕获的代码。

$username = ******
$password = ******
$sec_password = ConvertTo-SecureString -String $password -AsPlainText -Force
$creds = New-Object -Typename System.Management.Automation.PSCredential -ArgumentList $username, $sec_password
$functions = {
    Function GenericSqlQuery
    {
        $Datatable = New-Object System.Data.DataTable
        $Connection = New-Object System.Data.SQLClient.SQLConnection
        $Connection.ConnectionString = "Server=localhost;Trusted_Connection=True;Connection Timeout=30;"
        $connection.Open()
        $Command = New-Object System.Data.SQLClient.SQLCommand
        $Command.Connection = $Connection
        $Command.CommandText = "Select @@servername as name" <# for example #>
        $DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $Command
        $DataAdapter.SelectCommand.CommandTimeout = 600
        $Dataset = new-object System.Data.Dataset
        [void]$DataAdapter.Fill($Dataset)
        return $Dataset.tables[0]
    }
}
[Scriptblock]$Scriptblock = {
    GenericSqlQuery
}
Start-Job -InitializationScript $functions -ScriptBlock $Scriptblock -Credential $creds | Wait-Job | Receive-Job

 CategoryInfo          : OpenError: (localhost:String) [], PSRemotingTransportException
    + FullyQualifiedErrorId : -2147467259,PSSessionStateBroken
error: [localhost] An error occurred while starting the background process. Error reported: The stub received bad data. 

我知道你说你的凭据已损坏,但我的代码没有 - InitializationScript ,带有$ creds且没问题。

0 个答案:

没有答案