Tuesday, March 20, 2018

Powershell Get File Shares Into Array


I am trying to get a list of folders shared on a file server, and put them into an array. This is the code I have at the moment:


$FileServer = "ServerName"
[array]$FileServerShares = gwmi win32_Share -ComputerName $FileServer |
Where-Object {$_.type -eq '0'} |
Where {$_.name -notlike "*$*"}
Write-Host $FileServerShares

This outputs the folders that are shared (excluding the $ shares too), but the output puts them all into one long variable on one line.


How do I put this into an array with each record on a new line?


Update:


For those that are interested, I used the accepted answer and it worked great. I was actually after the "Name" instance of each folder, and so used code like this:


$FileServer = "ServerName"
$FileServerSharesFullName = gwmi win32_Share -ComputerName $FileServer |
Where-Object {$_.type -eq '0'} |
Where {$_.name -notlike "*$*"} # This excludes the "dollar shares" from being selected
$FileServerShares = $FileServerSharesFullName.name | % {$_.ToString()}

So each name of the folders that are shared in now in an array in $FileServerShares.


Answer



$FileServerShares already is an array (even without the [array] specifier):


PS> $FileServerShares.getType()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True True Object[] System.Array

For some reason, when an array of share objects is converted to a string, each share is put on the same line. I don't know why that is, but what you could do is convert the share objects to strings so that you have an array of strings. String arrays do get converted to multiline strings.


$FileServer = "ServerName"
$FileServerShares = gwmi win32_Share -ComputerName $FileServer |
Where-Object {$_.type -eq '0'} |
Where {$_.name -notlike "*$*"} |
% { $_.ToString() }
Write-Host $FileServerShares

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...