Cannot overwrite variable because it is readonly

19,435

$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 
Share:
19,435

Related videos on Youtube

paul deter
Author by

paul deter

Updated on June 04, 2022

Comments

  • paul deter
    paul deter almost 2 years

    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?

  • paul deter
    paul deter about 9 years
    Thanks, If I change it to different name, I get following result. I only want the process id. How can I do that? Id Name PSJobTypeName State HasMoreData Location Command -- ---- ------------- ----- ----------- -------- ------- 2 Job2 BackgroundJob Running True localhost ... 4 Job4 BackgroundJob Running True localhost ...
  • mjolinor
    mjolinor about 9 years
    You need to explain what it is your trying to accomplish in the question a little better.
  • paul deter
    paul deter about 9 years
    Just trying to print process id of all running notepad instances while using a function
  • paul deter
    paul deter about 9 years
    hmm, I am not getting PID but that's a different question. I will post it.
  • paul deter
    paul deter about 9 years
    here is the question link: stackoverflow.com/questions/29308385/…