Powershell 传递变量以调用命令,在inlineScript内部,在工作流内部

Powershell 传递变量以调用命令,在inlineScript内部,在工作流内部,powershell,Powershell,我正在尝试创建一个连接到各种服务器的脚本,应该连接一个PSDrive并复制文件。问题在于我无法将变量传递到Invoke命令脚本块 workflow kopijobb { param ([string[]]$serverList, $creds, $basePath) foreach -parallel ($server in $serverList){ # Use the sequence keyword, to ensure everything insid

我正在尝试创建一个连接到各种服务器的脚本,应该连接一个PSDrive并复制文件。问题在于我无法将变量传递到Invoke命令脚本块

workflow kopijobb {
    param ([string[]]$serverList, $creds, $basePath)

    foreach -parallel ($server in $serverList){

        # Use the sequence keyword, to ensure everything inside of it runs in order on each computer.
        sequence {

            #Use the inlinescript keyword to allow PowerShell workflow to run regular PowerShell cmdlets
            inlineScript{

                $path = $using:basePath

                Write-Host "Starting $using:server using $path"
                #Create session for New-PSSession
                $session = New-PSSession -ComputerName $using:server -Credential $using:creds

                # Copy Java and recreate symlink
                Invoke-Command -Session $session -ScriptBlock {

                    # Make a PSDrive, since directly copying from UNC-path doesn't work due to credential-issues
                    New-PSDrive -Name N -PSProvider FileSystem -root $using:path -Credential $using:creds | out-null
我将网络路径传递给$basePath,并且我能够在inlineScript块中读取它,在该块中我尝试将它存储在一个新的变量中进行测试,但是一旦我尝试在new PSDrive命令中访问它,该变量突然变为空/不可访问,驱动器装载失败,错误为无法将参数绑定到参数“Root”,因为该参数为null


我不明白为什么会失败,所以我转而求助于集体智慧。

如果回答我自己的问题感到尴尬,特别是在同一天,但我在工作中遇到了一位PowerShell大师,他看了一眼脚本,发现了问题:

我必须在Invoke命令中添加-Args

            Invoke-Command -Session $session -ScriptBlock {
                param($srv,$login,$path,$...)

                #Make a PSDrive, since directly copying from UNC-path doesn't work due to credential-issues
                New-PSDrive -Name N -PSProvider FileSystem -root $path -Credential $login | out-null
            } -Args $using:server,$using:creds,$using:basePath,$using:...

这当然意味着我必须将所有需要的参数从顶层导入工作流,然后导入Invoke命令。

使用硬编码路径是否有效?是的,问题是,$using:creds变量成为新PSDrive中的瓶颈。未登录,无法访问驱动器:我担心使用$creds将凭证移交给另一台机器在设计上是行不通的。所以你们完全正确地将用户和pwd分开移交。不要在调用块之外使用$using。它用于在脚本块内从调用机器访问变量。将凭据作为参数传递很好。至于$using,我尝试了各种变体,但我下面的解决方案是我使它工作的唯一方法。一旦我完成了我正在进行的其他项目,我将重新访问此脚本,看看是否可以改进它。您应该能够直接在脚本块中使用$using:scope,而不需要参数列表。是否应该?大概能够不可能!我尝试了各种各样的变化,其他的都没用。就像scriptBlock与它之前的一切都是隔离的。