Powershell: Capture process id of a background job - powershell

I want to start a background job and capture it's process id into a .pid file. I was able to do it with the Start-Process as follows:
Start-Process C:\process.bat -passthru | foreach { $_.Id } > start.pid
Now, I want to wrap Start-Process with Start-Job, to run it in the background, like this:
$command = "Start-Process C:\process.bat -passthru | foreach { $_.Id }"
$scriptblock = [Scriptblock]::Create($command)
Start-Job -ScriptBlock $scriptblock
Unfortunatelly, this doesn't work and Receive-Job gives me the following error:
The term '.Id' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
+ CategoryInfo : ObjectNotFound: (.Id:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
+ PSComputerName : localhost
Looks like it's something wrong with the $_ variable. Maybe it gets overwritten by the Start-Job.
Any clues greatly welcome!

That is because the variable is being expanded when using double quotes. If you want to keep the $_, then you need to use single quotes.
$command = 'Start-Process C:\process.bat -passthru | foreach { $_.Id }'
$scriptblock = [Scriptblock]::Create($command)
Start-Job -ScriptBlock $scriptblock

Related

Unable to pass argument in invoke powershell script

I am trying to pass value for argument in below command script called install.ps1. I execute it by ./install.ps1 HD1
invoke-command -Session $session -ScriptBlock {G:\usr\sap\$($args[0])\hdbclient\hdbuserstore.exe list}
but it gave an error to me that
The term 'G:\usr\sap\$($args[0])\hdbclient\hdbuserstore.exe' is not
recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
+ CategoryInfo : ObjectNotFound: (G:\usr\sap\$($a...dbuserstore.exe:String) [],
CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
+ PSComputerName : hostname
You are not using the -Argumentlist parameter on Invoke-Command. Let me show an example below. Use the Param method inside the scriptblock if you want to use custom variable names.
$Directory = "HD1"
$Scriptblock = {
param($Var1)
G:\usr\sap\$Var1\hdbclient\hdbuserstore.exe list
}
invoke-command -Session $session -ScriptBlock $Scriptblock -ArgumentList $Directory

How run a command in PowerShell from a specified directory and wait for it to complete before moving on?

I have a script that works to run an executable and wait until done in PS but I need to modify it to use a path defined in a variable earlier in the script.
Working:
$job = Start-Job `
-InitializationScript { Set-Location C:\MyDirectory\ } `
-ScriptBlock { C:\MyDirectory\MyCmdLineExecutable.exe }
Wait-Job $job
Receive-Job $job
Not working:
$Path = "C:\MyDirectory\"
$ExePath = $path+"MyCmdLineExecutable.exe"
$job = Start-Job `
-InitializationScript { Set-Location $Path } `
-ScriptBlock { $ExePath }
Wait-Job $job
Receive-Job $job
Here's the error:
Set-Location : Cannot process argument because the value of argument "path" is null. Change the value of argument "path" to a non-null value.
At line:1 char:2
+ Set-Location $Path
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Location], PSArgumentNullException
+ FullyQualifiedErrorId : ArgumentNull,Microsoft.PowerShell.Commands.SetLocationCommand
Id Name PSJobTypeName State HasMoreData Location Command
-- ---- ------------- ----- ----------- -------- -------
49 Job49 BackgroundJob Failed False localhost $ExePath
Running startup script threw an error: Cannot process argument because the value of argument "path" is null. Change the value of argument "path" to a non-null value..
+ CategoryInfo : OpenError: (localhost:String) [], RemoteException
+ FullyQualifiedErrorId : PSSessionStateBroken
Combining info from Start-Job docs with About_Scopes article, I am certain of that you need to use -InputObject parameter:
Specifies input to the command. Enter a variable that contains the
objects, or type a command or expression that generates the
objects. In the value of the ScriptBlock parameter, use the
$Input automatic variable to represent the input objects.
$Path = "C:\MyDirectory\"
$ExePath = $path+"MyCmdLineExecutable.exe"
$job = Start-Job -InputObject #( $Path, $ExePath) `
-InitializationScript { <# $Input variable isn't defined here #> } `
-ScriptBlock {
$aux = $Input.GetEnumerator()
Set-Location $aux[0]
& $aux[1] }
Wait-Job $job
Receive-Job $job
BTW, to run commands that are stored in variables and represented by strings, use & Call operator. See the difference:
$ExePath ### output only
& $ExePath ### invocation
I think you want Start-Process with the -Wait parameter. You can also specify the -WorkingDirectory parameter to specify the working directory for the new process. Example:
Start-Process notepad -WorkingDirectory "C:\Program Files" -Wait
Write-Host "Finished"
When you run this script, Notepad will open but the script won't continue until it closes. When you close Notepad, the Write-Host line runs.

Property is empty when run through Invoke-Command

I am trying to individually monitor memory usage of a process (w3wp.exe) that has multiple instances of itself by filtering out a string found in the process' CommandLine property.
It works when I run this script locally:
$proc = (WmiObject Win32_Process -Filter "Name = 'w3wp.exe'" | Where-Object {$_.CommandLine -like "*SomeTextFromCl*"})
$id = $proc.ProcessId
$ws = [math]::round((Get-Process -Id $id).WS/1MB)
Write-Host $ws
However, when I try to run it remotely through Invoke-Command, I get an error telling that the Id property's value is null:
Cannot bind argument to parameter 'Id' because it is null.
+ CategoryInfo : InvalidData: (:) [Get-Process], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetProcessCommand
+ PSComputerName : RemoteServerName
My Invoke-Command syntax is:
Invoke-Command -ComputerName RemoteServerName -FilePath script.ps1 -Credential $mycredential
I'm sure it's simple but I'm back to PS after a long absence and I had a look around but couldn't find anything really helpful.
You are writing the answer to the console. You use the ps1 as a function, so you should use:
return $ws
instead of
write-host $ws

Start-job resulting in null parameter

I'm trying to execute the following two lines of code in PowerShell v2.0 as a job, and am having trouble. I think I have the syntax right, but I can't get it to do what I think it should do, so I clearly am doing something wrong...
$report = <command line thing>
invoke-expression $report
These two lines work in PowerShell. But when I try to put it into a start-job command:
start-job -scriptblock {invoke-expression $report} -argumentlist $report | wait-job | receive-job
I get the following error:
Cannot bind argument to parameter 'Command' because it is null.
+ CategoryInfo : InvalidData: (:) [Invoke-Expression], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.InvokeExpre
ssionCommand
+ PSComputerName : localhost
I understand that error as saying that the argument I'm passing the invoke-expression is null, but, I'd thought that by passing $report in the -argumentlist param, it'd get through?
You cannot access $report directly unless you do:
-scriptblock {param($report) invoke-expression $report}
The param($report) part captures the $report variable passed in via -ArgumentList and makes it available for use inside the scriptblock.

PowerShell: Starting process with variable parsed from Get-Process

I am currently writing a PowerShell script to stop a few processes, start a program, and then restart those processes. The problem arises when I feed the processes into an array variable to restart them later.
My code:
$direc = "C:\Program Files (x86)\PathTo\Program.exe";
$arguments = "/theseArguments1", "/theseArguments2";
$processesDefined = #();
$processes = "notepad", "explorer";
ForEach ($i in $processes)
{
$processesDefined += get-process -name $i | select-object path;
get-process -name $i | stop-process -force;
}
start-process -filepath $direc -ArgumentList $arguments -NoNewWindow -wait;
ForEach ($i in $processesDefined)
{
start-process -filepath $i;
}
When debugging the $processesDefined.Count displays 2 and the $processesDefined displays as expected yet when it gets to tjhe time to start the processes I get:
Start-Process : This command cannot be executed due to the error: The system ca
nnot find the file specified.
At D:\Desktop\Aion.ps1:17 char:18
+ start-process <<<< -FilePath $i;
+ CategoryInfo : InvalidOperation: (:) [Start-Process], InvalidOp
erationException
+ FullyQualifiedErrorId : InvalidOperationException,Microsoft.PowerShell.C
ommands.StartProcessCommand
I've done a lot of searching but can't find anything of real help. Any help with this would be greatly appreciated. Thank you.
Output of $processesDefined:
[DBG]: PS D:\Desktop>>> $processesDefined
Path
----
C:\Program Files\Windows Media Player\wmpnetwk.exe
C:\Windows\explorer.exe
_____________________________________________________________
Try doing it this way. The way you are doing it leaves the variable $processesDefined with a table heading (PATH) and this will screw things up.
$processesDefined += (get-process -name $i).Path
This way will just give you the path with no table heading