如何将文件中一行的最后一个字段追加到powershell cli上的变量?

时间:2018-01-06 00:30:46

标签: powershell powershell-v2.0 powershell-v3.0

这是我的档案hello.txt

  

" ReceiptHandle" =" hellomyfriend == ++"

我想只将一行的最后一个字段附加到变量:

$friend = hellomyfriend==++

1 个答案:

答案 0 :(得分:0)

假设这是hello.txt文件中的所有内容。以下将分配""到你的$ friend变量...

$myhash = (gc 'hello.txt') -replace """","" | ConvertFrom-StringData
$friend = $myhash["ReceiptHandle"]

ConvertFrom-StringData使这很简单,因为你的文字已经在" something = value"格式。

那么这里发生了什么?首先,

  

gc' hello.txt'

获取文件的内容。我将它封装在()中,以便我可以使用..

  

-replace"""",""

..摆脱周围的双引号。它被传送到ConvertFrom-StringData,它将字符串转换为命名的键/值对[hashtable]。从那里,我可以通过询问哈希表来访问第二部分。

或者,你可以把这一切都放在一行......

(gc 'hello.txt') -replace """","" | ConvertFrom-StringData | %{$friend = $_["ReceiptHandle"]}