0

I am starting to learn Powershell and I have a csv file (pcfile.csv) with two columns:

  • Column one: PC - PC1, PC2, PC3
  • Column two: User - John, Michael, Tracy

I want to use test-path to check if the folder exists:

\\PC1\c$\users\John  
\\PC2\c$\users\Michael
\\PC3\c$\users\Tracy

Here is my code

$PCs = import-csv c:\pcfile.csv | select -ExpandProperty PC

$Users = import-csv c:\pcfile.csv | select -ExpandProperty User

Foreach ($PC in $PCs) {

    $Path = Test-Path "\\$PC\c$\$User"

      If ($Path -eq $True) {Write-Host 'Folder exists'}

      Else {Write-Host 'Folder does not exist'}

}

The problem I have is that I don't know how to put each user from $Users to check the path

1 Answer 1

1

You don't want to treat them as different lists, you just want to reference the different properties.

Sample data for others to be able to assist.

$tempfile = New-TemporaryFile

@'
PC,User
PC1,John
PC2,Michael
PC3,Tracy
'@ | Set-Content $tempfile

You want to import the data just once. Then iterate over each line which is made up of a PC property and a User property.

$csvdata = Import-Csv $tempfile

foreach($entry in $csvdata){

    If(Test-Path "\\$($entry.pc)\c$\$($entry.user)"){
        Write-Host 'Folder exists'
    }
    Else{
        Write-Host 'Folder does not exist'
    }

}

Note that in order to expand the variable and the property inside the path string, we had to enclose it inside of a subexpression $(...). You could also use the format operator.

foreach($entry in $csvdata){

    $userpath = "\\{0}\c$\{1}" -f $entry.pc,$entry.user

    If(Test-Path $userpath){
        Write-Host 'Folder exists'
    }
    Else{
        Write-Host 'Folder does not exist'
    }

}
Sign up to request clarification or add additional context in comments.

5 Comments

Hello, is {0}{1} just the place holder for $entry.pc,$entry.user? Sorry, just not familiar on how they're used, or when they can be used.
Thank you very much Doug for the quick response, so I'm not very clear on the $tempfile part, if I have 100 rows of data, do I need to put all the data in the $tempfile block @' PC1, name1 .... up to PC100, name100 '@
@AbrahamZinala, yes that's right. Have a look here
@mzoom2021, the $tempfile is just test data for the example. You instead may change $csvdata = Import-Csv $tempfile to $csvdata = Import-Csv c:\pcfile.csv
Thanks guys. Yes the point of the temp file was to have an easy way for others to run the code as well. I recommend you provide that in your next question @mzoom2021. For your actual code you will put in your csv file, not some arbitrary sample file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.