如何在invoke-command中使用不同的凭据

时间:2017-06-14 12:42:41

标签: powershell

我目前正在尝试从其他服务器获取值。所以我使用$sessionUsername$sessionPassword连接到服务器,但后来我需要使用不同的凭据来获取我需要的信息。

我不确定我是如何做到这一点的,到目前为止,我已尝试在Start-Job内部执行Start-ProcessInvoke-Command甚至是另一个调用程序命令,但这还没有工作

$sessionUserName = "mysession"
$sessionPassword = "sessionPassword"
#$sessionUserName = "LON\user"
#$sessionPassword = "user"

$serverAddress = "the address"

$securePassword = ConvertTo-SecureString -AsPlainText -Force -String $sessionPassword
$credentials = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $sessionUserName,$securePassword
$session = New-PSSession -ComputerName $serverAddress -Credential $credentials
$username = "LON\differentuser"
$password = "different password"
$PSS = ConvertTo-SecureString $password -AsPlainText -Force
$cred = new-object system.management.automation.PSCredential $username,$PSS


Invoke-Command -Session $session -scriptblock { 

    #Start-Process "C:\StuckApps\powershell.exe" -Credential $args[0] -ArgumentList "-file C:\StuckApps\connect.ps1"

    $args[0].GetNetworkCredential().username;
    $args[0].GetNetworkCredential().password;

    $t = {
        $args[0].GetNetworkCredential().username;
        $args[0].GetNetworkCredential().password;

        $conn = New-Object System.Data.SqlClient.SqlConnection
        $conn.ConnectionString = "Server = Theserver.co.uk; Database = m; Integrated Security = true;"

        $conn.Open()
        $command = New-Object System.Data.SqlClient.SqlCommand
        $command.CommandTimeout = 0
        $command.CommandText = "exec dbo.AlphaBoard_GetStuckApps"
        $command.Connection = $conn
        $rows = $command.ExecuteReader()
        $dt = New-Object System.Data.DataTable
        $dt.Load($rows)
        $number = $dt.Rows.Count
        $conn.Close()
        return $number
        Write-Host "Hello"
    } 
    Start-Job -ScriptBlock $t -Credential $args[0]

    #Start-Process powershell -ArgumentList '-executionpolicy','bypass', $t -Credential $session
    $number

} -ArgumentList $cred
$number
$previousNumberPath = "C:\bamboo-home\xml-data\build-dir\INT-SAM-JOB1\number.txt"

invoke-command中的$args[0].GetNetworkCredential().username;向我显示这是在传递凭据,但是我如何使用它们?我不确定我做错了什么?我似乎无法取回$number变量,我该怎么做?

我遇到的主要问题是错误

  

由于错误,无法运行此命令:访问被拒绝。

我不确定为什么会发生这种情况,就像我运行的服务器本身一样:

Start-Process powershell.exe -Credential $cred -ArgumentList "noexit", "-file C:\StuckApps\connect.ps1"

我也试过我当前的脚本,它工作正常,但在我的脚本上使用它显示访问被拒绝。我已经通过第一次调用命令进入服务器,为什么我得不到相同的结果?

0 个答案:

没有答案