从存储在变量中的命令输出中删除空行

时间:2016-10-04 12:33:04

标签: powershell

我的变量输出可能有100行。这就是它的出现方式:

VOLUME #28
 drive letter        = I:
 dev_name            = \Device\HarddiskVolume8
 guid_name           = \\?\Volume{35596739-d159-11e4-80c1-0050569cf1fd}
 size                = 5117 MB.
 disk tag            = 0x000000304f65e304.
 descriptor          = \\.\Volume{35596739-d159-11e4-80c1-0050569cf1fd}

 **** ERROR: DATA NOT AVAILABLE [0x00000100] ****

VOLUME #28
 drive letter        = B:
 dev_name            = \Device\HarddiskVolume63
 guid_name           = \\?\Volume{3bf4ee0a-d050-11e4-80be-0050569cf1fd}
 size                = 81917 MB.
 disk tag            = 0x000000304f65e304.
 descriptor          = \\.\Volume{3bf4ee0a-d050-11e4-80be-0050569cf1fd}

 **** ERROR: DATA NOT AVAILABLE [0x00000100] ****

这就是我想要的样子:

VOLUME #29
 drive letter        = I:
 dev_name            = \Device\HarddiskVolume8
 guid_name           = \\?\Volume{35596739-d159-11e4-80c1-0050569cf1fd}
 size                = 5117 MB.
 disk tag            = 0x000000304f65e304.
 descriptor          = \\.\Volume{35596739-d159-11e4-80c1-0050569cf1fd}
 **** ERROR: DATA NOT AVAILABLE [0x00000100] ****
VOLUME #28
 drive letter        = B:
 dev_name            = \Device\HarddiskVolume63
 guid_name           = \\?\Volume{3bf4ee0a-d050-11e4-80be-0050569cf1fd}
 size                = 81917 MB.
 disk tag            = 0x000000304f65e304.
 descriptor          = \\.\Volume{3bf4ee0a-d050-11e4-80be-0050569cf1fd}
 **** ERROR: DATA NOT AVAILABLE [0x00000100] ****

我正在检查是否有办法删除变量中的空白行。谢谢!

2 个答案:

答案 0 :(得分:2)

你可以用正则表达式来做到这一点:

(?m)^\s*?\n

(?m)设置多行标志,^断言行开头的位置,\s*?匹配零和无限次(非贪婪)和{{1}之间的任何空格字符匹配换行符。

示例:

\n

<强>输出:

$myVar = 
@'
VOLUME #28
 drive letter        = I:
 dev_name            = \Device\HarddiskVolume8
 guid_name           = \\?\Volume{35596739-d159-11e4-80c1-0050569cf1fd}
 size                = 5117 MB.
 disk tag            = 0x000000304f65e304.
 descriptor          = \\.\Volume{35596739-d159-11e4-80c1-0050569cf1fd}

 **** ERROR: DATA NOT AVAILABLE [0x00000100] ****

VOLUME #28
 drive letter        = B:
 dev_name            = \Device\HarddiskVolume63
 guid_name           = \\?\Volume{3bf4ee0a-d050-11e4-80be-0050569cf1fd}
 size                = 81917 MB.
 disk tag            = 0x000000304f65e304.
 descriptor          = \\.\Volume{3bf4ee0a-d050-11e4-80be-0050569cf1fd}

 **** ERROR: DATA NOT AVAILABLE [0x00000100] ****
'@

$myVar -replace '(?m)^\s*?\n'

答案 1 :(得分:0)

您的变量是外部实用程序的输出,因此您可以通过检查其类型来查看它是一个数组$output.GetType()将显示System.Object[]这意味着一个数组。

只需使用数组比较运算符:

$noBlanks = $output -ne ''

或正则表达式也过滤掉只有空格和制表符的行:

$noBlanks = $output -notmatch '^\s*$'