With PowerShell I am trying to take information from a CSV file and execute two commands that are based on two columns of data. The first piece of data is an asset that needs to copy a unique file to a folder and have renamed to config.txt.
The second piece of data is a name for a computer to have the folder that had received the unique file copied to the named computer. For example;
First command:
Copy-Item "c:\folder1\$asset.txt" -Destination "f:\folder2\config.txt"
Second command:
robocopy /e folder2 \\$ComputerName\folder3
The data is imported from a csv file that has two columns, asset and computername. The script is at follows and is one of many variations, none of which has worked including the one below. Any help would be much appreciated.
Computers.csv contains the following
A12345 CN12345
A54321 CN54321
Script:
Import-Csv -Delimiter ',' -Path c:\temp\computers.csv -Header 'Asset','ComputerName’ |
ForEach-Object {
$asset += $_.asset
$ComputerName += $_.NBN
Copy-Item "c:\folder1\$asset.txt" -Destination "f:\folder2\config.txt"
robocopy /e f:\folder2 \\$ComputerName\folder3
}
I have worked on the script and the results are below. The script does what I want except I manually have to change the position of the items in the array. I would like to have this done automatically but haven't figured that part out yet. I expect the csv file to contain 50 or more assets and computer names and don't look forward entering in the positions of each item and running the script 50 times. Is there a way to go through the array automatically?
$computers = Import-Csv -Path c:\temp\computers.csv -Header 'Asset','ComputerName' $asset = $computers[0].asset $ComputerName = $computers[0].ComputerName
ForEach-Object {
Copy-Item "c:\folder1\$asset.txt" -Destination "f:\folder2\config.txt"
robocopy /e /is "f:\folder2\" "\\$ComputerName\c$\folder3"
}
ForEach-Objectloop you need to use$_instead of just$. So to access the "asset" of the current item you would use$_.assetForEach-Object.The problem with your first example, is that you are creating an array, by using$asset += $_.Asset, and then attempting to use the entire contents of the array to build your file path.