Check if service is running after using start-sleep - powershell

How do I check if service is running again after Start-Sleep -m 120?
Maybe there is a situation when even after 120 minutes wuauserv can be running.
$getservice = Get-Service -Name wuauserv
If($getservice.Status -eq 'Running')
{
Start-Sleep -m 120
Get-ChildItem -Path $env:SystemRoot\SoftwareDistribution\Download -Force -Recurse | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
}
Else
{
Get-ChildItem -Path $env:SystemRoot\SoftwareDistribution\Download -Force -Recurse | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
}

It seems that you only want to call Get-ChildItem once your service is stopped.
One option is:
$getservice = Get-Service -Name wuauserv
$getservice.WaitForStatus('Stopped')
Get-ChildItem -Path $env:SystemRoot\SoftwareDistribution\Download -Force -Recurse |
Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
You can optionally specify a timeout:
$getservice.WaitForStatus('Stopped', '02:00:00')
Note that the WaitForStatus method waits approximately 250 milliseconds between each status check. If that's too heavy, you can use a while loop.
$getservice = Get-Service wuauserv
while($getservice.State -ne 'Stopped')
{
Start-Sleep -m 10
$getservice = Get-Service wuauserv
}
Get-ChildItem -Path $env:SystemRoot\SoftwareDistribution\Download -Force -Recurse |
Remove-Item -Force -Recurse -ErrorAction SilentlyContinue

You can run a script until the service is stopped and then run Get-ChilItem:
while($true){
if(-not isWuauservRunning){
Get-ChildItem -Path $env:SystemRoot\SoftwareDistribution\Download -Force -Recurse | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
break
}
}
If this is part of a larger script, you can us Start-Job to run this activity on the background because of the use while($true).
You can also do it like that (I don't like this method, I think it better to check the case when the service is stopped):
function isWuauservRunning(){
$isRunning = $false
$service = Get-Service -Name wuauserv
if(($service -ne $null) -and ($service.Status -eq 'Running')){
$isRunning = $true
}
return $isRunning
}
function getAndRemoveItems(){
Get-ChildItem -Path $env:SystemRoot\SoftwareDistribution\Download -Force -Recurse | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue
}
if(isWuauservRunning()){
Start-Sleep -m 120
if(-not isWuauservRunning()){
getAndRemoveItems
}
}else{
getAndRemoveItems
}

$getservice = Get-Service -Name wuauserv
while($getservice.Status -eq 'Running')
{
Start-Sleep -s 1800
$getservice = Get-Service -Name wuauserv
}
Get-ChildItem -Path $env:SystemRoot\SoftwareDistribution\Download -Force -Recurse | Remove-Item -Force -Recurse -ErrorAction SilentlyContinue

Related

Powershell Start-Process for Teams

I use the following script to clear the cache of—and start—Teams.
It worked as expected for some time. Now I get some strange behaviours like:
When I close powershell, Teams closes too
Before I close PS there appear some errors
# start Teams
# Start-Process -File "C:\Program Files (x86)\Microsoft\Teams\current\Teams.exe" -ArgumentList '--processStart "Teams.exe"'
# Write-Host "Teams Process Sucessfully Started"
# Start-Sleep -Seconds 5
#Stop Teams process
Get-Process -ProcessName Teams -ErrorAction SilentlyContinue | Stop-Process -Force
Start-Sleep -Seconds 3
Write-Host "Teams Process Sucessfully Stopped"
#Clear Team Cache
try{
# Get-ChildItem -Path $env:APPDATA\"Microsoft\Teams" | Remove-Item -Recurse -ErrorAction SilentlyContinue # Clear.all
Get-ChildItem -Path $env:APPDATA\"Microsoft\Teams\blob_storage" | Remove-Item -Recurse -ErrorAction SilentlyContinue
Get-ChildItem -Path $env:APPDATA\"Microsoft\Teams\databases" | Remove-Item -Recurse -ErrorAction SilentlyContinue
Get-ChildItem -Path $env:APPDATA\"Microsoft\Teams\cache" | Remove-Item -Recurse -ErrorAction SilentlyContinue
Get-ChildItem -Path $env:APPDATA\"Microsoft\Teams\gpucache" | Remove-Item -Recurse -ErrorAction SilentlyContinue
Get-ChildItem -Path $env:APPDATA\"Microsoft\Teams\Indexeddb" | Remove-Item -Recurse -ErrorAction SilentlyContinue
Get-ChildItem -Path $env:APPDATA\"Microsoft\Teams\Local Storage" | Remove-Item -Recurse -ErrorAction SilentlyContinue
Get-ChildItem -Path $env:APPDATA\"Microsoft\Teams\tmp" | Remove-Item -Recurse -ErrorAction SilentlyContinue
Write-Host "Teams Cache Cleaned"
}catch{
echo $_
}
#Remove Credential from Credential manager
$credential = cmdkey /list | ForEach-Object{if($_ -like "*Target:*" -and $_ -like "*msTeams*"){cmdkey /del:($_ -replace " ","" -replace "Target:","")}}
#Remove Reg.Key
$Regkeypath= "HKCU:\Software\Microsoft\Office\Teams"
$value = (Get-ItemProperty $Regkeypath).HomeUserUpn -eq $null
If ($value -eq $False)
{
Remove-ItemProperty -Path "HKCU:\Software\Microsoft\Office\Teams" -Name "HomeUserUpn"
Write-Host "The registry value Sucessfully removed"
}
Else { Write-Host "The registry value does not exist"}
#Get Desktop-config.json
$TeamsFolders = "$env:APPDATA\Microsoft\Teams"
try{
$SourceDesktopConfigFile = "$TeamsFolders\desktop-config.json"
$desktopConfig = (Get-Content -Path $SourceDesktopConfigFile | ConvertFrom-Json)
}
catch{ Write-Host "Failed to open Desktop-config.json" }
#Overwrite the desktop-config.json
Write-Host "Modify desktop-Config.Json"
try{
$desktopConfig.isLoggedOut = $true
$desktopConfig.upnWindowUserUpn =""; #The email used to sign in | also: whoami /upn
$desktopConfig.userUpn ="";
$desktopConfig.userOid ="";
$desktopConfig.userTid = "";
$desktopConfig.homeTenantId ="";
$desktopConfig.webAccountId="";
$desktopConfig | ConvertTo-Json -Compress | Set-Content -Path $SourceDesktopConfigFile -Force
}
catch{ Write-Host "Failed to overwrite desktop-config.json" }
Write-Host "Modify desktop-Config.Json - Finished"
#Delete the Cookies file. This is a fix for when the joining as anonymous, and prevents the last used guest name from being reused.
Get-ChildItem "$TeamsFolders\Cookies" | Remove-Item
#Lastly delete the storage.json, this corrects some error that MSTeams otherwise would have when logging in again.
Get-ChildItem "$TeamsFolders\storage.json" | Remove-Item
#Try to remove the Link School/Work account if there was one. It can be created if the first time you sign in, the user all
# $LocalPackagesFolder ="$env:LOCALAPPDATA\Packages"
# $AADBrokerFolder = Get-ChildItem -Path $LocalPackagesFolder -Recurse -Include "Microsoft.AAD.BrokerPlugin_*";
# $AADBrokerFolder = $AADBrokerFolder[0];
# Get-ChildItem "$AADBrokerFolder\AC\TokenBroker\Accounts" | Remove-Item -Recurse -Force
# Start-Sleep -Seconds 5
# start Teams
Start-Process -File "C:\Program Files (x86)\Microsoft\Teams\current\Teams.exe" -ArgumentList '--processStart "Teams.exe"'
# "$($env:USERProfile)\AppData\Local\Microsoft\Teams\Update.exe"
Start-Sleep -Seconds 3
Write-Host "Teams Process Sucessfully Started"
# Stop for testpurposes
pause
SIDENOTE
Teams is installed as per Microsoft recommendation for VDI setups.
(Citrix VDI/VDA, HDX Optimized)
It worked as expected for some time. Now I get some strange behaviours like:
When I close powershell, Teams closes too
Before I close PS there appear some errors
Screenshot of errors

New-PSsession to create a loop and wait to finish foreach line in text file

I am trying to get files from servers in a list using the below
$server = Get-Content server.txt
$server| ForEach-Object {
$session=new-pssession -computername $server -credential (Import-Clixml "mycredentials.xml")
Invoke-Command -Session $session -ScriptBlock ${function:getfiles}
Copy-Item -path "C:\some\folder\*" -Destination "C:\localfolder" -recurse -FromSession $session
}
If I supply explicitly a name in -computername, works like a charm.
When there are several names in the list, the execution stops after the first one. I suspect that the session closes after the first execution.
Is there a way to make it like this:
get-content -> for each line execute the copy-item -> close session -> open new session to new server -> .....etc, meaning that $session will be only for the current server.
$function:getfiles
function getfiles {
New-Item -Force -Path C:\path\trace.txt
$remoteserver=$env:computername
$trace='C:\path\trace.txt'
$Include = #('*.keystore', '*.cer', '*.crt', '*.pfx', '*.jks', '*.ks')
$exclude = '^C:\\(Windows|Program Files|Documents and Settings|Users|ProgramData)|\bBackup\b|\breleases?\b|\bRECYCLE.BIN\b|\bPerfLogs\b|\bold\b|\bBackups\b|\brelease?\b|'
Get-ChildItem -Path 'C:\','D:\' -file -Include $include -Recurse -EA 0|
Where-Object { $_.DirectoryName -notmatch $exclude } |
Select-Object -ExpandProperty FullName |
Set-Content -Path $trace
$des = "C:\some\folder\$remoteserver"
$safe = Get-Content $trace
$safe | ForEach-Object{
#find drive-delimeter
$first=$_.IndexOf(":\");
if($first -eq 1){
#stripe it
$newdes=Join-Path -Path $des -ChildPath #($_.Substring(0,1)+$_.Substring(2))[0]
}
else{
$newdes=Join-Path -Path $des -ChildPath $_
}
$folder=Split-Path -Path $newdes -Parent
$err=0
#check if folder exists"
$void=Get-Item $folder -ErrorVariable err -ErrorAction SilentlyContinue
if($err.Count -ne 0){
#create when it doesn't
$void=New-Item -Path $folder -ItemType Directory -Force -Verbose
}
$void=Copy-Item -Path $_ -destination $newdes -Recurse -Container -Verbose
}
}
UPDATE
So I have found out that the file where the lines should be be redirected from the script is not populated, which explains why the next step for copy-item fails. I have tried redirecting in different ways, still cant get it populated. The file is created without issues.
Made a workaround - placed the function in a script which is copied to the remote server / execute it \ clean afterwards.

Powershell script launched from logon script not working

I'm trying to create a powershell script that searches a users C drive for a certain file extension, and then writes a file to a network share if it finds one. The script is launched from the last line of a logon script that reads like this:
powershell.exe -ExecutionPolicy Bypass -windowstyle hidden -file "\\servername\Path\To\File.ps1"
And my powershell script looks like this:
$hostname = HostName
Get-ChildItem -Path C:\*.* -Filter $file -Recurse -Force -ErrorAction
SilentlyContinue | Out-File \\servername\Path\To\Results\$hostname\file.txt
If ((Get-Content "\\servername\Path\To\Results\$hostname\file.txt") -eq $Null) {
Remove-Item \\servername\Path\To\Results\$hostname\file.txt
}
Exit
The script runs perfectly fine on my machine even when I load it from the network share but whenever another computer runs it, it never produces an Out File. And I don't think it is even searching.
What am I doing wrong? I thought it was execution policy, but I've set the logon script to bypass it. I don't understand why it isn't working.
[edit]
I've now got the script working sometimes on Windows 10 machines. But it doesn't work at all on Windows 7. I've even tried running
Get-ChildItem C:\*.pst -Recurse
directly from a powershell command prompt, and it just fails silently and doesn't search for anything. Isn't Get-ChildItem a powershell 1 command?
Hello. If you do like this: Get-ChildItem -Path C:*.* -Filter $file
-Recurse -Force the text file output will be enough to weigh.
You can try to check the access to the network folder for the current
user:if access explicitly set, and write access exists, then you can
record a file with the content. Otherwise, it can create folder test
on the local machine which will create the file, indicating that there
is no access. How is this way:
Set-ExecutionPolicy remotesigned -Scope CurrentUser -Force| Out-Null
$user = [System.Environment]::UserName
$hostname = [System.Environment]::MachineName
try {
$accs = Get-ACL -Path "\\server\sharedfolder\Results\"
foreach ($access in $accs) {
$obj = New-Object -TypeName PSObject -Property #{
Access = $accs.Access
}
$obj1 = $obj | select -ExpandProperty Access
for ($i = 0 ; $i -le $obj1.Count ; $i ++ )
{
if (!($obj1[$i].IdentityReference -like "*Users*" -or $obj1[$i].IdentityReference -like "*$user*")) {
if (!(Test-Path "c:\test")) {
md c:\test
$s = "user access from group"
$s | out-file C:\test\ErrInfo.csv
}
else {
$s = "user access from group"
$s | out-file C:\test\ErrInfo.csv
}
}
if ($obj1[$i].IdentityReference -like "*Users*" -or $obj1[$i].IdentityReference -like "*$user*") {
if ($obj1[$i].FileSystemRights -like "*ReadAndExecute*")
{
if (!(Test-Path "c:\test")) {
md c:\test
$s = "Premission only ReadAndExecute"
$s | out-file C:\test\ErrInfo_rex.csv
}
else {
$s = "Premission only ReadAndExecute"
$s | out-file C:\test\ErrInfo_rex.csv
}
}
if ($obj1[$i].FileSystemRights -like "*FullControl*" -and $obj1[$i].AccessControlType -like "*Allow*" -or $obj1[$i].FileSystemRights -like "*Modify*" -and $obj1[$i].AccessControlType -like "*Allow*")
{
if (!(Test-Path "\\server\sharedfolder\Results\$hostname"))
{
md "\\server\sharedfolder\Results\$hostname"
Get-ChildItem -Path C:\testpatch\*.* -Filter $file -Recurse -Force -ErrorAction SilentlyContinue | Out-File "\\server\sharedfolder\Results\$hostname\file.txt"
}
else {
Get-ChildItem -Path C:\testpatch\*.* -Filter $file -Recurse -Force -ErrorAction SilentlyContinue | Out-File "\\server\sharedfolder\Results\$hostname\file.txt"
}
}
}
}
}
}
catch {
if (!(Test-Path "c:\test")) {
md c:\test
$s = "--NoAccess--"
$s | out-file C:\test\ErrInfo_noaccess.csv
}
else {
$s = "--NoAccess--"
$s | out-file C:\test\ErrInfo_noaccess.csv
}
}
Or you can do something like this (whiteout EXIT):
Set-ExecutionPolicy remotesigned -Scope CurrentUser -Force| Out-Null
$hostname = [System.Environment]::MachineName
if (!(Test-Path "\\server\sharedfolder\Results\$hostname")) {
md "\\server\sharedfolder\Results\$hostname" | Out-Null
If ((Get-ChildItem -Path C:\test\*.* -Filter $file -Recurse -Force -ErrorAction SilentlyContinue).Count -ne "0") {
Get-ChildItem -Path C:\test\*.* -Filter $file -Recurse -Force -ErrorAction SilentlyContinue | Out-File "\\server\sharedfolder\Results\$hostname\file.txt"
}
}
elseif (Test-Path "\\server\sharedfolder\Results\$hostname") {
If ((Get-ChildItem -Path C:\test\*.* -Filter $file -Recurse -Force -ErrorAction SilentlyContinue).Count -ne "0") {
Get-ChildItem -Path C:\test\*.* -Filter $file -Recurse -Force -ErrorAction SilentlyContinue | Out-File "\\server\sharedfolder\Results\$hostname\file.txt"
}
}

Need help trying to completely remove a "virus pertection software"

the company I work for is moving to a new virus protection software. I have been tasked with writing the tool that will remove the older virus software since the standard uninstall doesn't seem to remove the entire software package. I have searched around Stack Overflow and found many different examples of how to get different parts of this tool to work and have thrown them together in an attempt to make a working product. For a reason I have yet to figure out I can't seem to get anything to work. Here is what I have so far:
# This section launches Powershell as Admin
PS> Start-Process powershell -Verb runAs
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }
PS >Read-Host "Press ENTER"
Press ENTER:
# This section uninstalls Vipre from the program files
$app = Get-WmiObject -Class Win32_Product | Where-Object {
$_.Name -match "VIPRE BUSINESS AGNET"
}
$app.Uninstall()
PS >Read-Host "Press ENTER"
Press ENTER:
# This section searches the Registry for all instances of Vipre and VIPRE BUSINESS AGENT and deletes them
gci HKLM: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath)
-match "Vipre") { $_.PsPath} } | Remove-Item
gci HKCR: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath)
-match "Vipre") { $_.PsPath} } | Remove-Item
gci HKCU: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath)
-match "Vipre") { $_.PsPath} } | Remove-Item
gci HKU: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath)
-match "Vipre") { $_.PsPath} } | Remove-Item
gci HKLM: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath)
-match "VIPRE BUSINESS AGENT") { $_.PsPath} } | Remove-Item
gci HKCR: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath)
-match "VIPRE BUSINESS AGENT") { $_.PsPath} } | Remove-Item
gci HKCU: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath)
-match "VIPRE BUSINESS AGENT") { $_.PsPath} } | Remove-Item
gci HKU: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath)
-match "VIPRE BUSINESS AGENT") { $_.PsPath} } | Remove-Item
PS >Read-Host "Press ENTER"
Press ENTER:
I have a pause, "Press Enter" to try and see what the command before it has done and even that doesn't seem to be working. As the screen flashes, I can tell there are errors being thrown, and then goes away.
My questions are:
What am I doing wrong? Are there syntax errors and what are they?
Thank you for all help.
EDIT UPDATE
My file now looks like this:
# This section launches Powershell as Admin
{ Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -verb RunAs; exit }
$code = {
# This section uninstalls Vipre from the program files
$App = Get-WmiObject -Class Win32_Product -Filter 'Name like %"VIPRE BUSINESS AGENT"%"'
if ($App)
{
$App.Uninstall()
}
# This section searches the Registry for all instances of Vipre and VIPRE BUSINESS AGENT and deletes them
Get-ChildItem HKLM: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'Vipre') { $_.PsPath} } | Remove-Item
Get-ChildItem HKCR: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'Vipre') { $_.PsPath} } | Remove-Item
Get-ChildItem HKCU: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'Vipre') { $_.PsPath} } | Remove-Item
Get-ChildItem HKU: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'Vipre') { $_.PsPath} } | Remove-Item
Get-ChildItem HKLM: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'VIPRE BUSINESS AGENT') { $_.PsPath} } | Remove-Item
Get-ChildItem HKCR: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'VIPRE BUSINESS AGENT') { $_.PsPath} } | Remove-Item
Get-ChildItem HKCU: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'VIPRE BUSINESS AGENT') { $_.PsPath} } | Remove-Item
Get-ChildItem HKU: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'VIPRE BUSINESS AGENT') { $_.PsPath} } | Remove-Item
}
$bytes = [System.Text.Encoding]::Unicode.GetBytes($code)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -executionpolicy bypass -noprofile -noexit -verb runas -encodedCommand $encodedCommand
The PowerShell script seems to be at least trying to run now but then throws the error:
-verb : The term '-verb' is not recognized as the name of a cmdlet,function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1
+ -verb runas -encodedCommand DQAKACAAIAAgAA0ACgAjACAAVABoAGkAcwAgAHMAZ ...
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (-verb:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I tried removing -verb from both the top and bottom of the script and that causes PowerShell to give me a bunch of commands that need to follow RUNAS.
This here could work - but I have no idea what the first if-statement is supposed to do:
# This section launches Powershell as Admin
if (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) { Start-Process powershell.exe "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`"" -Verb RunAs; exit }
$code = {
Read-Host 'Press ENTER'
Press ENTER:
# This section uninstalls Vipre from the program files
$app = Get-WmiObject -Class Win32_Product | Where-Object {
$_.Name -match 'VIPRE BUSINESS AGNET' ##Typo 'AGNET'?
}
$app.Uninstall()
Read-Host 'Press ENTER'
Press ENTER:
# This section searches the Registry for all instances of Vipre and VIPRE BUSINESS AGENT and deletes them
Get-ChildItem HKLM: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'Vipre') { $_.PsPath} } | Remove-Item
Get-ChildItem HKCR: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'Vipre') { $_.PsPath} } | Remove-Item
Get-ChildItem HKCU: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'Vipre') { $_.PsPath} } | Remove-Item
Get-ChildItem HKU: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'Vipre') { $_.PsPath} } | Remove-Item
Get-ChildItem HKLM: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'VIPRE BUSINESS AGENT') { $_.PsPath} } | Remove-Item
Get-ChildItem HKCR: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'VIPRE BUSINESS AGENT') { $_.PsPath} } | Remove-Item
Get-ChildItem HKCU: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'VIPRE BUSINESS AGENT') { $_.PsPath} } | Remove-Item
Get-ChildItem HKU: -rec -ea SilentlyContinue | % { if((get-itemproperty -Path $_.PsPath) -match 'VIPRE BUSINESS AGENT') { $_.PsPath} } | Remove-Item
Read-Host 'Press ENTER'
Press ENTER:
}
$bytes = [System.Text.Encoding]::Unicode.GetBytes($code)
$encodedCommand = [Convert]::ToBase64String($bytes)
powershell.exe -executionpolicy bypass -noprofile -noexit -verb runas -encodedCommand $encodedCommand
Man, sorry but your code is a mess...
Few remarks:
1. This is not the right way to execute powershell code... save your code text to .PS1 file then execute it on the remote machine like this:
powershell -ExecutionPolicy Bypass -NoProfile -File \\share\script.ps1
2. If you want to check for admin privileges, do it inside your code,
if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
## if the user is admin the code will be executed
}
else
{
throw "This code must be run with admin privileges"
}
3. Use Get-WMIObject -Filter Parameter - It will be much faster then Where-Object
$App = Get-WmiObject -Class Win32_Product -Filter 'Name like %"VIPRE BUSINESS AGNET"%"'
if ($App)
{
$App.Uninstall()
}
4. Don't Search the whole Registry to find this keys, as Ansgar Suggested, check at the vendor for specific keys, see chapter IV - "Removal of the VIPRE Agent's Registry Entries" on the vendor site in the following link:
https://support.threattracksecurity.com/support/solutions/articles/1000070667-how-to-manually-remove-a-vipre-business-agent

Copy Folder To A Range Of Computers On LAN

I want to copy a folder to a range of computers on my LAN. Here is what I have so far:
$Computers = "Get-Content C:\Scripts\computers.txt"
$Source = "C:\Install\9_10_00_08HotFix_201504140001"
$Destination = "\\192.168.6.$\c$\Install"
ForEach-Object {
Copy-Item -Path $Source -Recurse -Destination $Destination -Verbose -Force -ErrorAction SilentlyContinue
}
You didn't say what your actual problem is, but it's probably that you misplaced the first double quote in the Get-Content statement, that you can't define a variable destination like you do, and that you don't do anything with what you (try to) read from computers.txt.
Change this:
$Computers = "Get-Content C:\Scripts\computers.txt"
$Source = "C:\Install\9_10_00_08HotFix_201504140001"
$Destination = "\\192.168.6.$\c$\Install"
ForEach-Object {
Copy-Item -Path $Source -Recurse -Destination $Destination -Verbose -Force -ErrorAction SilentlyContinue
}
into this:
$Computers = Get-Content "C:\Scripts\computers.txt"
$Source = "C:\Install\9_10_00_08HotFix_201504140001"
$Computers | ForEach-Object {
Copy-Item -Path $Source -Recurse -Destination "\\192.168.6.$_\c$\Install" -Verbose -Force -ErrorAction SilentlyContinue
}
and your code should work.