您可能可以通过一些正则表达式来实现所需的结果
兼容 Powershell V1
switch -regex (net share){
'^(\S+)\s+(\w:.+?)(?=\s{2,})' {
New-Object PSObject -Property @{
ShareName = $matches.1
Resource = $matches.2
}
}
}
Powershell 3.0+
switch -regex (net share){
'^(\S+)\s+(\w:.+?)(?=\s{2,})' {
[PSCustomObject]@{
ShareName = $matches.1
Resource = $matches.2
}
}
}
在 powershell 5.1 上,您可以使用ConvertFrom-String
“训练”数据。它可以是真实的样本数据或通用数据。可能需要针对您的特定环境进行一些调整,但这在测试中效果很好。
$template = @'
{Share*:ADMIN$} {Path: C:\Windows} {Note:Remote Admin}
{Share*:Admin} {Path: E:\Admin} {Note:Default share}
{Share*:Apps} {Path: D:\Apps} {Note:test}
'@
net share | Select-Object -Skip 4 | Select-Object -SkipLast 2 |
ConvertFrom-String -TemplateContent $template -OutVariable ShareList
显示的任何输出现在都应该包含在变量中$ShareList
$Sharelist | Get-Member -MemberType NoteProperty
TypeName: System.Management.Automation.PSCustomObject
Name MemberType Definition
---- ---------- ----------
Note NoteProperty string Note=Remote Admin
Path NoteProperty string Path=C:\Windows
Share NoteProperty string Share=ADMIN$
您还可以使用psexec远程获取信息并应用任一建议的解决方案。
switch -regex (.\PsExec.exe -nobanner \\$RemoteComputer cmd "/c net share"){
'^(\S+)\s+(\w:.+?)(?=\s{2,})' {
[PSCustomObject]@{
ShareName = $matches.1
Resource = $matches.2
}
}
}
或者
$template = @'
{Share*:ADMIN$} {Path: C:\Windows} {Note:Remote Admin}
{Share*:Admin} {Path: E:\Admin} {Note:Default share}
{Share*:Apps} {Path: D:\Apps} {Note:Test}
'@
.\PsExec.exe -nobanner \\$RemoteComputer cmd "/c net share" |
Select-Object -Skip 4 | Select-Object -SkipLast 2 |
ConvertFrom-String -TemplateContent $template -OutVariable ShareList