如何将ArrayList传递给远程机器执行的PowerShell Invoke-Command命令
问题根因
Invoke-Command的脚本块运行在远程机器的独立执行上下文里,默认无法直接访问本地定义的变量,你虽然通过ArgumentList传递了参数,但没有在脚本块内显式接收,脚本块内部的$ListOfUserProfiles是远程上下文新生成的空变量,自然返回count为0。
额外存在的问题
- 路径拼接语法错误,
"C:\Users\"$UserProfile"\AppData...的写法不符合PowerShell解析规则,会触发执行错误 - 函数内部的
$machine变量如果是外部定义的,存在作用域访问失效的风险 - 如果你本地定义的
WriteLog函数没有同步到远程机器,远程执行时会直接报错
修正后代码
$ListOfUserProfiles = GetMachineUserProfiles $ListOfUserProfiles.count Function Delete-Chrome-Temp-Files { # 显式声明函数入参,避免全局变量作用域问题 param($machine, $userProfiles) WriteLog "--------------------------------`n" WriteLog "COMMAND: Delete Chrome temporary files" $diskSpaceBeforeC = Disk-Free-Space $userProfiles.count Invoke-Command -ComputerName $machine -ArgumentList (,$userProfiles) -ScriptBlock { # 显式接收ArgumentList传递的参数 param($ListOfUserProfiles) $ListOfUserProfiles.count foreach ($UserProfile in $ListOfUserProfiles){ Write-Host $UserProfile # 用Join-Path拼接路径避免语法错误 $targetPath = Join-Path "C:\Users\$UserProfile\AppData\Local\Google\Chrome\User Data" Get-ChildItem -Path $targetPath -Filter "*.tmp" -Recurse -ErrorAction SilentlyContinue | foreach { Remove-Item -Path $_.FullName -Force # 将日志输出回传到本地处理 Write-Output "INFO: Deleting $($_.FullName)" } } } | ForEach-Object { # 调用本地WriteLog写日志 WriteLog $_ } } # 调用函数时传入对应参数 Delete-Chrome-Temp-Files -machine $machine -userProfiles $ListOfUserProfiles
内容的提问来源于stack exchange,提问作者punky
相关产品推荐
相关产品推荐

