在PowerShell中将多个参数放入一个变量中

时间:2013-07-12 20:43:29

标签: .net windows powershell

我试图将2个参数传递给调用invoke-command的PowerShell脚本,并且我试图传递多个参数。但是当我这样做时,似乎两个参数都放在一个变量中,我想知道为什么。

以下是两个程序的代码:

POC.ps1:

param($filename, $user)

echo $filename
echo "This"
echo $user

$responseObject = Invoke-Command CAPTESTPK01 -FilePath .\validatePath.ps1  -ArgumentList($filename, $user) -AsJob 




while($responseObject.State -ne "Completed")
{

}

$result = Receive-Job -Id $responseObject.Id -Keep
echo $result

validatPath.ps1:

Param([string] $filename,
      [string] $user)

function ValidatePath( $filename, $user, $fileType = "container" )
{
    Write-Host "This is the file name: $filename"
    echo "This is user: $user"
    $fileExist = $null
    if( -not (test-path $filename -PathType $fileType) )
    {               
        throw "$user, the path $filename does not exist!"

    }
    else
    {
         Write-Host "This is the second part"
         echo $filename found!
    }
     Write-Host "This is the third part"
    return $fileExist
}


try
{

    ValidatePath($filename, $user)
}
catch
{
    $e = $_.Exception
    echo $e
}

这是输出:

C:\Users
This
Blaine
This is the file name: C:\Users Blaine <--- This indicated both arguments are in one variable
This is user: 
This is the second part
This is the third part
C:\Users
Blaine

1 个答案:

答案 0 :(得分:2)

调用时,不应将PowerShell函数的参数放在括号中。它应该是ValidatePath $filename $user。你写的内容导致只用一个参数调用ValidatePath,$ filename是两个值的数组,即文件名和用户。

BTW:在PowerShell中调用.Net方法时,您需要使用括号。 :)