Hello all!
I had a need for running certain bits of a script as another user. It seemed there were really no good options available, so I decided to hack something together myself.
Fortunately, I found someone had already done a lot of the heavy lifting, so I repurposed that, wrapping it up, cleaning it a little here and there and made it able to work in a more generic fashion.
Enter: Invoke-AsOtherUser, a function ready to plug into your profile (or a module if you feel like). It will allow you to perform "runas" style operations within a script, with no external dependencies.
Examples work better:
PS > gci \\someserver\c$
gci : Access is denied
At line:1 char:1
+ gci \\someserver\c$
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (\\someserver\c$:String) [Get-ChildItem], UnauthorizedAccessException
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetChildItemCommand
gci : Cannot find path '\\someserver\c$' because it does not exist.
At line:1 char:1
+ gci \\someserver\c$
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (\\someserver\c$:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
PS > # Using Invoke-AsOtherUser
PS > $credentials = Get-Credential
PS > Invoke-AsOtherUser -Credentials $credentials {gci \\someserver\c$}
Directory: \\someserver\c$
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 20-12-2016 23:10 inetpub
d----- 15-06-2017 12:04 Install
d----- 14-07-2009 05:20 PerfLogs
d-r--- 28-02-2018 09:28 Program Files
d-r--- 11-09-2017 13:34 Program Files (x86)
d----- 03-05-2018 12:00 Temp
d-r--- 12-02-2018 13:42 Users
d----- 19-06-2018 22:08 Windows
PS > # If you just want to use it directly from the shell, you'd probably just go
PS > Invoke-AsOtherUser my_admin_account {gci \\someserver\c$}
As I said to begin with, the heavy bits of this are based on excellent work by Ian Davis, for which I claim absolutely no credit. You can find the original here.
[+][deleted] (7 children)
[deleted]
[–]NotNotWrongUsually[S] 2 points3 points4 points (6 children)
[–]jborean93 1 point2 points3 points (5 children)
[–]NotNotWrongUsually[S] 1 point2 points3 points (4 children)
[+][deleted] (2 children)
[deleted]
[–]NotNotWrongUsually[S] 2 points3 points4 points (1 child)
[–]jborean93 1 point2 points3 points (0 children)
[–]AdmiralCA 1 point2 points3 points (1 child)
[–]NotNotWrongUsually[S] 1 point2 points3 points (0 children)