【问题标题】:Could powershell text output be passed to powershell cmdlet可以将 powershell 文本输出传递给 powershell cmdlet
【发布时间】:2016-11-01 09:24:19
【问题描述】:

考虑下一个 powershell 对话框:

> Get-VpnConnection -AllUserConnection

Name                  : VPN-StackoverflowQuestion
ServerAddress         : x.x.x.4
AllUserConnection     : True
Guid                  : {XXX2C9DE-58F0-41E4-XXXX-9809E90DCXXX}
TunnelType            : Pptp
AuthenticationMethod  : {Chap, MsChapv2, Pap}
EncryptionLevel       : Optional
L2tpIPsecAuth         :
UseWinlogonCredential : False
EapConfigXmlStream    :
ConnectionStatus      : Disconnected
RememberCredential    : False
SplitTunneling        : False
DnsSuffix             :
IdleDisconnectSeconds : 0

这样的序列化看起来不错,可读且可编辑。我可以将它保存在一个文本文件(字典)中

Get-VpnConnection > VPN-StackoverflowQuestion.dic

现在我想将此文本文件作为参数传递给Add-VpnConnection。可能吗?

我知道Export-Clixml,它的结果文件不可读、不可编辑且非常麻烦。

【问题讨论】:

  • 嗨,为什么要通过文本文件?为什么不直接将第一个 cmdlet 的输出通过管道传递到下一个?
  • 因为第一次我没有连接。没有什么可复制的。
  • 我在我的答案中写下了如何设置 vpn
  • 当然可以。您只需要一个函数将连接对象转换为 INI 样式格式并将其写入文件,以及另一个函数将信息从平面文件中解析回来。

标签: xml powershell serialization pipe deserialization


【解决方案1】:

是的,使用这个命令:

Get-VpnConnection -AllUserConnection |out-string | out-file "c:\path\filename.txt"

你可以将其解析为返回值。

另一种方式:

 Get-VpnConnection -AllUserConnection |out-string | out-file "c:\path\filename.csv"

然后你可以将它返回到powershell中

检查一下,我这样设置我的 vpn:

$vpn = Get-VpnConnection
$vpn
$splitter = "SpliTtEr" #write custom string that you think unique 
$CustomStructure = $vpn.Name+$splitter+$vpn.ServerAddress+$splitter+$vpn.AllUserConnection+$SpliTtEr+$vpn.Guid ...


$CustomStructure | Out-File C:\path\filename.txt


$getcontent = Get-Content -Path C:\path\filename.txt


$items = $getcontent -split $splitter
Set-VpnConnection -Name $items[0] -ServerAddress $items[1] ...

【讨论】:

  • 你知道如何将它作为 powershell 对象返回吗?
  • @kyb : 你需要字符串吗?
【解决方案2】:

结果是一个对象,导出并保存对象(CliXML,json),当您需要时将导出的文档再次转换为对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    相关资源
    最近更新 更多