PowerShell 在 foreach 循环中将参数传递给 Invoke-Command [英] PowerShell passing arguments to Invoke-Command in a foreach loop
问题描述
为什么在我已经输入了 $PW
变量的密码并使用它创建了正确的 PSCredentials 之后,PowerShell 会要求我提供访问远程计算机的凭据?我遇到的另一个问题是 Start-Process 找不到指定的 FilePath(空或空).
Why does PowerShell asks me for Credentials to access a remotecomputer, after I already put in the password for my $PW
variable and created the correct PSCredentials with it? The other Issue I have is that Start-Process can't find the FilePath specified (Null or empty).
我猜这两个错误是因为同一个错误,一定是因为我的变量值没有传递给 foreach 循环.如您所见,我试图通过尝试 -argumentlist
参数来实现解决方案,但它不起作用.我做错了什么?
I guess those two errors are because of the same error, it has to be because my Variable-Values aren't passed to the foreach loop. As you can see, I tried to achieve a solution by trying the -argumentlist
parameter, but it doesn't work. What Am I doing wrong?
function Install-Exe {
param(
[string[]]$ComputerName,
[string]$UNCexepath,
[string[]]$exeargs
)
$Admin = "domain\admin"
$PW = Read-Host "Enter Password" -AsSecureString
$cred = New-Object System.Management.Automation.PSCredential -argumentlist $Admin, $PW
foreach ($c in $ComputerName) {
Invoke-Command -ComputerName $c -Credential $cred -ArgumentList $cred,$UNCexepath {
Start-Process -Filepath $UNCexepath -Credential $cred -Verb RunAs
}
}}
推荐答案
您需要在 Invoke-Command
脚本块中声明参数:
You need to declare the parameters inside the Invoke-Command
scriptblock:
foreach ($c in $ComputerName) {
Invoke-Command -ComputerName $c -Credential $cred -ArgumentList $cred,$UNCexepath {
param($cred,$UNCexepath)
Start-Process -Filepath $UNCexepath -Credential $cred -Verb RunAs
}
}}
这篇关于PowerShell 在 foreach 循环中将参数传递给 Invoke-Command的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!