Import-csv command piping needs to be done in below code

Hi Everyone,

I am new to powershell, plz help me to merge import-csv command in below script where i can fetch multiple computers instead of one

import-module activedirectory;

$servers = get-adcomputer "Computername" | where {$_.enabled -eq $true};

foreach ($server in $servers) {

if(test-connection -cn $server.name -quiet -count 1) {

write-host "-------------";
write-host $server.name;
write-host "-------------";

$shares = gwmi win32_share -computer $server.name;

foreach ($share in $shares) {

if (($share.name -ne "print$") -and ($share.path -notlike "*LocalsplOnly*") -and ($share.name -notmatch ".\$") -and ($share.name -ne "ipc$") -and ($share.name -ne "sysvol") -and ($share.name -ne "netlogon")-and ($share.name -ne "admin$")) {

$out = $server.name + "," + $share.name + "," + $share.path;
$out >> c:\output.csv
}

}

write-host "";

}
}

 

Please re-post this in General QnA forums. This forum is dedicated for PowerShell DSC.

did you try with outfile and the -append option ?

 

https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/out-file?view=powershell-6

[quote quote=145193]Please re-post this in General QnA forums. This forum is dedicated for PowerShell DSC.

[/quote]

It has been moved.

First, as an FYI, best practice is to not utilize aliases in scripts.
I would suggest using get-wmiobject vs the gwmi alias.

Now to your real question, you are already retrieving multiple computers with your initial get-adcomputer line.
So, I’m going to make an assumption here that what you’re really asking is how to get all of your share reports out to a csv.

change this line:
$out >> c:\output.csv

to
$out |export-csv c:\output.csv -append -notypeinformation

as well, best practice is to not utilize aliases in scripts.
I would suggest using get-wmiobject vs the gwmi alias.

Here is a rewrite of what you have.

Agreed with the ‘Don’t use aliases in production scripts’. They are fine to save typing when doing interactive stuff at the console. You can use aliases in your script, but make sure you expand them before release. There ways to auto expand aliases.

Import-Module -Name ActiveDirectory

Depending on what OS you are on, this is done automatically, so no real to do this.
It does hurt by doing it, but, modules autoload on the system where they are installed. Again, OS and PSVersion withstanding.

No real need to declare variables, for stuff you are just going to pass down the pipeline.
Make use of default variables when / where possible.

$_ and $PSItem is the same thing. Use the information being passed down from the previous command.

No reason for all the semi-colons in PowerShell, except in specific scenarios. Like when you need to put stuff on one line that are distinct command, vs a tire one-liner that uses the pipeline. What you are doing, they are not needed. Though you will see it in many books, samples etc. This is an indication you / others are coming from another language, which is fine, but being new to PowerShell, be sure to spend the time getting ramped up to avoid frustration, confusion, misconceptions, mangling your code, errors, bad habits, etc. See the references to below.

Now on to you script and my suggested refactor.

Get-ADComputer -Filter ‘*’ |
where {$_.enabled -eq $true} |
ForEach {
if(test-connection -ComputerName ($ServerName = ($PSItem.Name)) -Quiet -Count 1)
{
<#

Since you are outputting the computername on the below, why do it here. That is redundant or take it out of the below.

The (‘SomeCharacter’)*number simply means, repeat the quoted string x times

                ('-')*20
                $PSItem.name
                ('-')*20

Use the CIM namespace instead of WMI whenever possible. This is OS dependent.

What is CIM and Why Should I Use It in PowerShell?
https://devblogs.microsoft.com/scripting/what-is-cim-and-why-should-i-use-it-in-powershell

Scripting | Should I use CIM or WMI with Windows PowerShell?
https://devblogs.microsoft.com/scripting/should-i-use-cim-or-wmi-with-windows-powershell

CIM vs. WMI CmdLets – The top reasons I changed over
http://maikkoster.com/cim-vs-wmi-cmdlets-the-top-reasons-i-changed

So, this is about choice, based on where you are in your work / enterprise

                
# gwmi win32_share -computer $server.name
# Get-CimInstance -ClassName

Use the built-in cmdlets for share information and use natural line breaks to make code more readable.

Write-Host, should be avoided, and the there is no real reason to use it, except when using color or specific formatting requirements.

Write-Output is the default, which keeps data available and writes to the screen as well, and you don’t have to specify that.

Depending on what PowerShell version you are on, Write-Host dumps the buffer and thus is not usable on the pipeline.

I’d switch all the -and for a RegEx OR, to keep this simplier.

                Get-SmbShare | 
                foreach {
                    if ($PSItem.Name -notmatch '\w.*\$|sysvol|netlogon')
                    {
                        # Results
                        $PSItem | 
                        Select-Object -Property @{Name = 'ServerName';Expression = {$ServerName}}, Name, Path
                    }
                }

                "`n" # Insert a blank line using the new line character.
            }
} | Format-Table -AutoSize | 
Out-File -FilePath 'C:\Temp\ServerShareReport.csv' -Append

So final - without all the comments

Get-ADComputer -Filter '*' | 
where {$_.enabled -eq $true} | 
ForEach {
            if(test-connection -ComputerName ($ServerName = ($PSItem.Name)) -Quiet -Count 1) 
            {
                Get-SmbShare | 
                foreach {
                    if ($PSItem.Name -notmatch '\w.*\$|sysvol|netlogon')
                    {
                        # Results
                        $PSItem | 
                        Select-Object -Property @{Name = 'ServerName';Expression = {$ServerName}}, Name, Path
                    }
                }

                "`n"
            }
} | Format-Table -AutoSize | 
Out-File -FilePath 'C:\Temp\ServerShareReport.csv' -Append

Again, just another way of looking at this. Many will have different takes on style, form, etc.

# Learning Resources

https://social.technet.microsoft.com/wiki/contents/articles/183.windows-powershell-survival-guide.aspx
https://www.reddit.com/r/PowerShell/comments/ar6cvt/powershell_in_depth_second_edition/egmlpom/?context=3
https://www.reddit.com/r/PowerShell/comments/aw8cvk/course_to_increase_knowledge_of_windows
https://www.reddit.com/r/PowerShell/comments/ax83qg/how_to_learn_powershell
https://www.reddit.com/r/PowerShell/comments/ar6cvt/powershell_in_depth_second_edition/egmlpom/?context=3