I am trying to open two instances of msftpsrvr.exe(CoreFtp) on my local system simultaneously using powershell. I have two .bat files to handle that but once i run it in a function, it overrides the earlier one.
I tried with Start-Process with -Wait but it doesn't proceed to the next step until manual intervention.
function StartSFTP
{
Start-Process -FilePath "C:\SFTP\XXX-in-Reg.bat" -Wait
Start-Process -FilePath "C:\SFTP\XXX-out-Reg.bat" -Wait
}
I tried with the workflow RunScripts(solution given on stack overflow) but to no luck.
function StartSFTP
{
Start-Process -FilePath "C:\SFTP\XXX-in-Reg.bat"
Start-Process -FilePath "C:\SFTP\XXX-out-Reg.bat"
}
Current output is it opens two windows of Coreftp having XXX-in-Reg.bat credentials(port no. and path)
I am pretty much learning this powerful language and hope I was clear in stating my problem.
Related
I'm trying to create a Powershell script that will be deployed to any node that is showing bad update health to automate some of the simple tasks without having to interrupt users during their workday. The Powershell script works perfectly if ran from an elevated PS prompt. It also runs fine when the same script is deployed to a test machine via SCCM with one exception: it won't call SFC.EXE /SCANNOW.
I've tried using:
Start-Process -FilePath "${env:Windir}\System32\SFC.EXE" -ArgumentList '/scannow' -Wait -NoNewWindow
Start-Process -FilePath "sfc.exe" -ArgumentList '/scannow' -Wait -NoNewWindow
Start-Process -FilePath "${env:Windir}\System32\SFC.EXE" -ArgumentList '/scannow' -RedirectStandardOutput "C:\SFC-Out.log" -RedirectStandardError "C:\SFC-Err.log" -Wait -NoNewWindow
& "sfc.exe" "/scannow"
Invoke-Command -ScriptBlock { sfc.exe /scannow }
Again, all of these examples work exactly as intended when run from an elevated PS prompt, but fail when run from the deployed PowerShell script. When I used the -RedirectStandardOutput, I checked the file SFC-Out.log and it read:
"Windows Resource Protection could not start the repair service"
I think this is because SCCM runs programs/scripts in the SYSTEM context instead of a user context (or even an elevated user context, but SYSTEM is supposed to be higher than an elevated session).
Is there a way to accomplish this? Sorry for the bad formatting, this is my first post on this site.
A bit late but I encountered the same issue. Not sure if this is the case for you but the cause was configuring the deployment of the script with SCCM to run as a 32 bit process. The script was being deployed to 64 bit systems. When I unchecked "run as 32 bit process" in the deployment configuration SFC worked without an issue under the context of a System account.
I created a package (not an application) in SCCM and had to use the redirect using the elusive sysnative folder for x64 machines:
https://www.thewindowsclub.com/sysnative-folder-in-windows-64-bit
So it would be:
C:\Windows\Sysnative\SFC.EXE /SCANNOW
What you have will work, just missing "-Verb RunAs" to elevate permissions. So your cmdlet should read:-
Start-Process -FilePath "${env:Windir}\System32\SFC.EXE" -ArgumentList '/scannow' -Wait -Verb RunAs
I've been reading and searching online for this, the only answer so far is that It can't be run due to sccm using the system account. It's also the same behavior when trying to run winmgt.
Fast forward to SCCM Current Branch 2109 and I was able to solve this problem by using the new Scripts feature built into SCCM. Using & 'sfc.exe' '/scannow' works, and I can manually run this script against any device collection showing devices in error. Start-Process -FilePath "sfc.exe" -ArgumentList "/scannow" -NoNewWindow -Wait works too.
I am running a script that involves writing to a database only certain users have access to, so we are running the script as a different user (passing in those user credentials) on our corporate network.
Despite trying things like -NoNewWindow or -WindowStyle Hidden, it always seems to pop up in a new window. This is an issue because when we launch the script from our Jenkins builder with a powershell build step, Jenkins doesn't like the second window and really appears to need it all in the main window.
We are using Start-Process, and the script call looks similar to this (I cut some of the details out):
Start-Process -NoNewWindow powershell.exe -Credential $credential -ArgumentList “Start-Process powershell.exe 'path\script.ps1 -param1 xxx -param2 yyy' -Verb runAs”
Any ideas as to how to get this to actually run without a popup window?
Thanks!
one of these should do the trick to you
Invoke-Command -ComputerName 'Same computer Name' -Credential '(PAss Cred object here)' -ScriptBlock {'Your Scripts Here'}
Invoke-Command -ComputerName 'Same computer Name' -Credential '(PAss Cred object here)' -FilePath 'FilePAthHere'
I'm trying to find a way to get PowerShell not to spawn a command window when running an executable using Start-Process.
If I call the executable directly within the script (e.g. .\program.exe) then the program runs (with its arguments) and the output is returned to the PowerShell window.
If I use Start-Process the program spawns a command window where the program runs and returns it's output.
If I try and use the -NoNewWindow switch of Start-Process the script then errors out saying it can't find the exe file.
I would prefer to use Start-Process to have access to the -Wait switch, as the programs and configurations the script makes can take some time individually to finish, and I don't want later commands starting up.
This code runs the executable in a separate command window:
Start-Process DeploymentServer.UI.CommandLine.exe -ArgumentList "download --autoDownloadOn --autoDownloadStartTime $StartTime --autoDownloadEndTime $EndTime" -Wait
This code runs the exe within the PowerShell console:
.\DeploymentServer.UI.CommandLine.exe download --autoDownloadOn --autoDownloadStartTime $StartTime --autoDownloadEndTime $EndTime
If I add the -NoNewWindow to the Start-Process code
Start-Process DeploymentServer.UI.CommandLine.exe -ArgumentList "download --autoDownloadOn --autoDownloadStartTime $StartTime --autoDownloadEndTime $EndTime" -Wait -NoNewWindow
I get the following error:
Start-Process : This command cannot be executed due to the error: The system
cannot find the file specifie
At C:\Temp\SOLUS3Installv1.3.ps1:398 char:22
+ Start-Process <<<< DeploymentServer.UI.CommandLine.exe -ArgumentList "download --autoDownloadStartTime $StartTime --autoDownloadEndTime $EndTime" -Wait -NoNewWindow
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOperationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.Commands.StartProcessCommand
You should prefix the executable name with the current directory when you use the -NoNewWindow switch:
Start-Process .\DeploymentServer.UI.CommandLine.exe -ArgumentList "download --autoDownloadOn --autoDownloadStartTime $StartTime --autoDownloadEndTime $EndTime" -Wait -NoNewWindow
Background information:
The first thing Start-Process tries to do is to resolve the value of the -FilePath parameter by PowerShell rules. If it succeeds, it replaces the value value passed with the full path to the command. If not, it leaves the value untouched.
In the Windows API there are two ways to start a new process: CreateProcess and ShellExecute. ShellExecute is the default, but if you use a cmdlet parameter that requires CreateProcess (for example, -NoNewWindow), then CreateProcess will be used. The difference between them, which matters for this question, is that when looking for a command to execute, CreateProcess uses the current process' working directory, while ShellExecute uses the specified working directory (which Start-Process by default passes based on the current filesystem-provider location, unless explicitly specified via -WorkingDirectory).
PS Test:\> 1..3 |
>> ForEach-Object {
>> New-Item -Path $_ -ItemType Directory | Out-Null
>> Add-Type -TypeDefinition #"
>> static class Test {
>> static void Main(){
>> System.Console.WriteLine($_);
>> System.Console.ReadKey(true);
>> }
>> }
>> "# -OutputAssembly $_\Test.exe
>> }
PS Test:\> [IO.Directory]::SetCurrentDirectory((Convert-Path 2))
PS Test:\> Set-Location 1
PS Test:\1> Start-Process -FilePath Test -WorkingDirectory ..\3 -Wait # Use ShellExecute. Print 3 in new windows.
PS Test:\1> Start-Process -FilePath .\Test -WorkingDirectory ..\3 -Wait # Use ShellExecute. Print 1 in new windows.
PS Test:\1> Start-Process -FilePath Test -WorkingDirectory ..\3 -Wait -NoNewWindow # Use CreateProcess.
2
PS Test:\1> Start-Process -FilePath .\Test -WorkingDirectory ..\3 -Wait -NoNewWindow # Use CreateProcess.
1
PowerShell does not update the current process' working directory when you change the current location for the FileSystem provider, so the directories can differ.
When you type:
Start-Process DeploymentServer.UI.CommandLine.exe -Wait -NoNewWindow
Start-Process cannot resolve DeploymentServer.UI.CommandLine.exe by PowerShell rules, since it does not look in the current FileSystem location by default. And it uses CreateProcess, since you specify -NoNewWindow switch. So, it ends up looking for DeploymentServer.UI.CommandLine.exe in the current process' working directory, which does not contains this file and thus causes an error.
I have a Java program which I would like to launch as a background process from a PowerShell script, similar to the way a daemon runs on Linux. The PowerShell script needs to do a couple of things:
Run the program as a separate and detached process in the background, meaning the parent window can be closed and the process keeps running.
Redirect the program's standard output and standard error to files.
Save the PID of the background process to a file so it can be terminated later by another script.
I have a shell script on Linux which starts the program like so:
$ java -jar MyProgram.jar >console.out 2>console.err &
I'm hoping to replicate the same behavior on Windows using a PowerShell script. I have tried using Start-Process with various combinations of options, as well as creating System.Diagnostics.ProcessStartInfo and System.Diagnostics.Process objects, but so far I am not having any luck. PowerShell starts the program as a background process, but the program abruptly terminates when the DOS window which started the PowerShell session is closed. I would like it to start in the background and be independent of the command window which started it.
The output redirection has also been troublesome, as it seems that the output and error streams can only be redirected in the process is being run in the same window (e.g., using -NoNewWindow).
Is this sort of thing possible in PowerShell?
Use jobs for this:
Start-Job -ScriptBlock {
& java -jar MyProgram.jar >console.out 2>console.err
}
Another option would be Start-Process:
Start-Process java -ArgumentList '-jar', 'MyProgram.jar' `
-RedirectStandardOutput '.\console.out' -RedirectStandardError '.\console.err'
Consider using the task scheduler for this. Define a task and set it without any triggers. That will allow you to simply "Run" (manually trigger) the task.
You can set up and/or trigger scheduled tasks using the ScheduledTasks powershell module, or you can use the GUI.
This is an old post but since I have it working fine thought it might help to share. Its the call to 'java' instead of 'javaw' that is likely your issue. Ran it out myself using my JEdit java program through powershell to launch it.
#Requires -Version 3.0
$MyDriveRoot = (Get-Location).Drive.Root
$JEditDir = $($mydriveroot + "jEdit") ;# Should be C:\jEdit or wherever you want. JEdit is a sub-directory.
$jEdit = $($JEditDir + "\jedit.jar" )
$jEditSettings = $($JEditDir + "\settings")
$JEditLogs = $($JEditDir + "\logs")
Start-Process -FilePath javaw -ArgumentList ( '-jar',"$jEdit", '-settings="$JEditSettings"' ) -RedirectStandardOutput "$JEditLogs\console.out" -RedirectStandardError "$JEditLogs\console.err"
Which you can turn into a little function and then an alias to make it easy to launch in Powershell.
If ( ( Test-Path $jedit) ) {
Function Start-JEdit() {
Start-Process -FilePath javaw -ArgumentList ( '-jar',"$jEdit", '-settings="$($mydriveroot + "jEdit\settings")"' ) -RedirectStandardOutput "$JEditLogs\console.out" -RedirectStandardError "$JEditLogs\console.err"
}
New-Alias -Name jedit -Force Start-JEdit -Description "Start JEdit programmers text editor"
}
Try this with PowerShell:
Start-Process cmd -Args /c,"java -jar MyProgram.jar" `
-WindowStyle Hidden -RSI console.out -RSE console.err
OR
Start-Process cmd -Args /c,"java -jar MyProgram.jar >console.out 2>console.err" `
-WindowStyle Hidden
This will start a detached cmd window that is hidden, and will redirect the std streams accordingly.
Old question, but since I had the same goal, I used answer from #use to acheive it.
So here is my code :)
$NAME_TASK = "myTask"
$NAME_TASKPATH = "\myPath\"
if ($args[0] -eq "-task") {
# Code to be run "detached" here...
Unregister-ScheduledTask -TaskName $NAME_TASK -TaskPath $NAME_TASKPATH -Confirm:$False
Exit
}
$Task = (Get-ScheduledTask -TaskName $NAME_TASK -TaskPath $NAME_TASKPATH -ErrorAction 'SilentlyContinue')
if ($Task) {
Write-Host "ERR: Task already in progress"
Exit 1
}
$A = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-ExecutionPolicy bypass -NoProfile -Command ""$PSCommandPath -task $args"""
Register-ScheduledTask -TaskName $NAME_TASK -TaskPath $NAME_TASKPATH -Action $A | Start-ScheduledTask
The solution is to combine Start-Process with nohup:
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-7.3#example-9-create-a-detached-process-on-linux
(Note: This is NOT for Windows.)
I am running this command
Invoke-WmiMethod -ComputerName $machine -Credential $cred -Impersonation 3 -Path Win32_process -Name create -ArgumentList "powershell.exe -ExecutionPolicy Unrestricted -File C:\Windows_Updates.ps1" -Verbose
The only problem is in the remote machine, it getting created as a background process. When I open the task manager, I am able to see powershell.exe, but I have no way to identify what is going on. I have looked nearly everywhere but unable to find a solution.
Basically I need to execute the powershell file remotely. I am open to using other solutions where I can see the script running.
I dont think that is possible. Try psexec instead
http://blogs.technet.com/b/heyscriptingguy/archive/2005/09/06/how-can-i-remotely-start-an-interactive-process.aspx
sysinternals psexec
http://technet.microsoft.com/en-us/sysinternals/bb897553.aspx