PowerShell 变量未传递给 Invoke-Command

PowerShell 变量未传递给 Invoke-Command

我正在编写一个小脚本,以便我的团队更新页面文件的最小/最大大小,并将页面文件放在系统驱动器以外的驱动器上。如果我在服务器上使用静态值运行此脚本,它会正常工作;

$ComputerSystem = Get-WmiObject -ClassName Win32_ComputerSystem
$ComputerSystem.AutomaticManagedPagefile = $false
$ComputerSystem.Put()

#Remove all pagefiles
$pf = Get-WmiObject -ClassName Win32_PageFileSetting
$pf.delete()

#Do the work
Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{name="P:\pagefile.sys";InitialSize = 0; MaximumSize = 0} -EnableAllPrivileges
$SetPF = Get-WmiObject -ClassName Win32_PageFileSetting | where{$_.caption -like 'P:*'}
$SetPF.InitialSize = 16
$SetPF.MaximumSize = 12288
$SetPF.Put()

因此,我使用 Invoke 命令创建了一个针对远程系统运行的脚本。当我运行 Invoke 时,所需的驱动器号会传递到 cmd 中,并将页面文件放在该驱动器上。但是当它达到指定最小/最大大小的点时,它就会崩溃。这是脚本;

#Get Page File Size and Path
    $MinSize= Read-Host "Enter minimum size in MB"
    $MaxSize = Read-Host "Enter maximum size in MB"
    $GetDrive = Read-Host "What drive do you want the Page File to exist"
    $PagePath = $GetDrive + ":\pagefile.sys"


#Do the work
    Invoke-Command -ComputerName $PFServer -ScriptBlock{Set-WmiInstance -Class Win32_PageFileSetting -Arguments @{name= $using:PagePath;InitialSize = 0; MaximumSize = 0} -EnableAllPrivileges; 
    $SetPF = Get-WmiObject -ClassName Win32_PageFileSetting | where{$_.caption -like $Using:GetDrive};
    $SetPF.InitialSize = $Using:MinSize;
    $SetPF.MaximumSize = $Using:MaxSize;
    $SetPF.Put()}

错误如下:

The property 'InitialSize' cannot be found on this object. Verify that the property exists and can be set.
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFound
    + PSComputerName        : Server01

The property 'MaximumSize' cannot be found on this object. Verify that the property exists and can be set.
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : PropertyNotFound
    + PSComputerName        : Server01

You cannot call a method on a null-valued expression.
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull
    + PSComputerName        : Server01

我有点困惑。我尝试了无数种方法来实现这一点,但至今没有成功。有人有什么想法吗?

答案1

它说的$SetPF是空白,所以请检查Get-WmiObject命令是否真的返回了任何内容。您还可以像这样测试:

Invoke-Command -ComputerName $PFServer -ScriptBlock {
  "using these values remotely:", $using:MinSize, $using:MaxSize, $using:GetDrive

  $SetPF = Get-WmiObject -ClassName Win32_PageFileSetting | where{$_.caption -like $Using:GetDrive}
  "current settings are:", $SetPF
}

Win32_PageFileSetting在页面文件仍由操作系统管理的系统上为空白。仔细检查是否Set-WmiInstance实际成功创建了一个页面文件,或者检查是否(gwmi Win32_ComputerSystem).AutomaticManagedPagefile仍然返回True

相关内容