2

I am trying to figure out as why these commands are not running via script. But when I run this manually it's working.

$value = Get-Content c:\info.txt | select-string Id | Foreach-Object { $_.ToString().split(':')[1] -replace '\s','' } 
Write-Host "$value" >> c:\list.txt

I have tried to redirect out using >> but still there is no information gets updated in variable $value

Get-Content c:\info.txt | select-string Id | Foreach-Object { $_.ToString().split(':')[1] -replace '\s','' } >> $value
    Write-Host "$value" >> c:\list.txt
gary
  • 157
  • 1
  • 3
  • 15
  • What is the content of `c:\list.txt`? We can provide you with a better command. What is it you're really trying to do? – Bill_Stewart Sep 29 '17 at 21:48
  • it's just to check that if my information is getting stored in a variable, so I am printing the output in a text file(c:\list.txt). – gary Sep 29 '17 at 21:52

2 Answers2

0

To write content to a file you'll want to use Set-Content or Add-Content. In your case you'll want to use Add-Content as that will append rather than overwrite the data much like the >> stream re-director does. Write-Host should usually be avoided in PowerShell scripts outside of specific cases, more on that here.

$value = Get-Content c:\info.txt | select-string Id | Foreach-Object { $_.ToString().split(':')[1] -replace '\s','' }
Add-Content -Path C:\list.txt -Value $value

The reason Write-Host did not produce any output in the script is because it bypasses sending the object to the PowerShell objectflow engine and instead directly to the console host, which, depending on your scripts execution environment may not be what you expect.

Persistent13
  • 1,522
  • 11
  • 20
0

You cannot redirect Write-Host. You need to remove that. The following example will do what you are asking:

Get-Content "C:\info.txt" | select-string Id | Foreach-Object { $_.ToString().Split(':')[1] -replace '\s','' } >> "C:\List.txt"

...though I'm not sure what the string manipulations are for, since I don't know what the content of C:\Info.txt looks like.

If you simple want the output to be placed into $value rather than being redirected to a file, you would write it like this:

$value = Get-Content "C:\info.txt" | select-string Id | Foreach-Object { $_.ToString().Split(':')[1] -replace '\s','' }
Bill_Stewart
  • 22,916
  • 4
  • 51
  • 62