Cannot overwrite variable because it is readonly
$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
Related videos on Youtube
paul deter
Updated on June 04, 2022Comments
-
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 about 9 yearsThanks, 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 about 9 yearsYou need to explain what it is your trying to accomplish in the question a little better.
-
paul deter about 9 yearsJust trying to print process id of all running notepad instances while using a function
-
paul deter about 9 yearshmm, I am not getting PID but that's a different question. I will post it.
-
paul deter about 9 yearshere is the question link: stackoverflow.com/questions/29308385/…