在 PowerShell (PS) 中删除内存中的对象有几种方法:
1. 手动删除:
- 使用 `Remove-Variable` cmdlet 删除特定变量:
```powershell
Remove-Variable -Name myVariable
```
- 使用 `[System.GC]::Collect()` 手动触发垃圾回收,清理未引用的对象。
2. 使用 `$null` 赋值:
- 将对象赋值为 `$null` 来释放内存:
```powershell
$myObject = New-Object -TypeName System.Object
$myObject = $null
```
3. 使用 `[System.Runtime.InteropServices.Marshal]::ReleaseComObject()`:
- 对于 COM 对象,可以使用此方法手动释放资源:
```powershell
$excel = New-Object -ComObject Excel.Application
[System.Runtime.InteropServices.Marshal]::ReleaseComObject($excel) | Out-Null
```
4. 使用 `[System.GC]::Collect()` 和 `[System.GC]::WaitForPendingFinalizers()`:
- 强制执行垃圾回收,并等待所有 finalizers 完成:
```powershell
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
```
这些方法可以帮助您手动管理 PowerShell 会话中的内存使用情况。对于大型或复杂的对象,建议使用 `Remove-Variable` 和 `[System.GC]::Collect()` 的组合来确保完全释放内存。