无法将脚本块中填充的变量传递给powershell中脚本块之外的函数

问题描述 投票:0回答:2

尝试将日期从远程计算机传递到我的 PS 脚本中的函数。但只是给我垃圾。从阅读中我发现您不能在外部使用在脚本块内部声明和启动的变量。不知道如何从这些电脑获取日期。尝试使用“$using”和“$script”,但这不起作用。 get-date 工作正常,直接调用到屏幕

    #Fucntion to manipulate the data
Function writeToServer
{
  param($server,$Time)

  # Data preparation for loading data into SQL table 
  $InsertResults = @"
  INSERT INTO [ServerTimeSync].[dbo].[ServerTimes](SystemName,ShownTimeOnServer)
  VALUES ('$SERVER','$Time')
  "@      
  #call the invoke-sqlcmdlet to execute the query
     Invoke-sqlcmd @params -Query $InsertResults
 }



  foreach ($COMPUTER in $COMPUTERS){ 
  icm $COMPUTER -ScriptBlock {$ENV:COMPUTERNAME

    $computer 
    get-date -Format "MM-dd-yyyy hh:mm:ss tt"

    $script:sdate = get-date -Format "MM-dd-yyyy hh:mm:ss tt"                        
    } 
      writeToServer $computer $script:sdate      
}
powershell powershell-remoting
2个回答
2
投票
  • 您只能通过$using:范围

    将变量的
    传递给远程命令。

  • 从远程命令报告值的唯一方法是让它产生输出,您可以在调用方的变量中捕获它或在管道中进行处理。

您还可以通过使用并行处理来简化命令:

Invoke-Computer -ComputerName $COMPUTERS -ScriptBlock {
  Get-Date -Format "MM-dd-yyyy hh:mm:ss tt"
} | 
  ForEach-Object {
    writeToServer $_.PSComputerName $_      
  }

注:

  • 如果将多个计算机名称传递给

    Invoke-Command
    -ComputerName
    参数,处理会并行进行,但不能保证输出的顺序与传递名称的顺序相匹配。

  • ForEach-Object
    调用用于处理从远程调用接收到的每个对象,您可以通过自动
    $_
    变量
    来引用脚本块内的对象。

  • PowerShell 自动使用反映调用上下文的 ETS(扩展类型系统)属性来装饰远程脚本块的所有输出对象;值得注意的是,

    .PSComputerName
    包含远程计算机的名称。


0
投票

这就是正确使用 $using: 的方式

$MyString = 'Test 123'
Invoke-Command . -ScriptBlock {Write-Output $MyString} # produces no output because $MyString is empty
Invoke-Command . -ScriptBlock {Write-Output $using:MyString} # produces correct output because $MyString contains the string

远程会话的输出可以捕获如下

$MyString = 'Test 123'
$Capture = Invoke-Command . -ScriptBlock {Write-Output $using:MyString}
Write-Host $Capture
© www.soinside.com 2019 - 2024. All rights reserved.