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

标签 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
}

我收到以下错误:

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

我在这里做错了什么?

最佳答案

$PID 是一个 reserved, automatic variable包含 session 的进程 ID。你不能设置它。

参见:

Get-Help about_Automatic_Variables 

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

编辑:

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

 Get-Process -Name notepad |
   Select -ExpandProperty ID 

关于windows - 无法覆盖变量,因为它是只读的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29307941/

相关文章:

windows - 远程 OpenSCManager 失败,访问被拒绝

windows - 批处理文件(*.bat)中的创建文件命令

windows - 如何在 Windows 中找到删除/移动给定文件的进程

windows - 启动 PowerShell session 时出错

windows - 如何在后台运行 .exe,使用 perl PAR 的 pp 模块从 perl 脚本创建

Windows:什么编程语言?

web-applications - 在 64 位 : missing targets file 上从命令行使用 MSBuild 构建 Web 应用程序项目

azure - 在 PowerShell 中将字符串表达式转换为日期类型

json - 使用 Powershell 将文件内容转换为可以使用 JSON 传输的字符串

Powershell WMIC 数据文件查询无效?