Cannot overwrite variable because it is readonly

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?

Solutions/Answers:

Solution 1:

$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 

References

Related:  Most elegant way to extract a directory from a zipfile using PowerShell?