powershell snapin no output, non error
-
I try to run the script as snapin
# Create text file containing firmware settings bcdedit /enum firmware > c:\temp\firmware.txt # Find the line containing "IPV4", and read the line just before that $FullLine = (( Get-Content c:\temp\firmware.txt | Select-String "IPV4" -Context 1 ).context.precontext)[0] # Delete our temporary file #del firmware.txt # Split line into fields using the first left-curly as the delimiter, # and then grab the second field (and restore the first left-curly) $GUID = '{' + $FullLine.split('{')[1] # Set the boot order #bcdedit /set {fwbootmgr} displayorder $GUID {bootmgr} cmd /c bcdedit /set "{fwbootmgr}" displayorder $GUID /addfirst # SIG # Begin signature block # MIIECAYJKoZIhvcNAQcCoIID+TCCA/UCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB # gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
But I get no c:\temp\firmware.txt file
I think the script is not executedHere is the command line viewed on the fog console:
powershell.exe -ExecutionPolicy RemoteSigned -NoProfile -File boot-uefi.ps1I get this log
------------------------------------------------------------------------------ 31/03/2023 16:08:35 Client-Info Client Version: 0.11.19 31/03/2023 16:08:35 Client-Info Client OS: Windows 31/03/2023 16:08:35 Client-Info Server Version: 1.5.8 31/03/2023 16:08:35 Middleware::Response Success 31/03/2023 16:08:35 SnapinClient Running snapin boot-uefi-pxe-first 31/03/2023 16:08:35 Middleware::Communication Download: http://148.60.x.x//fog/service/snapins.file.php?mac=B8:85:84:AC:89:FA&taskid=5453 31/03/2023 16:08:36 SnapinClient C:\Program Files (x86)\FOG\tmp\boot-uefi.ps1 31/03/2023 16:08:36 Bus Emmiting message on channel: Notification 31/03/2023 16:08:36 SnapinClient Starting snapin 31/03/2023 16:08:40 SnapinClient Snapin finished 31/03/2023 16:08:40 SnapinClient Return Code: 0 31/03/2023 16:08:40 Bus Emmiting message on channel: Notification 31/03/2023 16:08:40 Middleware::Communication URL: https://fogus/fog/service/snapins.checkin.php?taskid=5453&exitcode=0&mac=B8:85:84:AC:89:FA&newServ
Any idea ?
-
When I run the command
C:\> powershell.exe -ExecutionPolicy RemoteSigned -NoProfile -File boot-uefi.ps1
I get :
L'opération a réussi.
-
@lebrun78 said in powershell snapin no output, non error:
L’opération a réussi.
Maybe try it without the text file? And without calling cmd? But for being sure it did something we can try adding a more verbose log file
$firmware = (bcdedit /enum firmware) $fullLine = (($firmware | Select-String "IPV4" -Context 1 ).context.precontext)[0] $GUID = '{' + $FullLine.split('{')[1] $result = (bcdedit /set "{fwbootmgr}" displayorder $GUID /addfirst) #make c:\temp if it doesn't exist if (!(Test-Path 'C:\temp')) { mkdir 'C:\temp' } #log everything in a new C:\temp\firmware.txt file New-Item -path C:\temp\firmware.txt -itemType File -value "Firmware: $($firmware | out-string)`n`nFullLine: $fullLine`nGUID: $GUID`nresult: $result`n" -force
-
@JJ-Fullmer
Thank you for your proposition
I now have the file with the title of each item, but the values are empty I modified by adding the date, just to have a trace$firmware = (bcdedit /enum firmware) $fullLine = (($firmware | Select-String "IPV4" -Context 1 ).context.precontext)[0] $GUID = '{'bcdedit /set "{fwbootmgr}" displayorder $GUID /addfirst) $datetime = (date).ToString() if (!(Test-Path 'C:\temp')) { mkdir 'C:\temp' } #log everything in a new C:\temp\firmware.txt file New-Item -path C:\temp\firmware.txt -itemType File -value "Firmware: $($firmware | out-string)`n`nFullLine: $fullLine`nGUID: $GUID`nresult: $result`ndate: $datetime`n" -force
I get
Firmware: FullLine: GUID: result: date: 03/04/2023 09:35:36
I tried adding cmd /c > it’s the same
-
@JJ-Fullmer
Running your script step by step works, I don’t understand why it doesn’t work by snapin.
Is it possible to test a script by the system account used by fog service? -
@lebrun78 Well that’s odd for sure.
You can use psexec top open up a system user shell. The tool may be flagged by your anti-virus software because it can give system user access, but it’s made by microsoft for this type of scenario. It’s a portable exe, no install needed.Once you have psexec
# open up a command prompt as system user path\to\psexec.exe -i -s cmd.exe # this will open a cmd in a new window # in the new window, enter powershell powershell #confirm you are the system account WhoAmI #this should display: nt authority\system
From there you can run the script and see what happens.
I can’t imagine
bcdedit
can’t be used by the system user. When I run the commands as the system user it appears to be working as expected.There could be some other weirdness with one of 2 things:
- 32 vs 64 bit version of powershell (you can specify a different path to powershell in your snapin definition, the default is
C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe
but there’s also a version atC:\windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe
- You could need to use start-process to call the bcdedit tool and specify the full path but that makes it more difficult to get the output into a variable, but not impossible, i.e.
$bcdedit = "C:\windows\System32\bcdedit.exe" $firmware = & {start-process -filepath $bcdedit -args "/enum firmware" -Wait -RedirectStandardOutput output.txt ; get-content output.txt; remove-item output.txt} $fullLine = (($firmware | Select-String "IPV4" -Context 1 ).context.precontext)[0] $GUID = '{' + $FullLine.split('{')[1] $result = & {start-process $bcdedit -args "/set `"{fwbootmgr}`" displayorder $GUID /addfirst" -Wait -RedirectStandardOutput output.txt ; get-content output.txt; remove-item output.txt} #make c:\temp if it doesn't exist if (!(Test-Path 'C:\temp')) { mkdir 'C:\temp' } #log everything in a new C:\temp\firmware.txt file New-Item -path C:\temp\firmware.txt -itemType File -value "Firmware: $($firmware | out-string)`n`nFullLine: $fullLine`nGUID: $GUID`nresult: $result`ndate: $datetime`n" -force
- 32 vs 64 bit version of powershell (you can specify a different path to powershell in your snapin definition, the default is
-
@JJ-Fullmer
I tried command line step by step with psexec, it works
I tried command line step by step with your modified script, it works
I tried snapin withSnapin Command read-only: C:\windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy bypass -NoProfile -File boot-uefi-pxe_win.ps1
and with boot-uefi-pxe_win.ps1
$bcdedit = "C:\windows\System32\bcdedit.exe" $firmware = & {start-process -filepath $bcdedit -args "/enum firmware" -Wait -RedirectStandardOutput output.txt ; get-content output.txt; remove-item output.txt} $fullLine = (($firmware | Select-String "IPV4" -Context 1 ).context.precontext)[0] $GUID = '{' + $FullLine.split('{')[1] $result = & {start-process $bcdedit -args "/set `"{fwbootmgr}`" displayorder $GUID /addfirst" -Wait -RedirectStandardOutput output.txt ; get-content output.txt; remove-item output.txt} # $firmware = $(bcdedit /enum firmware) # $fullLine = (($firmware | Select-String "IPV4" -Context 1 ).context.precontext)[0] # $GUID = '{' + $FullLine.split('{')[1] # $result = $(cmd /c bcdedit /set "{fwbootmgr}" displayorder $GUID /addfirst) $dateheure = (date).ToString() if (!(Test-Path 'C:\temp')) { mkdir 'C:\temp' } #log everything in a new C:\temp\firmware.txt file New-Item -path C:\temp\firmware.txt -itemType File -value "Firmware: $($firmware | out-string)`n`nFullLine: $fullLine`nGUID: $GUID`nresult: $result`ndate: $dateheure`n" -force
And the result is allways
Get-Content C:\temp\firmware.txt Firmware: FullLine: GUID: result: date: 03/04/2023 17:30:13
My OS is Windows 11
-
@lebrun78 I don’t have a windows 11 host to test with. Maybe there’s some new security feature in windows 11 related to bcdedit and background services even running as the system account. It doesn’t make a lot of sense.
Here’s another idea, it’s a bit crazy and will only work as part of firstlogoncommands after imaging (assuming you’re using sysprep with a firstlogoconcommands and auto logon of the admin user). This is when attached snapins will start applying anyway.
This script will essentially create a scheduled task that runs on demand as the built-in administrator named ‘administrator’ interactively. So it will open the powershell window in the logged in session in admin context, this only works with the built-in administrator in my experience and hopefully it still works in windows 11.
$adminUsr = "$($ENV:ComputerName)\Administrator" # create the scheduled task $trigger = New-ScheduledTaskTrigger -AtLogOn -User $adminUsr; $settings = New-ScheduledTaskSettingsSet -WakeToRun -Priority 0; $principal = New-ScheduledTaskPrincipal -UserId $adminUsr -RunLevel Highest -LogonType Interactive; $sb = { $firmware = (bcdedit /enum firmware); $fullLine = (($firmware | Select-String "IPV4" -Context 1 ).context.precontext)[0]; $GUID = '{' + $FullLine.split('{')[1]; $result = (bcdedit /set "{fwbootmgr}" displayorder $GUID /addfirst); #make c:\temp if it doesn't exist if (!(Test-Path 'C:\temp')) { mkdir 'C:\temp'; } #log everything in a new C:\temp\firmware.txt file New-Item -path C:\temp\firmware.txt -itemType File -value "Firmware: $($firmware | out-string)`n`nFullLine: $fullLine`nGUID: $GUID`nresult: $result`n" -force; } New-Item C:\netboot.ps1 -value $sb.tostring() -force; $action = New-ScheduledTaskAction -Execute powershell.exe -Argument "-File 'C:\netboot.ps1'" $task = New-ScheduledTask -Action $action -Description "update bcd" -Principal $principal -Trigger $trigger -Settings $settings; $taskName = "boot-to-net" Register-ScheduledTask -InputObject $task -TaskName $taskName; Start-ScheduledTask -TaskName $taskName; while ((Get-ScheduledTask $taskName).State -eq 'Running') { Start-Sleep -Seconds 1; } Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -EA 0; Remove-Item 'C:\netboot.ps1' -force -ea 0
-
@lebrun78 I just noticed that you’re running the command line step by step in the tests.
The best thing to do would be put a copy of the file atC:\Program Files (x86)\FOG\tmp\boot-uefi.ps1
and run it from there as the system account for a test of the full context of how it will run. You may want to runget-service fogservice | stop-service
first so that the fogservice doesn’t delete the tmp folder while you’re testing. To be fully ideal you should stop the service right after it downloads the script so that the permissions of the file created by the service are fully replicated, but that can be tricky -
@JJ-Fullmer
Thank you for your work, this script runs with snapin but does not do the expected job, the pxe is not ranked àat the good place :$adminUsr = "$($ENV:ComputerName)\Administrateur" $trigger = New-ScheduledTaskTrigger -AtLogOn -User $adminUsr; $settings = New-ScheduledTaskSettingsSet -WakeToRun -Priority 0; $principal = New-ScheduledTaskPrincipal -UserId $adminUsr -RunLevel Highest -LogonType Interactive; $sb = { $firmware = cmd /c "C:\windows\system32\bcdedit.exe" /enum firmware; $fullLine = (($firmware | Select-String "IPV4" -Context 1 ).context.precontext)[0]; $GUID = '{' + $FullLine.split('{')[1]; $result = cmd /c "C:\windows\system32\bcdedit.exe" /set "{fwbootmgr}" displayorder $GUID /addfirst; #make c:\temp if it doesn't exist if (!(Test-Path 'C:\temp')) { mkdir 'C:\temp'; } #log everything in a new C:\temp\firmware.log file New-Item -path C:\temp\firmware.log -itemType File -value "Firmware: $($firmware | out-string)`n`nFullLine: $fullLine`nGUID_ipV4: $GUID`nresult: $result`n" -force; } New-Item C:\netboot.ps1 -value $sb.tostring() -force; $action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-File C:\netboot.ps1" $task = New-ScheduledTask -Action $action -Description "update bcd" -Principal $principal -Trigger $trigger -Settings $settings; $taskName = "boot-to-IPV4"; Register-ScheduledTask -InputObject $task -TaskName $taskName; Start-ScheduledTask -TaskName $taskName; while ((Get-ScheduledTask $taskName).State -eq 'Running') { Start-Sleep -Seconds 1; } Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -EA 0; move-Item 'C:\netboot.ps1' 'C:\netbootOLD.ps1' -force -ea 0;
-
@lebrun78 I could be mistaken here, but I wonder if setting UEFI boot orders and adjusting UEFI parameters aren’t allowed by the system user directly? Since the system user typically doesn’t have a password, I imagine it’d be a bit of an issue if a piece of software elevated itself to the system and injected into your UEFI loader things.
Of course I’m just thinking overly much on the thought here, but it would seem maybe this is intentional?
-
@Tom-Elliott
Yes Tom, I agree,
That’s why JJ-Fullmer create a task executed as user administrator to modify the boot order.
I have a powershell problem, to how to create a task trigger at the creation of the task -
@lebrun78 If the snapin is part of the host, on deploy it should automatically create the snapin task.
The issue, as I’m seeing it, is that the system user is what would run that snapin through the FOG Client. If there’s indeed security to prevent the system user from running the boot order/uefi update process as you’re intending, this is part of the problem.
Again, I’m not certain this is actually the case, just it seems like a potential reason for the issue.
-
@lebrun78 It should still be creating that log file of C:\temp\firmware.log
What does that log say after running this? -
@JJ-Fullmer
No log film created.
Task created as you proposed require administrator login to be executed. That is not the purpose of the snapin.
But I have no idea how to work around the problem@Tom-Elliott
Do you have any idea how to keep pxe boot with eufi Windows ?If I have to get up from my chair every time I have to deploy, that’s no big deal.
-
@lebrun78 As I mentioned that method would only work if the admin is logged in. If you’re running this at deploy time and have other firstlogoncommands that run via an unattend.xml file then it would work when the computer is first imaged to change the boot order back to pxe boot first.
There is a feature request that’s being considered for making it so the fogclient can handle changing the boot order, but no idea when there will be the time for that to be implemented. You’re welcome to fork that repo and give it a go
Personally I made an internal powershell module that queues the image using the FogApi powershell module (see my signature) and runs a remote powershell command on the machine I’m imaging to download the latest ipxe.efi (or snponly.efi) and I set that as the bootfile (I find it hard to match the network boot option as it’s labeled different on different platforms in my environment, but booting directly to the efi boot file always works).
-
@lebrun78 Had another idea.
Since it does work with the system account in the psexec shell you try the scheduled task method again and have it use the system account. It would look something like belowAlso, matching just ‘IPV4’ from the firmware boot options may not yield the most reliable results as not every device will name their network boot option like that. Another option that may work would be finding what your various models do use for pxe identification and script finding that one within this script, that would take some effort to maintain but would always get you the options you want
Another possibility is finding all possible choices and putting them all above the windows boot manager. For example, I have a custom built pc that has 3 options related to network boot (excluding ipv6) options, I could find each of those guids and put them all at the top of the list so each one will be tried at boot. I altered the script below to use that method matching the things I found in a couple places (‘IPV4’, ‘Network’, ‘pxe’) and I switched the matching up using a method I found here https://stackoverflow.com/questions/16903460/bcdedit-bcdstore-and-powershell to parse the enum of firmware into a powershell object, it’s not a perfect conversion to an object but it’s workable.Another other option would be to get the tftpboot pxe files locally and add them to the efi partition and have it try a couple known ones, this method would work nicely as well especially on devices that don’t have built-in ethernet as they won’t have to support pxe boot to get to the bootfile that will get you into fog. But to make that work in a way that would support multiple pxe boot file options is a bit out of scope of this post.
#start the task 10 seconds after its defined $trigger = New-ScheduledTaskTrigger -Once -at ((Get-date).AddSeconds(10)) $settings = New-ScheduledTaskSettingsSet -WakeToRun -Priority 0; #make sure temp path exists, and use temp path to avoid issues with permissions on root of C if (!(Test-Path 'C:\temp')) { mkdir 'C:\temp'; } #use system account $principal = New-ScheduledTaskPrincipal -UserId 'NT AUTHORITY\SYSTEM' -RunLevel Highest -LogonType ServiceAccount; $sb = { $Configs = New-Object -TypeName System.collections.generic.List['System.Object'] $NameArray = @() $Pattern = '^(?<name>[a-z]*)?\s*(?<value>.*)?$' $firmware = (bcdedit /enum firmware); foreach ($item in $firmware ){ if ( $item.trim() ){ $res = [regex]::matches( $item, $pattern ) if ( $res ){ $Value = $res[0].Groups['value'].value $Name = $res[0].Groups['name'].value if ( $Value ){ if ( $Name ){ "$item creating pso" | out-host; $PSO = [PSCustomObject]@{ Name = $Name Value = $Value } $NameArray += $PSO } else { if ( $NameArray.count ){ ( $NameArray | Select-Object -last 1 ).Value += "; $Value" } } } } } else { if ( $NameArray ){ $Configs.add(($NameArray)) $NameArray = @() } } } #the above loop from the example I found doesn't add the final item, so run this bit one more time if ( $NameArray ){ $Configs.add(($NameArray)) $NameArray = @() } $netbootsipv4 = $configs | Where-Object { $_.Value[-1] -match "Network" -OR $_.Value[-1] -match "PXE" -OR $_.Value[-1] -match "IPV4" } | Where-Object { $_.Value[-1] -notmatch "IPV6" } #loop through the found netboot options and put each one at the top so all of them are before windows boot $result = New-Object -TypeName System.collections.generic.List['System.Object'] $netbootsipv4 | ForEach-Object { $GUID = $_.Value[0]; $bootOption = "Adding Desc: $($_.Value[1]) GUID: $GUID to boot first"; $addBootToTop = (bcdedit /set "{fwbootmgr}" displayorder $GUID /addfirst); $result.add($bootOption); $result.add($addBootToTop); } #now that for sure all pxe boot options are first boots, try to find the active connection that matches and make it for sure the first boot option $upNets = (get-netadapter | Where-Object status -eq up).InterfaceDescription $upNets | ForEach-Object { #set the current item to a variable $adapterName = $_; #see if the active adapter's description matches any of the found ipv4 boot options $adapterBootEntry = $netbootsipv4 | Where-Object { $_.Value[-1] | Select-String -pattern $adapterName -SimpleMatch} if ($adapterBootEntry) { $guid = $adapterBootEntry.Value[0] $bootOption = "This interface is active, put it towards the top - Adding Desc: $($_.Value[1]) GUID: $GUID to boot first"; $addBootToTop = (bcdedit /set "{fwbootmgr}" displayorder $GUID /addfirst); $result.add($bootOption); $result.add($addBootToTop); } } $newBootOrder = (bcdedit /enum "{fwbootmgr}"); #make c:\temp if it doesn't exist if (!(Test-Path 'C:\temp')) { mkdir 'C:\temp'; } #log everything in a new C:\temp\firmware.log file $resultString = "Firmware: $($firmware | out-string)`n`nresult: $($result | out-string)`n`nNewBootOrder: $newBootOrder`n" New-Item -path C:\temp\firmware.log -itemType File -value $resultString -force; } $netBootScript = "C:\temp\netboot.ps1"; New-Item $netBootScript -value $sb.tostring() -force; $action = New-ScheduledTaskAction -Execute "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Argument "-File 'C:\temp\netboot.ps1'" $task = New-ScheduledTask -Action $action -Description "update bcd" -Principal $principal -Trigger $trigger -Settings $settings; $taskName = "boot-to-IPV4"; #register the task Register-ScheduledTask -InputObject $task -TaskName $taskName; # force the task to start Start-ScheduledTask -TaskName $taskName; # wait for the task to finish while ((Get-ScheduledTask $taskName).State -eq 'Running') { Start-Sleep -Seconds 1; } #delete the task Unregister-ScheduledTask -TaskName $taskName -Confirm:$false -EA 0; #delete the created script file remove-Item $netBootScript -force -ea 0;
I saved the above as a .ps1 file and made it a snapin and it worked for me when I tested it on a vm. However, it did make it so when fog booted to the hard disk via refind it wasn’t able to boot into windows. This may be related to my own custom configs in refind, but something to test for on a few different platforms to be on the safe side.
Wait wait, I made a small change to the logging and updated the snapin and then it didn’t work the second time. That’s odd… I recreated and couldn’t get it to work a second time. There’s something weird going on for sure. I know I double checked that things were not already configured to boot to the network the time it did work.
Granted, since it’s happening via scheduled task, if you have an AD environment you could deploy this script in a scheduledTask via a gpo. Add the file (the one created from the $sb in the script) to computers with file preferences and create the scheduled task that runs as the system account using a scheduled task gpo.Will have to dig more into this on why the script isn’t doing anything via snapin, maybe @Sebastian-Roth can help a bit on troubleshooting the client side. And maybe other @testers could test using this script as a snapin too to see what results are being had elsewhere.
Then just as an fyi to anyone reading this, you can revert back to the normal windows boot manager with
(bcdedit /set "{fwbootmgr}" displayorder "{bootmgr}" /addfirst);
-
@lebrun78
Have you found a solution to your problem?
I have the same problem with bcdedit via a snapin. -
This post is deleted! -
I’m just going to put these right here
https://fogapi.readthedocs.io/en/latest/commands/Set-WinToBootToPxe/
https://github.com/darksidemilk/FogApi/blob/master/FogApi/Public/Set-WinToBootToPxe.ps1
Not an answer to the snapin issue with bcdedit, but I have published a powershell function within the FogApi module for managing the bcdedit commands and setting a host to boot ot pxe.
I did just test it as a snapin with a simple script like this:
#registery the psgallery repository and trust it Register-PSRepository -Default -ea 0; Set-PSRepository -Name PSGallery -InstallationPolicy Trusted; #install the fogapi module from the gallery install-module fogapi -Repository PSGallery -ea 0 -Confirm:$false -Force -Scope AllUsers; #run command to set pxe boot Set-WinToBootToPxe;
But when run as a snapin it still isn’t working, run manually on a machine it does work.
I’m not sure yet why the command run in the context of a snapin doesn’t work.