This is the PS-snippet that I have so far. Starting the detached process works fine, but I cannot set the ProcessStartupInformation. How can this be done? Also this code sometimes comes up with error code 8 or 21 in a fresh PS instance. I could not find a pattern for this error till now. But it happens, when I run this code multiple times in a row without closing the previously created notepad-process.
$startup = Get-WmiObject Win32_ProcessStartup
$arguments = @{
CommandLine = 'notepad.exe' # or just 'notepad'?
CurrentDirectory = 'c:\windows\system32'
# ProcessStartupInformation = $startup
}
Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments $arguments
For any reason, the command "Get-CimInstance -ClassName Win32_ProcessStartup" is not returning anything in latest Windows 11 here.
MSDN has this VB-sample code, but I dont know how to convert this into Powershell:
Const HIDDEN_WINDOW = 12
strComputer = "."
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objStartup = objWMIService.Get("Win32_ProcessStartup")
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = HIDDEN_WINDOW
Set objProcess = GetObject("winmgmts:root\cimv2:Win32_Process")
errReturn = objProcess.Create("Notepad.exe", null, objConfig, intProcessID)
Or should I better use any other (more reliable) option to start a detached process?
Update: This is the code I am now using, but still getting this annoying error codes 8 and 21 when running it multiple times:
# sample code starting a detached notepad-process
# referennce:
# https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-processstartup#properties
# https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-showwindow
$startup = [ciminstance]::new((Get-CimClass 'Win32_ProcessStartup'))
$startup.ShowWindow = 5 # hidden=0, normal=5, minimize=7, hidden=12
$startup.PriorityClass = 16384 # below normal
$arguments = @{
CommandLine = 'notepad.exe'
CurrentDirectory = 'c:\windows\system32'
ProcessStartupInformation = $startup
}
Invoke-CimMethod -ClassName Win32_Process -MethodName Create -Arguments $arguments
Create a [ciminstance]
object and pass the class as the first argument:
# create and configure startup object
$processStartup = [ciminstance]::new((Get-CimClass 'Win32_ProcessStartup'))
$processStartup.ShowWindow = 12
# attach to argument table
$arguments['ProcessStartupInformation'] = $processStartup