微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 ForEach 语句在多台主机上查询和设置时区

如何解决使用 ForEach 语句在多台主机上查询和设置时区

我正在尝试构建一个 PowerShell 脚本来在多台计算机上设置时区,而我也设置了一个 GPO 来执行此操作,这仅在重新启动后适用。因此,我希望能够快速轻松地推送到多台机器上。

$computers = Get-Content "\\RedactedFilePath.txt"
$TimeZone = "Azerbaijan Standard Time"

Foreach ($computer in $computers)
{
    Write-Host "Setting Time zone on $Computers" -ForegroundColor magenta
    Write-Host "Checking current time zone information" -ForegroundColor Green
    invoke-command -cn $computers {tzutil /g}
    Write-Host "Setting event time zone to $TimeZone" -ForegroundColor Yellow
    invoke-command -cn $computers {tzutil /s “Azerbaijan Standard Time”}
    Write-Host "Checking time zone information post change" -ForegroundColor Green
    invoke-command -cn $computers {tzutil /g}
}

现在,当运行这个工作时,但它运行序列会针对脚本中的计算机数量重复自身,而不是为每台计算机单独运行。有谁知道我如何将它分开,以便它为每台计算机单独运行序列? Script running multiple instances of the same command rather than running them separately TIA,詹姆斯

解决方法

作为评论发布,但为了清楚起见,将其发布为答案。您正在将数组 ($computers) 解析为 -ComputerName 开关。它需要的是 $computer(没有“s”)

$computers = Get-Content "\\RedactedFilePath.txt"
$TimeZone = "Azerbaijan Standard Time"

foreach ($computer in $computers)
{
    Write-Host "Setting Time zone on $computer" -ForegroundColor Magenta
    Write-Host "Checking current time zone information" -ForegroundColor Green
    invoke-command -cn $computer {tzutil /g}
    Write-Host "Setting event time zone to $TimeZone" -ForegroundColor Yellow
    invoke-command -cn $computer {tzutil /s "Azerbaijan Standard Time"}
    Write-Host "Checking time zone information post change" -ForegroundColor Green
    invoke-command -cn $computer {tzutil /g}
}

附注。请记住,虽然 powershell 在字符大小写方面对您来说很容易 - 请记住,在忽略大小写时 PS 是一个例外:)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。