无法覆盖变量,因为它是只读的

时间:2015-03-27 18:40:17

标签: windows powershell

我正在努力学习Powershell。我有以下脚本:

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

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

我收到以下错误:

  

无法覆盖变量PID,因为它是只读的或常量的。在   line:7 char:1   + $ pid = 1   + ~~~~~~~~       + CategoryInfo:WriteError:(PID:String)[],SessionStateUnauthorizedAccessException       + FullyQualifiedErrorId:VariableNotWritable无法覆盖变量PID,因为它是只读或常量。在行:11 char:1   + $ pid = $ process.ID   + ~~~~~~~~~~~~~~~~~~       + CategoryInfo:WriteError:(PID:String)[],SessionStateUnauthorizedAccessException       + FullyQualifiedErrorId:VariableNotWritable Start-Job:无法覆盖变量pid,因为它是只读或常量。在线:12   焦炭:5   + Start-Job -ScriptBlock $ cmd -ArgumentList $ pid

我在这里做错了什么?

1 个答案:

答案 0 :(得分:8)

$PIDreserved, automatic variable,其中包含会话的进程ID。你不能设置它。

请参阅:

Get-Help about_Automatic_Variables 

有关自动变量的完整列表和说明。

编辑:

输出所有记事本进程的进程ID:

 Get-Process -Name notepad |
   Select -ExpandProperty ID 
相关问题