【问题标题】:Remote PowerShell, Local Variables, and ForEach远程 PowerShell、局部变量和 ForEach
【发布时间】:2018-01-19 13:19:01
【问题描述】:

我希望使用 PowerShell 和 Invoke-Command 在某些远程服务器上获取特定文件的文件清单。我想收集信息,然后以 CSV 格式导出到特定文件夹。

我有几个局部变量用于日期(附加到文件名)和服务器列表。我知道我需要使用 -ArgumentList 参数来传递局部变量,但是语法让我对所涉及的 ForEach 方面感到困惑(我不是一个有编程头脑的人)。这是我所拥有的:

$FileServerList = "Server01","Server02","Server03"
$DateTime = Get-Date -Format s

ForEach ($FileServer in $FileServerList) { 
        Invoke-Command -ComputerName $FileServer -ScriptBlock { 
            Get-ChildItem -Path "D:\PathtoFile\*" -Recurse -Include "index.html"  | Select-Object Name,DirectoryName,CreationTime,LastWriteTime`
         | Export-Csv -Path C:\Users\Public\Documents\Data_$DateTime.csv -NoTypeInformation -Verbose 
    } 
}

我应该将脚本块本身保存在一个变量中还是另辟蹊径?任何指导表示赞赏。

【问题讨论】:

  • 这个问题更适合Stack Overflow。投票迁移问题。
  • 迁移这个我会 100% 没问题....
  • 您使用Invoke-Command 是有原因的吗?对于远程服务器上的gci,您不一定需要它。

标签: windows powershell


【解决方案1】:

由于Invoke-Command 没有使用单独的凭据调用,我假设当前 Powershell 会话中的用户具有访问服务器的凭据。

对于远程位置,您可以使用 UNC 路径:

$FileServerList = "Server01","Server02","Server03"
$DateTime = Get-Date -Format s

ForEach ($FileServer in $FileServerList) { 
  Get-ChildItem -Path "\\$FileServer\d$\PathtoFile\*" -Recurse -Include "index.html" |
  Select-Object Name,DirectoryName,CreationTime,LastWriteTime |
  Export-Csv -Path \\$FileServer\c$\Users\Public\Documents\Data_$DateTime.csv -NoTypeInformation -Verbose
}

【讨论】:

    猜你喜欢
    • 2021-04-23
    • 1970-01-01
    • 1970-01-01
    • 2019-02-27
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    • 2016-01-11
    相关资源
    最近更新 更多