下面是 PowerShell
check_disk_space.ps1
用于获取远程 Windows 服务器驱动器信息,但我收到错误:
param ( [string]$passdrives,
[string]$connuser,
[string]$connpass,
[int]$minFreeSpaceGB
)
$myconnuser = '$connuser'
$mypassword = '$connpass' | ConvertTo-SecureString -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $myconnuser, $mypassword
$disks = Get-WmiObject -ComputerName remotehost1 -Credential $credential -Class Win32_LogicalDisk -Filter "DriveType = 3";
输出:
powershell.exe -File .\check_disk_space.ps1 -passdrives "C" -minFreeSpaceGB "30" -connuser "remuser" -connpass "passxxx"
Get-WmiObject : Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
At D:\Git-Runners\s10\_work\poc\check_disk_space.ps1:38 char:11
+ ... $disks = Get-WmiObject -ComputerName remotehost1 -Credential $credenti ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-WmiObject], UnauthorizedAccessException
+ FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
命令错误如上。
但是,如果我从
-Credential $credential
中删除 Get-WmiObject
并以与 command prompt
不同的用户身份运行 remuser
,则相同的 check_disk_space.ps1
会成功运行!!
我尝试了以下方法,但也没有帮助:
启用远程 WMI 访问:在远程主机上,您可能需要为远程用户启用和配置 WMI 访问。为此,请按照下列步骤操作:
Open "Control Panel" -> "Administrative Tools" -> "Computer Management."
In the left pane, expand "Services and Applications" and select "WMI Control."
Right-click on "WMI Control" and select "Properties."
Go to the "Security" tab and set the necessary permissions for the user specified in $connuser.
我更倾向于使用更新的 powershell 代码的解决方案,而不是其他解决方案。
我想了解如何通过将
-Credential $credential
传递给 Get-WmiObject
来成功执行 PowerShell 脚本以获取驱动器详细信息。
您在脚本中使用
$myconnuser = '$connuser'
,这...实际上会将字符串 '$connuser
' 分配给变量 $myconnuser
,因为 PowerShell 中的单引号不会扩展变量。
您应该使用
$myconnuser = $connuser
来代替。mypassword
脚本将是:
param ( [string]$passdrives,
[string]$connuser,
[string]$connpass,
[int]$minFreeSpaceGB
)
$myconnuser = $connuser
$mypassword = ConvertTo-SecureString -AsPlainText -Force -String $connpass
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $myconnuser, $mypassword
$disks = Get-WmiObject -ComputerName remotehost1 -Credential $credential -Class Win32_LogicalDisk -Filter "DriveType = 3"