powershell Compress-Archive OutOfMemoryException - powershell

I need to compress a folder with power shell.
There is my code:
Get-ChildItem $YourDirToCompress -Directory |
where { $_.Name -notin $DirToExclude} |
Compress-Archive -DestinationPath $ZipFileResult -Update
Move-Item -Path $ZipFileResult -Destination $ZipFileDest
I get:
Exception calling "Write" with "3" argument(s): "Exception of type 'System.OutOfMemoryException' was thrown."
At
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Archive\Microsoft.PowerShell.Archive.psm1:820
char:29
+ ... $destStream.Write($buffer, 0, $numberOfBytesRead)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : OutOfMemoryException
I have set :
Set-Item WSMan:\localhost\Plugin\Microsoft.PowerShell\Quotas\MaxMemoryPerShellMB 8000
Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 8000
Restart-Service WinRM
The whole file is about 1.9 GiB and the compressed file is 500 MiB.
I find it hard to believe it is really a memory problem.
Also, once or twice it succeeded on file creation (when MaxMemoryPerShellMB was set to 4000). But most times it fails.
What can I do?

I was getting the exact same error in 2022:.
Exception calling "Write" with "3" argument(s): "Exception of type
'System.OutOfMemoryException' was thrown."
At C:\WINDOWS\system32\WindowsPowerShell\v1.0\Modules\Microsoft.PowerShell.Arch
ive\Microsoft.PowerShell.Archive.psm1:820 char:29
+ ... $destStream.Write($buffer, 0, $numberOfBytesRead)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : OutOfMemoryException
OutOfMemoryException Microsoft.PowerShell.Archive.psm1
I was able to resolve it very simply after a bit of thinking.
I too doubted that it was really a memory problem, since I have 16 GiB of RAM and it was showing only around 9 GiB in use.
Microsoft Scripting Guy Ed Wilson has written an article Learn How to Configure PowerShell Memory, and for some this may provide the solution.
In my case it did not, as PS appeared to be already configured to use the maximum available memory.
I was getting the issue on a folder I normally zip up every few days. This folder is over 11 GiB and zips down to around 4 GiB. This had previously been working for years.
However, thinking about it, to create a zip of this size I think it's likely that PS holds a significant amount of data in memory, more and more right up to the point when it commits it to the file system at the end. And I realized that although the computer has 16 GiB of RAM and was showing only around 9 GiB in use, 9 GiB is an unusually large amount of memory to be in use on that computer. Subtracting memory used by Windows, graphics etc still left several GiB free—but perhaps not enough for PS to create a large zipfile.
Sure enough, after a reboot to release the unusually large amount of RAM that had been in use, the process ran successfully and created my zipfile as usual.
In summary:
Check whether you can configure PS to use more RAM;
Check in Task Manager to see if you have less RAM free than usual;
Reboot to make maximum RAM available to PS.

It seems that the built-in Zip module of PowerShell is quite limited and designed for simple straightforward tasks. One of those limitations is that the max file size is 2GB. Also, the way that it obtains memory seems not very efficient. For example, if you try to zip files by Winzip or WinRar using Windows UI, it will probably work. More info about the underlying library https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.ziparchive
So, I recommend using 7Zip4Powershell library which worked perfectly for me with the same files/ Windows memory etc.

Related

Powershell Exception: Not enough quota is available to process this command

I am running a simple cmdlet with Powershell 5.1, winver 1803.
I am running:
Rename-Computer -ComputerName $pc -NewName $newName -DomainCredential $cred -Restart
This command is part of a script. Everything in the script works - and this line used to work, but for some reason it stopped.
The exception is:
Fail to rename computer '$pc' to '$newName' due to the following
exception: Not enough quota is available to process this command.
There are no memory or page-file size issues. There are no other applications even running. Page file size is in excess of 8GB.
WinRM is running, stack 3.0.
Why on earth is this command producing this error? How might I troubleshoot it?
UPDATE
This is what I am seeing...
Rename-Computer : Fail to rename computer 'W4000100' to 'W1401-TR100'
due to the following exception: Not enough quota is available to
process this command. At line:2 char:9
+ Rename-Computer -ComputerName $pc -NewName $newName -DomainCr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (W4000100:String) [Rename-Computer], InvalidOperationException
+ FullyQualifiedErrorId : FailToRenameComputer,Microsoft.PowerShell.Commands.RenameComputerCommand
Rename-Computer : Fail to rename computer 'W4000100' to 'W1401-TR100'
due to the following exception: Not enough quota is available to
process this command. At line:2 char:9
+ Rename-Computer -ComputerName $pc -NewName $newName -DomainCr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (W4000100:String) [Rename-Computer], InvalidOperationException
+ FullyQualifiedErrorId : FailToRenameComputer,Microsoft.PowerShell.Commands.RenameComputerCommand
Again, this same message pops up if you try to rename a computer locally via the GUI, and also happens if I remove the hyphen from the name, etc.
After researching, I believe this solution may solve your issue from the following article by Phil Coutard:
http://blog.coultard.com/2012/01/fix-windows-error-0x80070718-not-enough.html
This might be set on the user level. Try going to Control Panel, Sync Center, Offline Files, Manage Offline Files (left hand side), Disk Usage tab, Change Limits. It could be that your Disk Usage has a limit. Try that first and see if that fixes it.
UPDATE:
If that doesn't work, since the error is so generic, I would recommend using Microsoft's Automatic diagnostic/repair tool: https://support.microsoft.com/en-us/help/17590/automatically-diagnose-and-repair-windows-file-and-folder-problems
The answer after troubleshooting with MS is that the image used for these systems was domain-joined at the time of capture. This results in each machine having the same AccountDomainSID, which apparently can cause many issues - however, this is the only issue we have identified as a result.
MS have pretty much stopped researching with me and say this is the cause and that the only fix is to remove from domain and rejoin.

BizTalk 2016 wmi query failing

In our Powershell deployment scripts we terminate inflight instances identified by the following query:
get-wmiobject -namespace Root\MicrosoftBizTalkServer -query "SELECT * FROM MSBTS_ServiceInstance WHERE (ServiceClass = 1 OR ServiceClass = 64) AND AssemblyName LIKE 'Our.AssemblyName'"
For some reason this has stopped working on a Windows 2016 server, failing with this message:
get-wmiobject : An internal failure occurred for unknown reasons.
At line:1 char:1
+ get-wmiobject -namespace Root\MicrosoftBizTalkServer -query "SELECT * ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : GetWMICOMException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
Some searching has pointed to recent OS security patches. We uninstalled the KB mentioned from all nodes.
The above query runs without failure on 2 nodes in one environment and 1 node in another. This one box still gives the above error. Not sure what caused the original problem but maybe the uninstall did not clean up properly.
Any ideas where to start looking to fix the problem? I was thinking maybe installing the patch again and uninstalling it to make sure it cleans up properly. It takes about 4 hours for the VM to boot after the uninstall so testing such theories take a long time.
Turns out we have auto patching that kept re-applying the patch. What added to the confusion was the patch number being different for each OS and then there is the 4 hour thing that made it really difficult to poke the issue.
On 2016 it is KB4345418 that is causing the problem.

Can't get sector size of VHDX changed?

I have been hopelessly trying to change the sector size of a freshly created Windows 10 VHDX file, to 4096 bytes per sector.
After searching the net and trying things, this comes closest (using Windows 10):
Install Hyper-V
Select Start button and type Powershell
Right mouse click "Run as Administrator"
Type command: Set-Vhd -Path 4Kn.vhdx –PhysicalSectorSizeBytes 4096
The latter command has been tried in all possible flavors, with full path, just the filename (after CD'ing to the folder) etc.
I always get errors:
Set-Vhd : The operation on computer 'DESKTOP-JCMNHRV' failed: Invalid class
At line:1 char:1
+ Set-Vhd -Path C:\Users\Peter\Desktop\4Kn.vhdx –PhysicalSectorSizeByte ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Set-VHD], VirtualizationException
+ FullyQualifiedErrorId : Unspecified,Microsoft.Vhd.PowerShell.Cmdlets.SetVhd
Any idea what to do or where to start? I don't see it anymore
The .vhdx is not attached, and I tried without any formatting inside, and later with an NTFS formatted volume.

Random errors while doing Enter-PSSession in powershell

I have setup lots of Powershell scripts on my WIndows 2008 R2 server. The scripts do lots of processing (data crunching, executing SQLCMD.exe, bcp.exe etc). All of these scripts work without issues.
I am trying to call and execute the scripts from a remote laptop (within the same network) using the following command:
Enter-PSSession -ComputerName sun -ConfigurationName myprofile
The "myprofile" currently has just one function that will change directory to c:
This allows me to execute the scripts from my local laptop, however, they "run" on the server. That is my understanding.
However, I have not seen any scripts execute fully. At random intervals, the scripts fail with the below error messages... Once again, I have never seen these errors when I am trying to run the scripts on the server itself.
Any inputs on how to "fix" these errors? Any settings that I need to do on the "client" in terms of memory allocation?
a.
Processing data for a remote command failed with the following error message: Not enough storage is available to complete this operation. For more information, see the about_Remote_Troubleshooting Help topic.
b.
Get-Content : Exception of type 'System.OutOfMemoryException' was thrown.
At E:\automation\mssql-upload.ps1:144 char:14
+ (get-content <<<< $PipeFile -ReadCount 1000) | set-content $FinalFile
+ CategoryInfo : InvalidOperation: (:) [Get-Content], OutOfMemoryException
+ FullyQualifiedErrorId : ProviderContentReadError,Microsoft.PowerShell.Commands.GetContentCommand
c.
[Microsoft] [ODBC Driver Manager] Driver's SQLAllocHandle on SQL_HANDLE_ENV
d.
Processing data for a remote command failed with the following error message: The WSMan provider host process did not return a proper response. A provider in the host process may have behaved improperly. For more information, see the about_Remote_Troubleshooting Help topic.
It is likely your remote session is bumping up against the WS-Man quota MaxMemoryPerShellMB. You can see the current value by executing this command on the remote machine:
Get-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB
You can set a new value like so:
Set-Item WSMan:\localhost\Shell\MaxMemoryPerShellMB 512 -Force
This sets the value at 512MB. Set it to a value that works for your application.

Unzip with Powershell doesn't work on XP

I got the Request to unzip a .zip file with Powershell. On the Internet i found the following code multiple times:
param( [String]$newlocation, [String]$filepath)
if(($newlocation -and $filepath) -and ((test-path $newlocation) -and (test-path $filepath)))
{
Copy-Item $filepath $newlocation
$shell_app=new-object -com shell.application
$filename = $filepath.split("\")[-1]
if(Test-Path "$newlocation\$filename")
{
$zip_file = $shell_app.namespace("$newlocation\$filename")
$destination = $shell_app.namespace($newlocation)
$destination.Copyhere($zip_file.items())
}
}
As I implemented it into my script it changed a little bit. This above is the changed version. Now I've got an error:
Exception calling "NameSpace" with "1" argument(s): "The system cannot find the file specified. (Exception from HRESULT
: 0x80070002)"
At Z:\MyScripts\deploy.ps1:34 char:34
+ $zip_file = $shell_app.namespace <<<< ("$newlocation\$filename")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
And then another one, that is quite clear (caused by the first error
You cannot call a method on a null-valued expression.
At Z:\MyScripts\deploy.ps1:36 char:39
+ $destination.Copyhere($zip_file.items <<<< ())
+ CategoryInfo : InvalidOperation: (items:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
The File and the destination Path both exist and I've got rights to acces them (I created both). I'm running on Windows XP with PowerShell 2.0
Major Minor Build Revision
----- ----- ----- --------
2 0 -1 -1
Here is my entire dump from Powershell when I run it directly on the console.
I hope you guys can help me or at least tell me where I can go to find an answer.
I tried already to unzip the zip file manually and it worked, I have got access to both, the file and the file path (as I created both).
I've found this one on the web:
Also the code looks to me like it's dependent on the Windows Explorer support for zipFolders, which you may have turned off
Unregister (disable) XP Zip folders
REGSVR32 /u C:\Windows\System32\zipfldr.dll
Register (enable) XP Zip folders
REGSVR32 zipfldr.dll
It's from here.
I came to it during testing my script on several machines, e.g. on a Windows Server 2008 and on a Windows 7 client. Both worked, so I came to the conclusion that it's not my script,but it's my PC. After the registration of XP Zip folders, it worked.
Many thanks to the guy who wrote this one, I dumped too much time into this problem.
You might be running into a problem with accessing the COM objects. If you are using 64-bit windows, make sure you execute your script from a 64-bit powershell.exe. This means the powershell.exe in c:\windows\system32...\v1.0.... This was counter-intuitive for me, having the '32' in system32. I was executing powershell from Console2, which was a 32bit process, and was therefore launching 32-bit powershell (from c:\windows\syswow64...). Also make sure your powershell.exe is being run with administrator privileges.
Instead of trying to automate the Windows Shell, now in .NET Framework 4.5 there is a ZipFile class that you can use like this:
[System.Reflection.Assembly]::LoadWithPartialName('System.IO.Compression.FileSystem')
[System.IO.Compression.ZipFile]::ExtractToDirectory($sourceFile, $targetFolder)
Edit: Oops, .NET Framework 4.5 is not supported on Windows XP.
Anyhow, this answer might still prove useful for anyone else with ZIP problems in Powershell…