A follow on from Get Process ID after starting psexec
I would like to know how the answer to the question can be obtained using PSCommand and PowerShell.
I am out my depth and would like some help. Here's what I initially thought to translating the answer and is my failed attempt.
private int GetRemoteProcessId()
{
string remoteFilename = "ExampleBatfile.bat";
string remoteDirectory = "C:\\ExampleDirectory";
string remoteUsername = "ExampleUsername";
string remotePassword = "ExamplePassword";
string remoteIp = "ExampleIP";
PowerShell ps = PowerShell.Create()
.AddScript($"psexec.exe \\{remoteIp} -accepteula -u {remoteUsername} -p {remotePassword} -s -i -d - w {remoteDirectory} {remoteFilename}" )
.AddCommand( "Select-String" ).AddParameter( "process ID (\\d+)" )
.AddCommand( "ForEach-Object" ).AddParameter( "{$_.Matches.Groups[1].Value}" );
Collection<PSObject> results = ps.Invoke();
int remoteProcessId = ( int )results.First().BaseObject;
return remoteProcessId;
}
All I want is to obtain the process id from a remote process using psexec after starting it (same as the answered question) - But via C# PSCommands.
In the end, I realised the psexec proccess outputs the process id to the console. I ended up dumping the output of the psexec process to a temp file and parsing for the mentioned process id.
I'm sure there is a better/more secure way than this but it works!