调用Win32 API, 取得网络文件夹的剩余空间. 用户无需挂载磁盘即可取得结果
$a = Add-Type -memberDefinition @"
[DllImport("Kernel32.dll")]
public static extern bool GetDiskFreeSpaceEx(
string lpDirectoryName,
out long lpFreeBytesAvailable,
out long lpTotalNumberOfBytes,
out long lpTotalNumberOfFreeBytes
);
"@ -passthru -name MyGetDiskFreeSpaceEx
$fba = [int64] 0;
$tnb = [int64] 0;
$nfb = [int64] 0;
$a::GetDiskFreeSpaceEx("//.host/Shared Folders/files", [ref] $fba, [ref] $tnb, [ref] $nfb)
"FreeBytesAvailable: $($x)"
"TotalNumberOfBytes: $($y)"
"TotalNumberOfFreeBytes: $($z)"
------------OLD------------
$a = Add-Type -memberDefinition @"
[DllImport("Kernel32.dll")]
public static extern bool GetDiskFreeSpaceEx(
string lpDirectoryName,
IntPtr lpFreeBytesAvailable,
IntPtr lpTotalNumberOfBytes,
IntPtr lpTotalNumberOfFreeBytes
);
"@ -passthru -name MyGetDiskFreeSpaceEx
$fba = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(20);
$tnb = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(20);
$nfb = [System.Runtime.InteropServices.Marshal]::AllocHGlobal(20);
$a::GetDiskFreeSpaceEx("//.host/Shared Folders/files", $fba, $tnb, $nfb)
$x = [System.Runtime.InteropServices.Marshal]::ReadInt64($fba)
$y = [System.Runtime.InteropServices.Marshal]::ReadInt64($tnb)
$z = [System.Runtime.InteropServices.Marshal]::ReadInt64($nfb)
"FreeBytesAvailable: $($x)"
"TotalNumberOfBytes: $($y)"
"TotalNumberOfFreeBytes: $($z)"
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($fba);
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($tnb);
[System.Runtime.InteropServices.Marshal]::FreeHGlobal($nfb);
使用PowerShell调用Win32 API获取网络文件夹剩余空间
这篇博客介绍了如何通过PowerShell调用Win32 API的GetDiskFreeSpaceEx方法,无须挂载磁盘即可获取网络共享文件夹的自由空间、总字节数和总自由字节数。示例代码展示了两种实现方式:一种使用ref参数,另一种使用IntPtr分配内存并读取。
6063

被折叠的 条评论
为什么被折叠?



