X++ run a process with user credentials
April 6th, 2010
6 comments
When you want to run for example a command prompt from within the X++ language, you can use the following code :
Let’s assume that the following parameters were passed to the method :
- FileName : “C:\windows\system32\cmd.exe”
- Arguments : “”
- RunAsAdmin : true
- UseShellExecute : true
- WaitForExit : false
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 | static void runWindowsProcess( FileName _fileName , str _arguments , boolean _runAsAdmin = false , boolean _useShellExecute = false , boolean _waitForExit = false) { System.Diagnostics.ProcessStartInfo processStartInfo; System.Diagnostics.Process process; System.OperatingSystem operatingSystem; System.Version operatingSystemVersion; System.Exception ex; int major; Boolean start; ; try { // Assert CLRInterop permission new InteropPermission(InteropKind::ClrInterop).assert(); // BP deviation documented processStartInfo = new System.Diagnostics.ProcessStartInfo(_fileName, _arguments); // BP deviation documented process = new System.Diagnostics.Process(); // Get an instance of the System.OperatingSystem class operatingSystem = System.Environment::get_OSVersion(); // Get the OS version number operatingSystemVersion = operatingSystem.get_Version(); // If admin rights asked if(_runAsAdmin) { major = operatingSystemVersion.get_Major(); // Get the major part of the version number (Starting from Windows Vista) if(major >= 6) { // Start using the runAs property which will prompt for administrator credentials processStartInfo.set_Verb('runas'); } } // Use the system shell to execute the process processStartInfo.set_UseShellExecute(_useShellExecute); // Attach the starting information to the process process.set_StartInfo(processStartInfo); // Start the process and wait for it to complete start = process.Start(); // Wait for the process to finish if(_waitForExit) { process.WaitForExit(); } // Revert permission CodeAccessPermission::revertAssert(); } catch(Exception::CLRError) { // BP Deviation documented ex = ClrInterop::getLastException(); while (ex != null) { error(ex.ToString()); ex = ex.get_InnerException(); } throw error(strFmt("@HEL270", _fileName)); } } |