I think I'm doing ForEach wrong

Hello everyone! I could use a little help with a script I'm trying to set up, I think I'm doing my ForEach loop incorrectly, but Powershell doesn't spit out any errors so I'm not sure where to start looking.

I've got two things we want to do, working from the same CSV file:

  1. Take the list of Users, and change their password to the one specified in the CSV file.

  2. Take a list of computers, and run a remote command to change a registry key, using the password from the CSV file.

The CSV file itself is set up something like this (generic info):

ComputersUsersPassword
Computer1User1Password1
Computer2User2Password2

For the first task, here's the script we've built so far:

https://pastebin.com/i12kjRWq

For the second task (change registry key that stores the auto-login password), here's the script so far:

https://pastebin.com/wbKs2JSe

For both scripts, when they are run (in powershell as normal "admin", or as "domain admin") they just output the table from the CSV file, no error messages.

I suspect that I am doing forgetting something stupid in my ForEach loop, but I'm not quite sure what, it looks (to me) just like any other ForEach example I've seen.

For the second task, I'm starting to suspect that I might need to pass the variables ($Computer and $Password) to the "Remote Command" as an Argument? I'm not quite sure to accomplish that.

ANY ideas or direction is appreciated here!

Posted Apr 5, 2017, 3:54 PM UTC

1923
omers•

For each loops are foreach (<item> in <array>) you're calling arrays that don't exist:

Import-CSV C:\Temp\Test.csv
ForEach ($Computer in $ComputerName){

}

needs to be:

$CSV = Import-CSV C:\Temp\Test.csv
ForEach ($Computer in $CSV){

}

or something like that.

8
motsanciens•

Yes, and OP--to expand on this, if you want to make your CSV in Excel, for instance, your column headers will be your properties. Example, columns are Size, Weight, Height, Color, and you import that such as $dogs = import-csv c:\doglist.csv. As you iterate through each dog in your list using the foreach loop (e.g. foreach($dog in $dogs), you'd reference the $dog.size, $dog.weight, etc.

4
TerminalProtocolOP•

Awesome. I think i understand what I was missing before. I was assuming that i just Import-CSV, and that Powershell for the rest of that "instance" would just refer back to it whenever I reference a variable.

So theoretically, I could bring in two CSV files, like this:

$CSV1 = Import-CSV C:\Temp\Test1.CSV

$CSV2 = Import-CSV C:\Temp\Test2.CSV

And then refer back to them each, pulling the Computer and Password from different sheets like this:

Invoke-Command -ComputerName $Computer.CSV1 -ScriptBlock {reg add "hklm\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultPassword /t REG_SZ /d $Password.CSV2 /f}

Are you allowed to pull info from two sheets like that, or am I getting this wrong?

1
Jaymzkerten•

You have your variables and properties mixed up. $CSV1/$CSV2 are the variables, and .Computer/.Password are properties of those respective variables. It would actually read as $CSV1.Computer and $CSV2.Password if you were to go that route.

In the case of what you are doing, it makes more sense to have 1 CSV file as you have 1 for 1 mapping of computer-user-password, whereas if you split them apart you need a way to tell the script what entry in $CSV1 matches up to a partner entry in $CSV2.

With the foreach loop you are essentially telling the script to iterate through each entry of your $CSV variable and run whatever set of commands for each entry of that variable. Ideally, assuming your CSV has column headers for ComputerName and Password your loop should look like this:

$CSV = Import-Csv C:\temp\Test.csv
ForEach ($Computer in $CSV){
    Invoke-Command -ComputerName $Computer.ComputerName -ScriptBlock {
        reg add "hklm\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultPassword /t REG_SZ /d $Using:Computer.Password /f
    }
}

Also a little bit more advanced but $Using: is needed any time you are trying to use invoke-command and passing a variable to the remote session, because your variables don't exist on the remote server. $Using: tells it to pass the variable over to the remote session.

3
TerminalProtocolOP•

Hmm, you're right, I had that backwards. It makes sense that you would list it out as $MainThing.SubThing when I think about it.

I'm currently using one CSV file to pull in whatever I need, I just wanted to make sure that you could potentially pull in more than one file. I wasn't sure if pulling in a second file would "replace" the previous one.

As long as you give it a different $Nickname, it should be fine right?

2
Jaymzkerten•

Correct, you can create an infinite number of variables so long as they each have their own unique name.

2
RiPont•

Pro Tip: Whenever you are doing batch processing like this, always, always, always log your progress to a file.

When it invariably breaks partway through due to a random network exception or something, you can look at the progress file to see where to resume from.

$computers = Import-CSV computers.csv -Headers "ComputerName","Column2","Column3"
foreach ($computer in $computers) {
    # do the thing with $computer.ComputerName
    $computer.ComputerName | Out-File -Append computerProgress.txt -Encoding utf8
}

Alternatively, you can try/catch and output the successfully processed ones to "success.txt" and the failed ones to "failed.txt" rather than stopping on failure.

3
SaladProblems•

You can also use -OutVariable and then dump its contents on failure.

1
jheinikel•

Here is the first one. You were running a foreach on nothing and using values below that were not pointing to their sub-item in the CSV. (This assumes the headers on that CSV are Computers,Users,Password)

# Import the CSV File with all the stuff.
$Users = Import-CSV C:\Temp\Test.csv
# Initiate a ForEach Loop.
ForEach ($User in $Users){
    # Invoke the command to actually change passwords.
    # The following will select each account (Users column), and "Reset" the password to the corresponding string in the "Password" column.
    Get-ADUser $User.Users | Set-ADaccountPassword -Reset -NewPassword (ConvertTo-SecureString -AsPlainText $User.Password -Force)
    #If you want to check the "Force User to Change Password on Next Login" box, un-comment the next line.
    # Get-ADUser $User.Users | Set-ADUser -ChangePasswordAtLogon $true
}

Same things applied to the second:

# Import the CSV File with all the stuff.
$Computers = Import-CSV C:\Temp\Test.csv
# Initiate a ForEach loop.
ForEach ($Computer in $Computers){
	# Invoke the command to actually set the registry key.
	$Password = $Computer.Password
	Invoke-Command -ComputerName $Computer.Computers -ScriptBlock {reg add "hklm\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v DefaultPassword /t REG_SZ /d $Password /f}
}
2
TerminalProtocolOP•

Ok, I think i see where I went wrong.

So when I import-CSV, I'm not just telling Powershell "hey bring in this CSV file, and use the contents of it", I need to give it a variable "NickName".

So $Users = Import-CSV C:\Temp\Test.CSV is me telling Powershell "bring in this CSV, and call it $Users"

Then later I refer to the contents as Get-ADUser $ColumnHeader.CSVNickName.

Is this about right, or am I going off-track?

1
eric256•

The colums from the CSV will be attributes of the rows in the $Users variable.

Get-ADUser $User.CSVNickName

Where you get $user in your for each. So each $user would be a row and $Users is all the rows together

Assuming your CSV has a first row that is a header and tells PowerShell what each column is.

3
TerminalProtocolOP•

Alright, it's obvious I need to go back and read up on how Powershell handles variables (and how variables work, in general).

At least I have something that works now, that I can use as a base to build on. And I at least have an idea of what I don't know.

Thanks for your amazing help! You've given me a huge leap forward.

2
eric256•

So lets play with this abit. I'll make a sample CSV file like the following callled test.csv

username, firstname
test, jeb
test2, joe
test3, fred

So we can see I've set the column headings as username and firstname. Lets load that in PowerShell

Import-CSV -path "test.csv" 

Now by default when you have a command that has output and you don't put it in a variable, PowerShell outputs it to the console. In this case we would get:

H:\PowerShell> Import-CSV -path "test.csv"

username firstname
-------- ---------
test     jeb      
test2    joe      
test3    fred    

If you look at the output we can see that it took my headings and put them above the dashed line. This makes them the column headers and means we can get to that data using that name. I can select a column with the Select-Object command, shortened to Select

 H:\PowerShell> Import-CSV -path "test.csv" | Select username

username
--------
test    
test2   
test3   

Now if instead I wanted that table in a variable I would assigned the import to the variable, then i can select on that variable

$users = Import-CSV -path "test.csv" 
$users | Select Username, firstname

output:

username firstname
-------- ---------
test     jeb      
test2    joe      
test3    fred     

So now we have users and it has a table of data in it, with with a username and first name. The select was redundant there, if I had left it off powershell would have just output the table for me.

So now lets play with that variable. We'll use foreach to loop over it.

$users = Import-CSV -path "test.csv" 
foreach ($user in $users)
{
    Write-Output "Processings $user"
}

Output:

Processings @{username=test; firstname=jeb}
Processings @{username=test2; firstname=joe}
Processings @{username=test3; firstname=fred}
        

Now this has a lot of new stuff. First we introduce a new variable called $user and tell powershell to put the row data for each for into the variable $user. That means inside that block we are going to repeat once for each row, and everytime we will put the row data in $user. Then Write-ouput does what we would expect. $user.firstname is a way to access the data in that row based on the column name we want to access.

I also output each row ($user) so that we could see what is in there. We can see that for each row we have a username and a first name. So now lets do something accessing those:

$users = Import-CSV -path "test.csv" 
foreach ($user in $users)
{
    Write-Output "Processings $user"
    Write-Output "Reseting password for user " $user.username
}

Output:

Processings @{username=test; firstname=jeb}
Reseting password for user 
test
Processings @{username=test2; firstname=joe}
Reseting password for user 
test2
Processings @{username=test3; firstname=fred}
Reseting password for user 
test3

See how now I access $user.username and that gives me each users name for each row in the table. It should be pretty straight forward to extrapolate from this to your scripts. PowerShell makes it wierd to learn because a lot of power shell never even uses variables. That script I just wrote could also be

Import-CSV -path "test.csv"  | %{ Write-Output "Processings $_"; Write-Output "Reseting password for user " $_.Username} 

The pipe (|) just means take the out put from that last bit and put it into the next command, and %{ is short hand for "foreach ($_ in data i just recieved)".

I hope this gave you some steps you can go through to understand variables and foreach in PowerShell!

7