在提升的 PowerShell 控制台中运行以下命令即可创建虚拟驱动器。
New-VHD -Path c:\vm_vol\Base.vhdx -SizeBytes 10GB
但是,在非提升权限的 shell 中运行以下命令:
runas /user:$env:userdomain\$env:username "New-VHD -Path c:\vm_vol\Base.vhdx -SizeBytes 10GB"
提示输入密码,并尝试运行命令:
Enter the password for dom1\user1:
Attempting to start New-VHD -Path c:\vm_vol\Base.vhdx -SizeBytes 10GB as user "dom1\user1" ...
但随后出现错误:
RUNAS ERROR: Unable to run - New-VHD -Path c:\vm_vol\Base.vhdx -SizeBytes 10GB
2: The system cannot find the file specified.
我怎样才能使这个命令在非提升权限的 shell 中运行?
答案1
作为宠物食品建议,使用runas /user:$env:userdomain\$env:username "powershell -NoExit", "Get-VM"
就可以了。
然而,我采取了以下措施,以便从长远来看让事情变得不那么冗长。
在提升的 PowerShell 会话中执行命令的函数。
psudo.ps1
:
function psudo ([string]$cmd = "echo Hello!") {
Start-Process -FilePath "powershell" -Verb RunAs -ArgumentList "-NoExit", $cmd
}
if ($args[0] -eq $null) {
$cmd = "echo 'please provide powershell command to execute in elevated shell as a quoted string'"
} else {
$cmd = $args[0]
}
psudo $cmd
psudo
从非提升权限的 shell运行:
psudo "echo 'This is a test using psudo'"
导致升高的控制台保持打开状态:
This is a test using psudo
运行psudo
执行 PowerShell cmdlet Get-VM
,需要提升权限:
psudo Get-VM
导致升高的控制台保持打开状态:
Name State CPUUsage(%) MemoryAssigned(M) Uptime Status Version
---- ----- ----------- ----------------- ------ ------ -------
test_vm Off 0 0 00:00:00 Operating normally 9.0
我真的希望我可以让它工作,Invoke-Command
这样我就可以在同一个控制台中看到结果,而不必每次以管理员身份运行命令时都打开一个单独的窗口。
但是,我无法让任何与以下类似的版本运行:
获取并存储凭证
脚本文件getcreds.ps1
保存在我的用户文件夹的一个目录中,该目录也在我的$env:PATH
变量中。这样,我只需要输入一次密码,并且每次出于安全策略需要更改密码时也只需要输入一次。
getcreds.ps1
:
function getcurcreds {
$pwd = Get-Content "$HOME\ExportedPassword.txt" | ConvertTo-SecureString
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList "$env:USERDOMAIN\$env:username", $pwd
Add-Type -AssemblyName System.DirectoryServices.AccountManagement -ErrorAction Stop
$Domain = $env:USERDOMAIN
$ct = [System.DirectoryServices.AccountManagement.ContextType]::Domain
$pc = New-Object System.DirectoryServices.AccountManagement.PrincipalContext $ct, $Domain
$validated = $pc.ValidateCredentials($cred.UserName, $cred.GetNetworkCredential().password)
if (-Not $validated) {
$cred = Get-Credential -UserName "$env:USERDOMAIN\$env:username" -Message "WK NA password"
Set-Content "$HOME\ExportedPassword.txt" ($cred.Password | ConvertFrom-SecureString)
}
$cred
}
getcurcreds
函数修改为在提升的 PowerShell 会话中执行命令并将结果返回到当前未提升的 PowerShell 会话。
psudo.ps1
:
$cred = getcreds
function psudo ([string]$cmd = "echo Hello!") {
$cmdBlk = [scriptblock]::Create(
"Start-Process -FilePath 'powershell' -Verb RunAs -ArgumentList '-NoExit', $cmd"
)
Invoke-Command -ComputerName $env:computername $cmdBlk -RunAsAdministrator -Credential $cred
}
我不断收到如下错误:
Invoke-Command : Parameter set cannot be resolved using the specified named parameters.
或者
cmdlet Invoke-Command at command pipeline position 1
Supply values for the following parameters:
ContainerId[0]: