开发者

Why tee’d variables aren’t visible in later scripblocks?

开发者 https://www.devze.com 2022-12-21 02:35 出处:网络
Someone knows for which strange reason Powershell doesn\'t show de \'tee\'d\' variable in the following snippet?

Someone knows for which strange reason Powershell doesn't show de 'tee'd' variable in the following snippet?

# a.txt contains any text 
cat a.txt | tee -variable foovar | % { 'value of foovar: ' + $foovar } 

In practice, I'd like to do, in only one line, a 开发者_如何学Pythonsearch for some text and then, based on the results, process the text, for example send a mail with it:

get-content [somefile] | select-string [somePattern] | tee [var] | ..[more processing] | .\sendmail.ps1 [var] 


Since all output that was passed into Tee-Object has to be available in the variable the cmdlet caches its input and writes it to the variable at the end.

But you can just as well do the following:

$var = gc a.txt
$var | your_processing_stuff


You might use -OutVariable as well

cat c:\dev\NamingConventions.txt -OutVariable test1 | % { write-host 'value: ' $_ }
$test1
cat c:\dev\NamingConventions.txt | select-string -patt panel -OutVariable test2
$test2


It looks like tee works in your script, but not the way you are expecting. It does indeed send the whole array to $foovar, but you can't use it until the next line. It looks like that's the nature of tee. You can see that it works this way by running your script two times in a row. On the second run $foovar has the entire contents of a.txt.

It looks like you want each line of the file set to foovar, not the whole array (unless I'm mistaken). If that's the case when you send everything to a foreach loop you are setting it to the special $_ var anyway... i.e.

cat a.txt |%{'value of line: ' $_}

The above will work with select-string too.

0

精彩评论

暂无评论...
验证码 换一张
取 消