Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot overwrite variable because it is readonly

I am trying to learn Powershell. I have the following script:

$cmd = {
  param($pid)
  Write-Host $pid
}

$processes = Get-Process -Name notepad
foreach ($process in $processes) 
{ 
    $pid = $process.ID
    Start-Job -ScriptBlock $cmd -ArgumentList $pid
}

I'm getting the following error:

Cannot overwrite variable PID because it is read-only or constant. At line:7 char:1 + $pid = 1 + ~~~~~~~~ + CategoryInfo : WriteError: (PID:String) [], SessionStateUnauthorizedAccessException + FullyQualifiedErrorId : VariableNotWritable Cannot overwrite variable PID because it is read-only or constant. At line:11 char:1 + $pid = $process.ID + ~~~~~~~~~~~~~~~~~~ + CategoryInfo : WriteError: (PID:String) [], SessionStateUnauthorizedAccessException + FullyQualifiedErrorId : VariableNotWritable Start-Job : Cannot overwrite variable pid because it is read-only or constant. At line:12 char:5 + Start-Job -ScriptBlock $cmd -ArgumentList $pid

What am I doing wrong here?

like image 876
paul deter Avatar asked Mar 27 '15 18:03

paul deter


1 Answers

$PID is a reserved, automatic variable that contains the process id of your session. You cannot set it.

See:

Get-Help about_Automatic_Variables 

for a complete list and description of the automatic variables.

Edit:

To output the process ID's of all the Notepad processes:

 Get-Process -Name notepad |
   Select -ExpandProperty ID 
like image 54
mjolinor Avatar answered Nov 02 '22 11:11

mjolinor