Methods to start process in C# and powershell

private int StartProcess(SoftwareSvr swSvr, string workingDir)
{
    Process proc = new Process();
    proc.StartInfo.UseShellExecute = true;
    proc.StartInfo.WorkingDirectory = workingDir;
    proc.StartInfo.FileName = swSvr.Command;

    if (swSvr.Args != null && swSvr.Args.Any())
    {
        proc.StartInfo.Arguments = string.Join(' ', swSvr.Args);
    }

    bool started = proc.Start();

    if (started)
    {
        return proc.Id;
    }
    else
    {
        return -1;
    }
}
private int StartProcessByPs(SoftwareSvr swSvr, string workingDir)
{
    /*
     * 1. wmic process call create "cluster\GatewayServer.exe start -id 1", "c:\app\", 但wmic启动的进程中不使用系统的环境变量
     * 2. powershell -Command "try{$app = Start-Process -PassThru -FilePath \"cluster\GatewayServer.exe\" -WorkingDirectory \"C:\app\" -ArgumentList \"start -id 5\";echo $app.Id} catch {throw}"
     */
    Process proc = new Process();
    proc.StartInfo.WorkingDirectory = workingDir;
    proc.StartInfo.FileName = @"C:\windows\system32\cmd.exe";
    proc.StartInfo.RedirectStandardOutput = true;
    var psArgs = string.Empty;

    if (swSvr.Args != null && swSvr.Args.Any())
    {
        psArgs = " -ArgumentList \\\"{string.Join(' ', swSvr.Args)}\\\"";
    }

    var psCmd = $"/C powershell -Command \"try{{$app = Start-Process -PassThru -FilePath \\\"{swSvr.Command}\\\" -WorkingDirectory \\\"{workingDir}\\\"{psArgs};echo $app.Id}} catch {{throw}}\"";
    proc.StartInfo.Arguments = psCmd;
    proc.Start();
    proc.WaitForExit();
    var output = proc.StandardOutput.ReadToEnd();

    if (proc.ExitCode != 0)
    {
        _logger.LogWarning($"Failed to start process: {proc.StartInfo.Arguments}, output: {output}");
        return -1;
    }
    else
    {
        return int.Parse(output);
    }
}

In Powershell

$taskName = "DelayStartup";


$t = New-ScheduledTaskTrigger -Once -At (Get-Date).AddSeconds(2);
$t.EndBoundary = (Get-Date).AddSeconds(60).ToString('s');
Register-ScheduledTask -Force -TaskName $taskName -Action (New-ScheduledTaskAction -Execute C:\test.bat) -Trigger $t -Principal (New-ScheduledTaskPrincipal -UserID \\\"NT AUTHORITY\\SYSTEM\\\" -LogonType ServiceAccount -RunLevel Highest) -Settings (New-ScheduledTaskSettingsSet -DeleteExpiredTaskAfter 00:00:01)";


$t = New-ScheduledTaskTrigger -Once -At (Get-Date).AddHours(24);
Register-ScheduledTask -Force -TaskName $taskName -Action (New-ScheduledTaskAction -Execute C:\test.bat) -Trigger $t -Principal (New-ScheduledTaskPrincipal -UserID \\\"NT AUTHORITY\\SYSTEM\\\" -LogonType ServiceAccount -RunLevel Highest);
Start-ScheduledTask -TaskName $taskName;
Start-Job -ScriptBlock { Start-Sleep -s 10; Unregister-ScheduledTask -Confirm -TaskName 'DelayStartup'";};


Register-ScheduledTask -Force -TaskName $taskName -User '\\ContainerAdmin' -Password 'AutoOps#1' -Action (New-ScheduledTaskAction -Execute C:\test.bat);
Start-ScheduledTask -TaskName $taskName";

Leave a Comment