csvpowershellvariablesnew-item

Error calling New-Item in a loop from CSV data


Before we get to the code, I have a CSV with a list of PC's and only 1 column. The goal is to use the info from Column A, labeled "Computers" and get all services for these machines and output them into folders created based on the info from Column A. Here is the script so far:

Import-Module activedirectory
$Group=import-csv C:\Users\axb3055\Documents\CSV_Test.csv 
$ServiceList = Test-Path C:\ServiceList
if($ServiceList -eq $true)
{Write-Host "Service List Exists"}
else
{
Write-Host "Creating ServiceList folder"
New-Item C:\ServiceList\$CompName -ItemType directory -ErrorActionSilentlyContinue | Out-Null
}
$Group | foreach {$CompName = $_.Computers New-Item -Path C:\ServiceList\$CompName -ItemType directory | Get-Service -ComputerName  $_.Computers} | Out-File C:\ServiceList\$CompName\$CompName.txt

What is happening now is that the Service List folder is created but nothing happens after that. I get an error point to the "New-Item" in the for-each block but I am not sure what it could be. Any ideas?


Solution

  • I would begin troubleshooting by breaking up your piping statements. Print out values throughout the sequence to see if you have null values and tweak accordingly.

    Import-Module activedirectory
        $Group=import-csv C:\Users\axb3055\Documents\CSV_Test.csv 
        $ServiceList = Test-Path C:\ServiceList
        if($ServiceList -eq $true)
        {
        Write-Host "Service List Exists"
        }
        else
        {
        Write-Host "Creating ServiceList folder"
        New-Item C:\ServiceList\$CompName -ItemType directory -ErrorActionSilentlyContinue | Out-Null
        }
    
        foreach ($CompName in $Group.Computers){
         #create file
         New-Item -Path C:\ServiceList\$CompName -ItemType directory 
         #get service and assign to variable
         $service = Get-Service -ComputerName $CompName
         #output the service content to the textfile
         Out-File C:\ServiceList\$CompName\$CompName.txt -value $service        
        }