我正在努力学习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,因为它是只读的或常量。在行:7字符:1+$pid=1+~~~~~~~~+CategoryInfo:WriteError:(PID:String)[],SessionStateUnauthorizedAccessException+FullyQualifiedErrorId:VariableNotWritable无法覆盖变量PID,因为它是只读或常量。第11行字符:1+$pid=$process.ID+~~~~~~~~~~~~~~~~~~+CategoryInfo:WriteError:(PID:String)[],SessionStateUnauthorizedAccessException+FullyQualifiedErrorId:VariableNotWritable启动作业:无法覆盖变量pid,因为它是只读或常量。在线:12字符:5+启动作业-ScriptBlock$cmd-ArgumentList$pid
我在这里做错了什么?
$PID
是一个保留的自动变量,包含会话的进程id。你不能设置它。
参见:
Get-Help about_Automatic_Variables
以获取自动变量的完整列表和描述。
编辑:
输出所有记事本进程的进程ID:
Get-Process -Name notepad |
Select -ExpandProperty ID