Powershell Write Bitlocker status to text file - shell

I am trying to write the bitlocker status to a text file via powershell by invoking a cmd shell but it doesn't seem to work. Any ideas?
Here is what i have tried so far
#doesn't work
cmd /c manage-bde.txt>c:\bitlockerstatus.txt
# makes an empty file
$oProcess = Start-Process cmd.exe -ArgumentList "manage-bde>c:\bitlockerstatus.txt" -wait -NoNewWindow -PassThru
$oProcess.HasExited
$oProcess.ExitCode
#doesn't work
[Diagnostics.Process]::Start("cmd.exe","/c manage-bde>c:\bitlockerstatus.txt")

why don't you call the exe directly from powershell using the & operator ?
& manage-bde.exe -status > c:\temp\bl.txt

Related

How to keep the PowerShell process alive after closing powershell terminal in windows

I need to run a PowerShell command in windows PowerShell, its running fine as expected. The problem is when I close the Windows PowerShell terminal, it kills the process, whereas I want the process to continue running forever.
Is there a way to close the terminal and have process working in the background.
Here is my command that I need to run:
.\start.ps1 -accountUuid '{XXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXX}' `
-repositoryUuid '{XXXXXX-XXXXX-XXXX-XXXX-XXXXXXXXXX}' `
-runnerUuid '{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXX}' `
-OAuthClientId XXXXXXXXXXXXXXXXX `
-OAuthClientSecret XXXXXXXXXXXXXXXXXXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXX `
-workingDirectory '..\temp'
You can try with the command Start-process with option -NoNewWindow to run the process in the background. Add all your arguments in -ArgumentList.
Start-Process -FilePath ".\start.ps1" -ArgumentList "-accountUuid ...", "-repositoryUuid ..." -NoNewWindow
More info here

Opening another powershell terminal from the current script to execute the current script output

$argList = "-file `"C:\Users\bdl\Desktop\jhansi\PowerShell_Scripts\dialog.ps1`""
Start powershell -argumentlist $argList -NoNewWindow
I am trying to open another powershell terminal from the current script to execute the current script output. Another powershell terminal is opening but it is blinking continuously. The above two lines of code i have written but it is blinking. please tell me where is the mistake in the above two lines.
You can try something like this:
$ArgList = "C:\Users\bdl\Desktop\jhansi\PowerShell_Scripts\dialog.ps1"
Start-Process -FilePath PowerShell -ArgumentList $ArgList -NoNewWindow -Wait
You can also check if the script called in PowerShell returns successfully or not by adding an exit code into it (Exit 0 means it succeed and Exit 1 if it fails) with:
$Exe = (Start-Process -FilePath PowerShell -ArgumentList $ArgList -NoNewWindow -Wait -PassThru).ExitCode
If ($Exe -ne 0)
{
Write-Host "An error has occured while running the script."
}
As the exit code other than 0 means the script didn't finish properly.

Dynamically rename a command prompt window title via Powershell

I have a powershell script which launches a ffmpeg command
$process = Start-Process -FilePath "cmd" -ArgumentList "/c c:\bin\ffmpeg\bin\ffmpeg.exe -rtsp_transport tcp -i........
This spawns a command prompt window.
I would like to rename the title of the command prompt window and be able to do that for every iteration I run of the ffmpeg command.
I have seen how to rename the title of the window directly via the command prompt and how to rename the powershell window title.
I cannot find any information pertaining to powershell being able to dynamically assign a new title to the command prompt window when created.
Any assistance/pointers would be greatly appreciated.
Once you pass your code off to the cmd instance you started it would be up to the running process to update it's title window (without getting into pinvoke/Windows API calls.) If ffmpeg.exe provides you with the current file as it's running then simply use that to set the title. If not, then it's most likely you'd need to adjust your commands to first get the list of files then iterate over those files setting the title and running the ffmpeg command. Here's a small example of letting the commands set the title.
Start-Process -FilePath "cmd" -ArgumentList "/c for /l %a in (1,1,10) do (title %a & cls & timeout 3)"
If you are instead referring to each time you do Start-Process then simply set the title before the other commands.
Start-Process -FilePath "cmd" -ArgumentList "/c title ffmpeg command running & c:\bin\ffmpeg\bin\ffmpeg.exe -rtsp_transport tcp -i........"
The & character instructs CMD to run the first command AND the next command. && says run the first command and only run the second if the first succeeds. || says run first command and if it fails run second.
By the way, unless you use the -Passthru on Start-Process then it is not collecting anything. With the passthru parameter it would collect a System.Diagnostics.Process object. That could be used for tracking, closing, etc.
$host.ui.RawUI.WindowTitle = "Changed Title"
Something like this?

Passing a response file to a process in Powershell

I have a process that would traditionally be run like so (in the command line):
filepath.exe #"respfile.resp"
where respfile.resp is a response file that has command line arguments for the executable.
Running the command like that works as desired in the command prompt.
However I am trying to use a powershell script to run multiple programs. Here is what I have:
if (Test-Path $respPath){
$executionResposne = Start-Process -NoNewWindow -Wait -PassThru -FilePath $bimlcExePath -ArgumentList $respPath
if ($executionResposne.ExitCode -eq 1){
Write-Output "Unable to successfully run the process. Exiting program."
return
}
}
and I am getting the following error message:
Error:: filepath\to\resp\file Data at the root level is invalid.
How can I make this work?
You need to embed the quotes for the interpreter:
-ArgumentList "#`"$respPath`""

Start a detached background process in PowerShell

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.)

Resources