简体   繁体   中英

PowerShell passing arguments to Invoke-Command in a foreach loop

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).

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   
        }
    }}

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   
    }
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM