Skip to content

Instantly share code, notes, and snippets.

@fiddyschmitt
Last active October 14, 2022 00:20
Show Gist options
  • Select an option

  • Save fiddyschmitt/8e3d8954ab1d4b3242edf3e97ea949c1 to your computer and use it in GitHub Desktop.

Select an option

Save fiddyschmitt/8e3d8954ab1d4b3242edf3e97ea949c1 to your computer and use it in GitHub Desktop.
Get list of shares
#$Servers = ( Get-ADComputer -Filter { DNSHostName -Like '*' } | Select -Expand Name )
$Servers = @('server-01', 'server-02')
foreach ($Server in $Servers)
{
(net view $Server /all) | %{
if($_.IndexOf(' Disk ') -gt 0)
{
$shareName = $_.Split(' ')[0]
Write-Host "\\$Server\$shareName"
}
}
}
net view \\server /all
http://www.pinvoke.net/default.aspx/netapi32/netshareenum.html
public class GetNetShares
{
#region External Calls
[DllImport("Netapi32.dll", SetLastError = true)]
static extern int NetApiBufferFree(IntPtr Buffer);
[DllImport("Netapi32.dll", CharSet = CharSet.Unicode)]
private static extern int NetShareEnum(
StringBuilder ServerName,
int level,
ref IntPtr bufPtr,
uint prefmaxlen,
ref int entriesread,
ref int totalentries,
ref int resume_handle
);
#endregion
#region External Structures
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct SHARE_INFO_1
{
public string shi1_netname;
public uint shi1_type;
public string shi1_remark;
public SHARE_INFO_1(string sharename, uint sharetype, string remark)
{
this.shi1_netname = sharename;
this.shi1_type = sharetype;
this.shi1_remark = remark;
}
public override string ToString()
{
return shi1_netname;
}
}
#endregion
const uint MAX_PREFERRED_LENGTH = 0xFFFFFFFF;
const int NERR_Success = 0;
private enum NetError : uint
{
NERR_Success = 0,
NERR_BASE = 2100,
NERR_UnknownDevDir = (NERR_BASE + 16),
NERR_DuplicateShare = (NERR_BASE + 18),
NERR_BufTooSmall = (NERR_BASE + 23),
}
private enum SHARE_TYPE : uint
{
STYPE_DISKTREE = 0,
STYPE_PRINTQ = 1,
STYPE_DEVICE = 2,
STYPE_IPC = 3,
STYPE_SPECIAL = 0x80000000,
}
public SHARE_INFO_1[] EnumNetShares(string Server)
{
List<SHARE_INFO_1> ShareInfos = new List<SHARE_INFO_1>();
int entriesread = 0;
int totalentries = 0;
int resume_handle = 0;
int nStructSize = Marshal.SizeOf(typeof(SHARE_INFO_1));
IntPtr bufPtr = IntPtr.Zero;
StringBuilder server = new StringBuilder(Server);
int ret = NetShareEnum(server, 1, ref bufPtr, MAX_PREFERRED_LENGTH, ref entriesread, ref totalentries, ref resume_handle);
if (ret == NERR_Success)
{
IntPtr currentPtr = bufPtr;
for (int i = 0; i < entriesread; i++)
{
SHARE_INFO_1 shi1 = (SHARE_INFO_1)Marshal.PtrToStructure(currentPtr, typeof(SHARE_INFO_1));
ShareInfos.Add(shi1);
currentPtr += nStructSize;
}
NetApiBufferFree(bufPtr);
return ShareInfos.ToArray();
}
else
{
ShareInfos.Add(new SHARE_INFO_1("ERROR=" + ret.ToString(),10,string.Empty));
return ShareInfos.ToArray();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment