【问题标题】:Get-Content and foreach in two files两个文件中的 Get-Content 和 foreach
【发布时间】:2016-04-17 03:03:16
【问题描述】:

我有两个文件。第一个包含主机名 (Computers.txt),第二个包含 SID (SID.txt)。我想使用Get-Contentforeach在每台具有相应SID的计算机上执行一个命令来修改注册表。

我们以 PC 1(第一行 Computers.txt 和第一行 SID.txt)和 PC 2(第二行 Computers.txt 和第二行 SID.txt)为例。

$Computer = Get-Content D:\Downloads\computers.txt
$SID = Get-Content D:\Downloads\SID.txt
foreach ($pc in $Computer)
{
    Invoke-Command -ComputerName $pc {New-Item HKEY_USERS:\$SID -Name -Vaue}
}

【问题讨论】:

    标签: powershell powershell-remoting


    【解决方案1】:
    • 使用foreach-loop 不会为您提供当前行号,因此不可能从 SID 列表中获取同一行。您应该使用while- 或for-循环来创建一个索引,每次运行都会增加一,这样您就可以知道“当前行”。

    • 没有HKEY_USERS: PSDrive。您需要使用 Registry-provider 访问它,例如 Registry::HKEY_USERS\

    • Invoke-Command-scriptblock 中无法访问本地范围内的变量(例如$currentsid),因为它是在远程计算机上执行的。您可以使用-ArgumentList $yourlocalvariable 传递它并使用$args[0] 调用它(或将param ($sid) 放在脚本块的开头)。使用 PS 3.0+,这要简单得多,因为您可以在脚本中使用 using-scope ($using:currentsid)。

    例子:

    $Computers = Get-Content D:\Downloads\computers.txt
    $SIDs = Get-Content D:\Downloads\SID.txt
    
    #Runs one time for each value in computers and sets a variable $i to the current index (linenumer-1 since arrays start at index 0)
    for($i=0; $i -lt $Computers.Length; $i++) {
        #Get computer on line i
        $currentpc = $Computers[$i]
        #Get sid on line i
        $currentsid = $SIDs[$i]
    
        #Invoke remote command and pass in currentsid
        Invoke-Command -ComputerName $currentpc -ScriptBlock { param($sid) New-Item "REGISTRY::HKEY_USERS\$sid" -Name "SomeKeyName" } -ArgumentList $curentsid
    
        #PS3.0+ with using-scope:
        #Invoke-Command -ComputerName $currentpc -ScriptBlock { New-Item "REGISTRY::HKEY_USERS\$using:currentsid" -Name "SomeKeyName" }
    }
    

    单线:

    0..($Computers.Length-1) | ForEach-Object { Invoke-Command -ComputerName $Computers[$_] -ScriptBlock { param($sid) New-Item REGISTRY::HKEY_USERS\$sid -Name "SomeKeyName" } -ArgumentList $SIDs[$_] }
    

    附带说明:使用具有匹配行号的两个文件是一个坏主意。如果计算机的行数多于 SID 怎么办?您应该使用映射计算机和 SID 的 CSV 文件。例如..

    输入.csv:

    Computer,SID
    PC1,S-1-5-21-123123-123213
    PC2,S-1-5-21-123123-123214
    PC3,S-1-5-21-123123-123215
    

    这样更安全,更易于维护,您可以这样使用它:

    Import-Csv input.csv | ForEach-Object { 
        Invoke-Command -ComputerName $_.Computer -ScriptBlock { param($sid) New-Item REGISTRY::HKEY_USERS\$sid -Name "SomeKeyName" } -ArgumentList $_.SID
    }
    

    【讨论】:

    • 太棒了。请记住使用答案左侧的复选标记标记所选答案,以便关闭问题。 :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2019-09-08
    • 2020-05-22
    相关资源
    最近更新 更多