Home > Net >  Scope on Powershell Variables
Scope on Powershell Variables

Time:02-22

Objective:

Es to be able to visualize the modification of my [w32timeStatus] variable at the level of the 2nd Write-output.

But my variable always keeps its initial value.

I tried:

To use the [$Global:w32timeStatus] and [$Scriptw32timeStatus] scope but I can't find where the error is.


    function setW32time{
      
      $Script:w32timeStatus = (Get-Service -Name w32time).Status;
    
      if("$w32timeStatus" -eq "Stopped"){
    
          # Demarre le service de temps windows,
          Write-Output "[Start]::Windows time is: $w32timeStatus and will be Start..."
          net start w32time
          Write-Output "[End]::Windows time is: $Script:w32timeStatus"
          Write-Output "[End]::Windows time is: $w32timeStatus"
      }
    }
    setW32time

Outputed:

[Sart]::Windows time is: Stopped

[End]::Windows time is: Stopped

[End]::Windows time is: Stopped

I would like to get:

[Sart]::Windows time is: Stopped

[End]::Windows time is: Running

[End]::Windows time is: Running

CodePudding user response:

Try using Start-Service instead, the status of the service object doesn't get updated by net start.

function setW32time {
[cmdletbinding()]
param()

    $service = Get-Service -Name w32time
    if($service.Status -eq "Stopped") {
        try { 
            "[Start]::Windows time is: $($service.Status)"
            Start-Service $service
            "[End]::Windows time is: $($service.Status)"
        }
        catch {
            $PSCmdlet.WriteError($_)
        }
    }
}

setW32time

If you want to use net start instead, you could call the .Refresh() method for the object. For example:

$service = Get-Service -Name w32time
net start w32time
$service.Status # => 'Stopped'
$service.Refresh()
$service.Status # => 'Running'
  • Related