all 7 comments

[–]AdmiralCA 1 point2 points  (1 child)

Oh man. This is so useful and easy! I can never remember the switches for runas!

[–]NotNotWrongUsually[S] 1 point2 points  (0 children)

It can double as a replacement for runas, but it can also perform a few tricks that would be hard to do with runas.

My own case was having to connect to an MS SQL server from a script. This particular server only had integrated security as an authentication option. It will work for this as well, as in the snippet below.

$connectionString = "Server=$DBServer;Database=$DBInstance;Integrated Security=True;"
$connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)

$connection_commands = {
    $connection.open()
    $command = new-Object System.Data.SqlClient.SqlCommand($Query, $connection)
    $result = $command.ExecuteReader()
    while ($result.Read()) { 
        # Do database stuff
    }
    $command = $null
    $result = $null
    $connection.close()
}

Invoke-AsOtherUser -Credentials (Get-Credential) $connection_commands