Bouncing to specific points in the script

Is there a way to make the script go to a specific location, for example: GOTO on the command line? I wanted to make a jump script at the beginning when it ends.

$tag1 = Read-Host 'Enter tag #' cls sc.exe \\$tag1 start RemoteRegistry cls Start-Sleep -s 2 cls systeminfo /S $tag1 | findstr /B /C:"OS Name" /C:"System Boot Time" /C:"System Up Time"; Get-EventLog system -computername $tag1 -InstanceId 2147489657 -Newest 10 | ft EventID,TimeWritten,MachineName -AutoSize Pause 
+6
source share
3 answers

Here's an example using your script:

 $GetInfo = { $tag1 = Read-Host 'Enter tag # or Q to quit' if ($tag1 -eq 'Q'){Return} cls sc.exe \\$tag1 start RemoteRegistry cls Start-Sleep -s 2 cls systeminfo /S $tag1 | findstr /B /C:"OS Name" /C:"System Boot Time" /C:"System Up Time" Get-EventLog system -computername $tag1 -InstanceId 2147489657 -Newest 10 | ft EventID,TimeWritten,MachineName -AutoSize .$GetInfo } &$GetInfo 

Use. instead of the script block and inside it so that it cannot go up the call stack.

Entering code into script blocks that will be called later from arbitrary points in the script (GoTo emulation) functionally coincides with the use of the function, and the script block used in this way is sometimes called "anonymous functions".

+8
source

There is no goto in PowerShell, and no one misses it :). Just wrap the command block in a loop or something like that.

Or try below. You can assign a list of commands to a variable and then execute them with &$varname . However, that is not all.

 $commands = { Write-Host "do some work" $again = Read-Host "again?" if ($again -eq "y"){ &$commands } else { Write-Host "end" } } &$commands 
+5
source

Another variation on the script with some ideas taken from @mjolinor. I also refused to use systeminfo , because at least on my computer it is much slower than using the corresponding WMI request.

 while (1) { $tag1 = Read-Host 'Enter tag # or Q to quit' if ($tag1 -eq "Q") { break; } sc.exe \\$tag1 start RemoteRegistry; start-sleep -seconds 2 $OSInfo = get-wmiobject -class win32_operatingsystem -computername $tag1; $OSInfo | Format-Table -Property @{Name="OS Name";Expression={$_.Caption}},@{Name="System Boot Time";Expression={$_.ConvertToDateTime($_.LastBootUpTime)}},@{Name="System Uptime (Days)";Expression={[math]::Round((New-TimeSpan -Start $_.converttodatetime($_.LastBootUpTime)|select-object -expandproperty totaldays),2)}} -AutoSize; Get-EventLog system -computername $tag1 -InstanceId 2147489657 -Newest 10 | format-table EventID,TimeWritten,MachineName -AutoSize } 

I'm not sure if WMI needs a remote registry, so you can completely eliminate the sc.exe and sleep . If you do not need it for something else.

+3
source

Source: https://habr.com/ru/post/958873/


All Articles