Reputation: 11
I have looked for weeks, and had others research with/for me, but I haven't found the answer to this.
I have a script that lives on server 1, and needs to be executed on server 1 using certain credentials. The ultimate solution will help with decrypting files. The script must execute as a certain user on a certain server because the key pair is in the user's key ring on that server.
I want the script to be called from server 2 as part of a larger process. Server 2 has a sql job which has the following flow:
The script on server 1 runs locally without any issues, and produces the expected results. When attempting to have server 2 execute the script on server 1, I haven't had any success. In order to get as simple as possible for finding out what is actually not working, I came up with a set of scripts which are simple (see below).
I am not a powershell guru of any kind - so I apologize now if it is a very obvious thing. :)
#-------------------------------------
# script 1
# this script lives on server 1
# file name: c:\deleteme\helloworld2.ps1
$CMD = Invoke-Expression " `"hello world`" >> C:\deleteme\helloworld.txt"
Invoke-Command -ScriptBlock { $CMD }
#-------------------------------------
# script 2
# this script is executed on server 2 and attempts to execute the script on server 1
$session = New-PSSession -ComputerName "SERVER01.lahcg.com" #-Credential $username
$CMD = "Invoke-Command -ScriptBlock { powershell.exe `"C:\deleteme\helloworld2.ps1`" } "
#write-output $CMD
Invoke-Command -Session $session -ScriptBlock { $CMD }
Remove-PSSession $session
Environment Info:
Extra Notes
Upvotes: 1
Views: 3590
Reputation: 328
BenH is correct. You have two options. You can either use
Invoke-Command is the faster way to do it since it automatically establishes a PSSession, executes the code, then tears it down. The issue with it is that it doesn't allow you to control which user establishes the session. For that you have to build the session yourself then tell Invoke-Command which session to use. So try something like this:
Upvotes: 1