Hsu Amanda
Hsu Amanda

Reputation: 31

the first line output nothing in powershell

i try output parameter value in PowerShell, but it output nothing for the first time.

i have to try multiple times and it always succeeds after the first output. does anyone know the problem?

here is the code test.ps1:

Get-Content D:/Config.txt | Foreach-Object{    
$var = $_.Split('=')    
New-Variable -Name $var[0] -Value $var[1]
}
Write-Host $DeskTopPath -BackgroundColor black 
Write-Host $DeskTopPath -BackgroundColor green 
Write-Host $DeskTopPath -BackgroundColor blue 

Config.txt

DeskTopPath=D:\Users\Test\Desktop

my output


D:\Users\Test\Desktop
D:\Users\Test\Desktop

my PowerShell version: 5.1.14393.3471

Upvotes: 1

Views: 336

Answers (1)

AdminOfThings
AdminOfThings

Reputation: 25001

Write-Host writes to the console immediately. It doesn’t wait for or care about what the pipeline is processing. It is simply executing too fast before your variable is created. You either need to add a sleep or delay or don’t use Write-Host.

Get-Content D:/Config.txt | Foreach-Object{    
$var = $_.Split('=')    
New-Variable -Name $var[0] -Value $var[1]
}
Start-Sleep -m 200
Write-Host $DeskTopPath -BackgroundColor black 
Write-Host $DeskTopPath -BackgroundColor green 
Write-Host $DeskTopPath -BackgroundColor blue 

This isn't reproducible for everyone because of the number of variables involved in running PowerShell code. It will have to be trial and error.

Upvotes: 1

Related Questions