I'd like to condense
psexec \\server taskill /f /t /fi "USERNAME eq $username" /im soffice*
psexec \\server taskill /f /t /fi "USERNAME eq $username" /im swriter*
psexec \\server taskill /f /t /fi "USERNAME eq $username" /im scalc*
psexec \\server taskill /f /t /fi "USERNAME eq $username" /im simpress*
Into one psexec command. Normally I'd try the & operator to do so & so but since I'm doing this all in PS, it doesn't seem to like that. I tried an array of () and "" but it doesn't seem to like those either.
EDIT [answer]
Ended up just copying a .cmd (BAT) file and making a shortcut in my $PROFILE locally.
function flushlibra
{
param([string]$user = "")
if ($user -eq "")
{
$user = Read-Host "User to nuke LibraOffice proccesses: "
}
psexec -c "\\unc\path\to\flushlibra.cmd" $user
}
.cmd file
taskkill /f /t /fi "USERNAME eq %1" /im soffice*
taskkill /f /t /fi "USERNAME eq %1" /im swriter*
taskkill /f /t /fi "USERNAME eq %1" /im scalc*
taskkill /f /t /fi "USERNAME eq %1" /im simpress*
psexec allows you to invoke a batch script remotely, too, not just single commands. Use the -c switch to indicate that the script should be copied to the remote system.
So if you locally have a script KillProcs.cmd:
taskill /f /t /fi "USERNAME eq $username" /im soffice*
taskill /f /t /fi "USERNAME eq $username" /im swriter*
taskill /f /t /fi "USERNAME eq $username" /im scalc*
taskill /f /t /fi "USERNAME eq $username" /im simpress*
Then you can run that remotely like this
psexec \\server -c c:\localpath\KillProcs.cmd
I always use like this way :) and works properly
psexec \\COMPUTER -e cmd /c (COMMAND1 ^& COMMAND2 ^& COMMAND3)
If you just want to concatencate commands on a single line then use the statement separator ; e.g.:
psexec \\server taskill /f /t /fi "USERNAME eq $username" /im soffice*; psexec \\server taskill /f /t /fi "USERNAME eq $username" /im swriter* ; psexec \\server taskill /f /t /fi "USERNAME eq $username" /im scalc* ; psexec \\server taskill /f /t /fi "USERNAME eq $username" /im simpress*
From looking at the PSEXEC usage, it doesn't appear to allow you to specify multiple programs in a single invocation of PSEXEC.
BTW you could use PowerShell's remoting capability - assuming server has WMF 2.0 or higher installed and has enabled WSMan remoting e.g.:
Invoke-Command -ComputerName server {Stop-Process -Name soffice*,swriter*,scalc*,simpress* -Force}
If you can't go the remoting route, another approach would be to create a PowerShell function:
function Stop-RemoteProcess([string]$ComputerName, [string[]]$Programs, [string]$UserName)
{
foreach ($program in $Programs)
{
psexec "\\$ComputerName" taskill /f /t /fi "USERNAME eq $UserName" /im $program
}
}
Stop-RemoteProcess server soffice*,swriter*,scalc*,simpress* JohnDoe
Related
Supp guys. I and a buddy is creating a AIO that we can personally use but I am struggling with the following code which will allow us to "uninstall" MS Security module.
Here is the code
:REMOVE_WINDOWS_DEFENDER
title REMOVE WINDOWS DEFENDER
color 0f
mode con cols=98 lines=32
cls
ECHO:
ECHO This script makes use of the install_wim_tweak.exe to run API in the system to remove Windows Defender.\n\nThe install_wim_tweak.exe will be
ECHO automatically downloaded and executed. This script must be run as administrator and the system restarted after finish. If Windows complains
ECHO afterwards about the system being unprotected, right click the notification and hide it.
ECHO This script changes can not be reverted. USE AT OWN RISK!
ECHO STILL WORKING OUT THE FINE DETAILS
timeout 2 >nul
Reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer /v SmartScreenEnabled /t REG_SZ /d "Off" /f
Reg add HKCU\Software\Microsoft\Windows\CurrentVersion\AppHost /v "EnableWebContentEvaluation" /t REG_DWORD /d "0" /f
Reg add HKCU\Software\Classes\Local Settings\Software\Microsoft\Windows\CurrentVersion\AppContainer\Storage\microsoft.microsoftedge_8wekyb3d8bbwe\MicrosoftEdge\PhishingFilter /v "EnabledV9" /t REG_DWORD /d "0" /f
Reg add HKLM\SOFTWARE\Policies\Microsoft\Windows Defender /v DisableAntiSpyware /t REG_DWORD /d 1 /f
Reg add HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Spynet /v SpyNetReporting /t REG_DWORD /d 0 /f
Reg add HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Spynet /v SubmitSamplesConsent /t REG_DWORD /d 2 /f
Reg add HKLM\SOFTWARE\Policies\Microsoft\Windows Defender\Spynet /v DontReportInfectionInformation /t REG_DWORD /d 1 /f
Reg delete HKLM\SYSTEM\CurrentControlSet\Services\Sense /f
Reg add HKLM\SOFTWARE\Policies\Microsoft\MRT /v "DontReportInfectionInformation" /t REG_DWORD /d 1 /f
Reg add HKLM\SOFTWARE\Policies\Microsoft\MRT /v "DontOfferThroughWUAU" /t REG_DWORD /d 1 /f
Reg delete HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run /v "SecurityHealth" /f
Reg delete HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run /v "SecurityHealth" /f
Reg add HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\SecHealthUI.exe /v Debugger /t REG_SZ /d "%windir%\System32\taskkill.exe" /f
Reg add HKCU\Software\Microsoft\Windows\CurrentVersion\Notifications\Settings\Windows.SystemToast.SecurityAndMaintenance /v "Enabled" /t REG_DWORD /d 0 /f
Reg delete HKLM\SYSTEM\CurrentControlSet\Services\SecurityHealthService /f
powershell.exe {
$dir = 'C:\AIO'
Set-Location $dir
$baseUrl = 'https://raw.githubusercontent.com/coff33ninja/AIO/main/TOOLS/2.COMPUTER_CONFIGURATION/'
$files = 'install_wim_tweak.exe',
'Uninstall.cmd'
foreach ($file in $files)
{
Write-Host "Downloading $file"
$dlUrl = "$($baseUrl)$file"
$dlPath = "$($dir)$file"
Invoke-WebRequest $dlUrl -OutFile $dlPath
}
}
call C:\AIO\Uninstall.cmd
pause & cls & goto end_COMPUTER_CONFIGURATION
I am still abit new as we mix alot of cmd and powershell code
I have a script for stress testing networks in batch, and it has been working fine for me and doing exactly what I wanted it to do. I recently tried to remake it in powershell, and overall it was the same, except for one detail. Whenever I tried to start new command prompts with start cmd.exe -argumentlist {/k ping $p /l $Bytes /t} -windowstyle Minimized, it starts cmd, but it gets lost at the $p saying Ping request could not find host $p. Please check the name and try again. instead of actually passing the variable. I have been stumped for a while and couldn't find what was causing this issue since when I passed other variables to set the title of the prompts, it worked fine. The variable $p isn't getting undefined either, so I don't know what is causing this.
Here are my scripts
Batch file:
#echo off
title MainPingCenter
(call )
choice /c DC /m "Would you like to ping the default gateway or a custom IP/Web Address?"
IF %ERRORLEVEL% EQU 1 ((for /f "tokens=2,3 delims={,}" %%a in ('"WMIC NICConfig where IPEnabled="True" get DefaultIPGateway /value | find "I" "') do (echo Default IP Gateway : %%~a & set i=%%~a))
goto add)
set /p i="Type in the IP address or website address you want to ping: "
:add
set /p loopcount="How many cmds do you want to ping with? "
set /p Bytes="How many bytes of data do you want to ping with? "
set /a loopcount=loopcount+1
:loop
set /a loopcount=loopcount-1
if %loopcount% LEQ 0 (goto exitloop)
start /min cmd.exe /k ping %i% /l %Bytes% /t
goto loop
:exitloop
echo Success
echo Commands are running in background
pause
:back
choice /c CP /m "Would you like to create more ping cmds or proceed? "
IF %ERRORLEVEL% EQU 1 goto add
IF %ERRORLEVEL% EQU 2 goto choose
:choose
(call )
choice /c YNTC /m "Would you like to close all cmd processes? (Yes, No, Timer, Cancel)"
IF %ERRORLEVEL% EQU 1 goto yes
IF %ERRORLEVEL% EQU 2 goto no
IF %ERRORLEVEL% EQU 3 goto timer
IF %ERRORLEVEL% EQU 4 goto back
:yes
echo Closing all instances of cmd excluding this...
taskkill /im cmd.exe /t /f /fi "windowtitle ne MainPingCenter"
echo Taskkill complete. Press any key to continue...
pause >nul
title Command Prompt
goto :eof
:no
echo Ok, press any key to end this file...
pause >nul
title Command Prompt
goto :eof
:timer
set /p timer="Set amount of seconds until processes are closed: "
choice /c YN /m "Would you ike it to close automatically when the time is finished? "
IF %ERRORLEVEL% EQU 1 (timeout /t %timer% /nobreak & goto yes)
timeout /t %timer% /nobreak
echo Time is up. Press any key to terminate all command prompts
pause >nul
goto yes
Powershell
$host.ui.RawUI.WindowTitle = "Main Ping Center"
while (!($p)) {
$choice = read-host "Do you want to ping the default gateway, localhost, or a custom address? `n[D,L,C]"
switch ($choice) {
"D" {$p = WMIC NICConfig where IPEnabled="True" get DefaultIPGateway /value |findstr "{"; $p = $p.trimstart('DefaultIPGateway={"'); $p = $p.trimend('"}'); break}
"L" {$p = "localhost"; break}
"C" {$p = read-host "What address do you want to ping?"; break}
}
if (!($p)){echo "Invalid input"}
}
$p
while (!($lc -is [int])){
$lc = read-host "How many cmds do you want to ping with? "
$ErrorActionPreference = 'SilentlyContinue'
[int]$lc = $lc
if (!($lc -is [int])){echo "Invalid input"}
}
while (!($bytes -is [int])){
$Bytes = read-host "How many bytes of data do you want to ping with? "
$ErrorActionPreference = 'SilentlyContinue'
[int]$bytes = $bytes
if (!($bytes -is [int])){echo "Invalid input"}
}
$ErrorActionPreference = 'continue'
$nametitle = (Get-Random)*([math]::pi)*(Get-Random)
$p
do {
start cmd.exe -argumentlist {/k title $nametitle `& ping $p /l $Bytes /t} -windowstyle Minimized
# Variable "$nametitle" gets passed normally but even if I remove the title and "&", $p never gets passed
$lc--
} until ( $lc -eq 0 )
write "Success`nCommands are running in background"
pause
while (!($C2)) {
$choice2 = read-host "Would you like to close all cmd processes? (Yes/Y, No/N, Timer/T)"
switch ($choice2) {
"Yes" {$C2 = "Yes"}
"Y" {$C2 = "Yes"}
"No" {$C2 = "No"}
"N" {$C2 = "No"}
"Timer" {$C2 = "Time"}
"T" {$C2 = "Time"}
}
if (!($C2)){echo Invalid input}
}
switch ($C2) {
"Yes" {echo "Closing all instances of cmd excluding this..."
taskkill /im cmd.exe /t /f /fi "windowtitle eq $nametitle"
echo "Taskkill complete. Press any key to continue..."
pause | out-null
exit}
"No" {cd "$home\desktop"
echo $nametitle > PingName.txt
echo "Ok, sending name of ping cmds to text file..."
echo "Press any key to exit this file..."
pause | Out-Null
exit}
"Time" {$timer = read-host "Set amount of seconds until processes are closed"
timeout /t $timer /nobreak
echo "Closing all instances of cmd excluding this..."
taskkill /im cmd.exe /t /f /fi "windowtitle eq $nametitle"
echo "Taskkill complete. Press any key to continue..."
pause | out-null
exit}
}
I'm writing a cleaner for some known virus key like ( "vbs" ,"vbe" ,"wsf", "a3x") from the registry.
I want to add a BalloonTip in powershell with this script but, there is something wrong !
I don't know how to remove the icon from the taskbar to show the progress scan ?
This is a draft. It is not yet optimized !
#echo off
Title Hackoo Virus Cleaner to delete virus key from registry by Hackoo 2016
Color 1A & Mode con cols=80 lines=8
Set Pattern="\.vbs"^
^ "\.vbe"^
^ "\.wsf"^
^ "\.a3x"^
^ "VBScript.Encode"^
^ "\winlogon\.bat"
Set Key="HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run"^
^ "HKCU\Software\Microsoft\Windows\CurrentVersion\Run"^
^ "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"^
^ "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options"
For %%P in (%Pattern%) Do (
For %%K in (%Key%) Do (
Cls
echo(
echo(
Echo ***************************** Scan *****************************
echo %%K
Echo ****************************************************************
Call :PS_Sub 'Warning' 10 '" Please wait... "' "' Scan is in progress.... %%K'" 'Warning'
Call :Delete_Virus_Key %%K %%P "%TmpLogFile%"
)
)
exit /b
::*************************************************************************
:Delete_Virus_Key <Key> <Pattern> <LogFile>
Setlocal enabledelayedexpansion
for /f "delims=REG_SZ" %%I in (
'reg query "%~1" /s^|findstr /ic:"%~2"'
) Do (
If %ErrorLevel% NEQ 1 (
Set KeyName="%%~I"
(
Call:Trim !keyName!
Title Deleting Run key: !keyName!
echo Deleting Run key: !keyName!
echo reg delete "%~1" /v !keyName! /f
echo(
echo *****************************
echo reg delete "%~1" /v "!keyName!" /f
echo *****************************
echo(
)>>"%~3"
rem Call :PS_Sub 'Warning' 100 '"!KeyName!"' "'Delete !KeyName!'" 'Warning'
) else (
Set KeyName="%%~I"
Call:Trim !keyName!
Title Deleting Run key: !keyName!
echo Deleting Run key: !keyName!
echo reg delete "%~1" /v !keyName! /f
echo(
echo *****************************
echo reg delete "%~1" /v "!keyName!" /f
echo *****************************
echo(
)>>"%~3"
)
)
EndLocal
Exit /b
::*************************************************************************
:Trim <String>
(
echo Wscript.echo Trim("%~1"^)
)>"%tmp%\%~n0.vbs"
for /f "delims=" %%a in ('Cscript /nologo "%tmp%\%~n0.vbs"') do (
set "KeyName=%%a"
)
exit /b
::**************************************************************************
:PS_Sub $notifyicon $time $title $text $icon
PowerShell ^
[reflection.assembly]::loadwithpartialname('System.Windows.Forms') ^| Out-Null; ^
[reflection.assembly]::loadwithpartialname('System.Drawing') ^| Out-Null; ^
$notify = new-object system.windows.forms.notifyicon; ^
$notify.icon = [System.Drawing.SystemIcons]::%1; ^
$notify.visible = $true; ^
$notify.showballoontip(%2,%3,%4,%5)
%End PowerShell%
exit /B
::*************************************************************************
So to simplify my issue, we focus just on this function :
What should i add here to get rid the notifyicon from the taskbar ?
::**************************************************************************
:PS_Sub $notifyicon $time $title $text $icon
PowerShell ^
[reflection.assembly]::loadwithpartialname('System.Windows.Forms') ^| Out-Null; ^
[reflection.assembly]::loadwithpartialname('System.Drawing') ^| Out-Null; ^
$notify = new-object system.windows.forms.notifyicon; ^
$notify.icon = [System.Drawing.SystemIcons]::%1; ^
$notify.visible = $true; ^
$notify.showballoontip(%2,%3,%4,%5)
%End PowerShell%
exit /B
::*************************************************************************
I solved the problem thanks to #rojo idea like this :
::**************************************************************************
:PS_Sub $notifyicon $time $title $text $icon $Timeout
PowerShell ^
[reflection.assembly]::loadwithpartialname('System.Windows.Forms') ^| Out-Null; ^
[reflection.assembly]::loadwithpartialname('System.Drawing') ^| Out-Null; ^
$notify = new-object system.windows.forms.notifyicon; ^
$notify.icon = [System.Drawing.SystemIcons]::%1; ^
$notify.visible = $true; ^
$notify.showballoontip(%2,%3,%4,%5); ^
Start-Sleep -s %6; ^
$notify.Dispose()
%End PowerShell%
exit /B
::*************************************************************************
So, if anyone like to test the whole code in beta version , here is the link :
Hackoo Virus Cleaner
I have the following script in as a cmd file
FOR /F "usebackq delims=" %%G IN (myservices.txt) DO (
echo "Start service: %%Gā
NET START "%%G"
)
How would I translate that into powershell?
My guess would be something like this
FOR /F "usebackq delims=" %%G IN (myservice.txt) DO (
echo "Start service: %%Gā
start-service -name "%%G"
)
If gsp_services.txt contains service name on each line:
get-content gps_services.txt | % {
"Start service: $_ā
start-service $_
}
My shutdown script using the Shutdown -R command to do a mass reboot of machines. If the Shutdown -R throws a error like "RPC Service Unavailable, or access denied" I can't catch it or just don't know how to. Can someone help? I don't want to use Restart-Computer in powershell since you can't delay the reboot and can't add comments.
foreach($PC in $PClist){
ping -n 2 $PC >$null
if($lastexitcode -eq 0){
write-host "Rebooting $PC..." -foregroundcolor black -backgroundcolor green
shutdown /r /f /m \\$PC /d p:1:1 /t 300 /c "$reboot_reason"
LogWrite "$env:username,$PC,Reboot Sent,$datetime"
} else {
write-host "$PC is UNAVAILABLE" -foregroundcolor black -backgroundcolor red
LogWrite "$env:username,$PC,Unavailable/Offline,$datetime"
}
}
If PowerShell Remoting is enabled on $PC something like this might work:
Invoke-Command -Computer $PC { shutdown /r /f /d p:1:1 /t 300 /c $ARGV[0] } `
-ArgumentList $reboot_reason
The -Computer option takes an array of names/IPs.
If you want to stick with your approach and just catch errors from shutdown.exe, evaluate $LastExitCode after the command:
shutdown /r /f /m \\$PC /d p:1:1 /t 300 /c "$reboot_reason" 2>$null
if ($LastExitCode -ne 0) {
Write-Host "Cannot reboot $PC ($LastExitCode)" -ForegroundColor black `
-BackgroundColor red
} else {
LogWrite "$env:username,$PC,Reboot Sent,$datetime"
}
2>$null suppresses the actual error message, and the check on $LastExitCode triggers the success/failure action.