I have two files. The first with contains hostnames (Computers.txt) and the second one contains SID (SID.txt). I want to use Get-Content
and foreach
to execute a command on each computer with the corresponding SID to modify registry.
Let's take for example PC 1 (first line Computers.txt with first line SID.txt) and PC 2 (second line Computers.txt with second line 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}
}
Using a
foreach
-loop doesn't give you the current linenumber so it's impossible to get the same line from the SIDs-list. You should use awhile
- orfor
-loop to create an index that increments by one for each run so you know the "current line".There's no
HKEY_USERS:
PSDrive. You need to access it using the Registry-provider, likeRegistry::HKEY_USERS\
Variables in your local scope (ex.
$currentsid
) aren't accessible inside theInvoke-Command
-scriptblock since it's executed on the remote computer. You can pass it in using-ArgumentList $yourlocalvariable
and call it with$args[0]
(or putparam ($sid)
at the beginning of the scriptblock). With PS 3.0+ this is much simpler as you can use the using-scope ($using:currentsid
) in your script.Example:
One-liner:
On a side-note: Using two files with matching line numbers is a bad idea. What if comptuers has more lines than SIDs? You should be using a CSV-file that maps computer and SID. Ex..
input.csv:
This is safer, easier to maintain and you can use it like this: