Powershell Form watching wsusutil.exe until finished - powershell

This is my first form I'm making to accomplish a task, but also to learn how to do it. I'm making a simple front end for exporting and then importing WSUS data from a connected server to a disconnected server. I'm working on the export part now and I need to figure out how to start the export process, then once it is done then make the iso file.
Here is the button code I have so far, but not sure how to watch the WsusUtil.exe until it's done then proceed to the next task. I thought I could watch the process and when it's over move to the next step. But have not been able to make that work. I tried a do until, but it kept running the start-process over and over. Also when it starts it make a large black box with some message on it. I tried to use the -NoNewWindow but it did launched. WsusUtil.exe running
$btnStartExport.Add_Click({
$nicedate = get-date -UFormat %m-%d-%y #put in MM-DD-YY format
#progress bar for overall progress of steps 1 and 2 and individual progress bar for each steps
$WSUSUtilPath = "c:\Program Files\Update Services\Tools\"
$WSUSMetaDataPath = "c:\tools\wsusexport\"
$isotitle = "WSUS Offline Server update $nicedate"
$ProcessName = "WsusUtil" #process to watch until it's done
$isofilename = "WSUSSvrOffline-$nicedate.iso" #creates WSUS Offline Server update-11-14-2021.iso
#Step 1 Check if directory exists
Check-Path $WSUSMetaDataPath
#Step 1 - export the WSUS Metadata
Start-process -FilePath $WSUSUtilPath\WsusUtil.exe -ArgumentList #("export","$WSUSMetaDataPath\$nicedate-export.xml.gz","$WSUSMetaDataPath\$nicedate-export.log") -NoNewWindow -Wait
$wsusProcess = get-process WsusUtil -ErrorAction SilentyContinue
# Step 2 - create ISO
get-childitem "$WSUSMetaDataPath","$txtWSUSContentPath.text" | New-IsoFile -path $txtISOLocation.text+$isofilename -Force -Title $isotitle
#clean up medatadata directory
get-childitem -path $WSUSMetaDataPath -Include *.* -File -Recurse | foreach {$_.Delete()}
})
$frmMain.controls.add($btnStartExport)

Related

How do I create a loop based on file size in power shell

I am working with intune and PowerShell and I basically want to run a exe file which downloads 15.2GB / 7932 files for the insulation off the autodesk website and then creates a text file so that intune knows that it's done as I want to delete all the install files with another script later.
The problem is the PowerShell script will run and close before it has finished downloading and intune thinks it is done and the next script tries to install what was downloaded but it is not fully downloaded so it fails.
I have tried to put a wait command but intune will just hang and you will have to restart windows which is something I don't want the users to do.
I am thinking to add a loop so ot checks the file size of the following folder:
C:\Autodesk\{E658F785-6D4D-4B7F-9BEB-C33C8E0027FA}
and once it reaches 15.2GB / 7932 files it goes to the next step and creates the text file.
Below is my current PowerShell script:
Start-Process -NoNewWindow -FilePath "\\arch-syd-fs\EM Setup\Autodesk Recap Custom Install 2023\Source 1 Download\Revit_2023.exe" -ArgumentList "--quiet' " -Wait
New-Item "C:\Temp\Revit 2023" -Type Directory
New-Item -Path "C:\Temp\Revit 2023\Download Done.txt"
Lets break this down into 3 questions
How do you check the size of a directory?
How do you check the count of files in a directory?
How do you make a script wait until these checks reach a certain value?
It turns out you can do the first 2 together
$dirStats = Get-ChildItem -Recurse -Force 'C:\path\to\whatever' | Measure-Object -Sum Length
$size = $dirStats.Sum
$fileCount = $dirStats.Count
Then you can wrap it in a do-until loop (with a delay to keep it from eating all the CPU) to make the script wait until those values reach a certan threshold
do {
Start-Sleep 5
$dirStats = Get-ChildItem -Recurse -Force 'C:\path\to\whatever' | Measure-Object -Sum Length
$size = $dirStats.Sum
$fileCount = $dirStats.Count
} until( ($size -ge 15.2*1024*1024*1024) -and ($fileCount -ge 7932) )
Note that $size is in bytes, and you might want to make that an -or condition rather than an -and depending on weather you want the script to return after either condition is met or wait for both.

Create Scheduled Task download ClamAV daily using Powershell

So I'm looking to download the ClamAV cvd definition files on a server so that I can keep my clients updated regularly.
In order to keep it separate from any login/admin account, I'd like to use a service account.
This is the powershell script that I have so far;
Start Microsoft-Edge:http://database.clamav.net/main.cvd
sleep 120
Get-Process -Name "*Edge*" | Stop-Process
Start Microsoft-Edge:http://database.clamav.net/daily.cvd
sleep 120
Get-Process -Name "*Edge*" | Stop-Process
Get-Item -Path "C:\Temp\*.cvd" | Move-Item -Destination "C:\Updates\ClamAV\*.cvd"
This powershell script works for me, and should run fine as a scheduled task under a different service account:
# Download both files using edge to bypass cloudflare
Start-Process msedge http://database.clamav.net/main.cvd
Start-Process msedge http://database.clamav.net/daily.cvd
sleep -Seconds 30
# close edge
Get-Process msedge | Stop-Process
# move files from default edge location to updates folder
Get-Item "$env:USERPROFILE\Downloads\*.cvd" | Move-Item -Destination "C:\Updates\ClamAV\*.cvd"
Alternatively, you can skip the move step by specifying a different download folder in edge. Run edge as your service account user > Settings > Downloads > Location > set the folder path you want

Run all .exe in a folder

I'm playing with malware in a VM and every script I try gets stuck. Basically I need to run every .exe in a folder. Tried batch files using start, powershell, etc. The issue happens when AV moves some file to quarentine, or some process keep running then the script doesn't jump to the next one.
CMD start works but shows popups when doesn't find some file, then you have to keep clicking to jump to the next file.
These works but get stuck after a while:
Get-ChildItem 'C:\Users\LAB\Desktop\test' | ForEach-Object {
>> & $_.FullName
>> }
Same here:
for %%v in ("C:\Users\LAB\Desktop\test\*.exe") do start "" "%%~v"
and here:
for %%i in (C:\Users\LAB\Desktop\test\*.exe) do %%i
You need to provide some form of code to allow us to help you troubleshoot it; this is not a request a script page.
Anyways, you would be looking at something like this:
#Assuming the .exe's are located in C Root.
Get-ChildItem -Path C:\ | Where-Object {$_.Extension -like ".exe"}| Foreach {Start-Process $_.FullName}
#In Ps, we like to filter as far left as possible for faster results.
Get-ChildItem -Path C:\ -File "*.exe" | Foreach {Start-Process $_.FullName}
#Running the commands as jobs so it doesnt wait on any to finish before running the next.
Start-Job { Get-ChildItem -Path C:\ -File "*.exe" | Foreach {Start-Process $_.FullName} }
Start-Sleep 2
Get-Job | Remove-Job
Please refer to the following link: How to ask a question

PS1 script stops execution in the middle when run silently

I'm trying to set up a PS1 script to restart the Windows service on the remote machine. Script is supposed to be automatically run by PRTG platform (monitoring solution). Platform has built-in feature which allows you start script for you. Problem is that when PRTG runs the script it stops in a half way without error after the ‘Stop-Service’ cmdlet. When I remove it from the script then full script is run. I've tried different variations of the script but it's always like it stops when it finished execution of ‘Stop-Service’.
The script supposed to be run in silent mode by the PRTG. Do you have any idea what can be the cause of it or how to check it?
$service = Get-Service -ComputerName 123.123.123.123 -Name Tomcat
Stop-Service -InputObject $service -Force
Move-Item -Path "\\123.123.123.123\C$\Program Files (x86)\tomcat\logs\tomcat.log" -Destination "\\123.123.123.123\C$\Program Files (x86)\tomcat\logs\log_archieve"
Get-ChildItem "\\123.123.123.123\C$\Program Files (x86)\tomcat\logs\log_archieve\tomcat.log" | ForEach-Object {
Rename-Item $_.FullName "$BackupFolder$($_.BaseName -replace " ", "_" -replace '\..*?$')-$(Get-Date -Format "ddMMyyyy")_oldlog.log"
}
Start-Service -InputObject $service -Verbose

Print PDFs to specific printers based on filename

I would just like to preface this by saying I am brand new to Powershell and have been trying to learn by picking things up here and there. I'm currently trying to automate a process within my company using strictly powershell and Adobe reader.
Our company currently is manually printing individual sets of records and a separate cover page, binding them, and sending them off. An idea to automate this process was to fill a folder with a zipped set of .pdfs for the day. This zip file would then be extracted and it's contents moved to another folder. PDFs with the normal set of records listed as "WO-xxxxxx Set" and the cover page as "WO-xxxxxx Cover". All I would need to do is create a simple script that prints these out in order, so that "WO-000001 Cover" is on top of "WO-000001 Set" and then print the next set in the order.
The complication I've run into is that Start-Process -FilePath $File.Fullname -Verb Print only allows me to target a default printer. Our Covers will need to be printed on thicker paper, and as such I thought the best course of action would be to create two printers on the network with the required printer settings. If I could have the script swap between the two printers based on file name then it would solve my issue.
This script is sending the documents to the printer in order but not actually swapping the default printer. I'm sure this is something I've done wrong in my IfElse cmdlet and would appreciate an experts eye in this.
Function UnZipEverything($src, $dest)
{
[System.Reflection.Assembly]::LoadWithPartialName("System.IO.Compression.FileSystem") | Out-Null
$zps = Get-ChildItem $src -Filter *.zip
foreach ($zp IN $zps)
{
$all = $src + $zp
[System.IO.Compression.ZipFile]::ExtractToDirectory($all, $dest)
}
}
UnZipEverything -src "C:\Users\admin\Desktop\Zip Test\" -dest'C:\Users\admin\Desktop\UnZip Test\'
Remove-Item "C:\Users\admin\Desktop\Zip Test\*.zip"
$files = Get-ChildItem “C:\Users\admin\Desktop\UnZip Test\*.*” -Recurse
ForEach ($file in $files){
If ($files -eq '*Cover*') {
(New-Object -ComObject WScript.Network).SetDefaultPrinter('Test')
Start-Process -FilePath $File.FullName -Verb Print -PassThru | %{ sleep 10;$_ } | kill
(New-Object -ComObject WScript.Network).SetDefaultPrinter('\\RFC-Print01\Collections Tray 6')
}
Else {Start-Process -FilePath $File.FullName -Verb Print -PassThru | %{ sleep 10;$_ } | kill
}
}
Any help would be greatly appreciated.
If you use the verb PrintTo instead of Print, you can specify the printer:
Start-Process -FilePath $File.FullName -Verb PrintTo '\\RFC-Print01\Collections Tray 6' -PassThru
This would allow you to remove the SetDefaultPrinter calls from the script.