Powershell ignore errors, when zipping files - windows

I'm trying to zip specific files however on some files powershell breaks due to the charachter limit of 256, I know I can can alter this y changing registry keys. But I kind of want to ignore this error and write it to a file and zip this error file into the created archive.
However it seems whenever I run this code and an errors appears it does not continue with the code but rather breaks it midway.
If anyone could help it would be much appriciated.
Here is the code:
try { Add-Type -assembly "system.io.compression.filesystem";
[io.compression.zipfile]::CreateFromDirectory('C:\Windows\Temp\XYZ\directoryToZip',
'C:\zippedXYZ.zip')}
catch { Write-Output $_ | Out-File -Append -FilePath C:\Windows\Temp\XYZ\Error.txt;
Compress-Archive -Update C:\Windows\Temp\XYZ\Error.txt C:\zippedXYZ.zip}

Related

Windows PowerShell - Input file name, output file path

I've just started using PowerShell and I have a task where I need to be able to have the file path displayed on screen when I enter the file name.
Is there a script that allows me to do the below ? :
Ex 1: I enter "test.txt" and I get "C:\Program Files...."
Ex 2: I enter a file name "My Documents" and I also get its path.
I have searched online on how to do this but I didn't quite find what I was looking for and all the queries/answers were too complicated for me to understand.
Can anyone help me out, please?
Thanks in advance!
Here is a starter sample for you.
This example search only within the confine of the paths present is the Path system environment variable. It also only looks for files and do not recurse through these path.
So anything you could access directly from the command line should be available to you through it.
Now, if you want to search the whole drive, you could replace the $DefaultPaths assignment with Get-ChildItem -Path 'C:' -Recurse but doing that each time won't be super efficient.
You could do it and it will work... but it will be slow.
To search on the whole drive or whole filesystem, there are alternative methods that might work better. Some examples of what might entice:
Using a database which you have to buld & maintain to index all the files so that when you search, results are instantaneous and / or very fast
Parsing the MFT table (if using Windows / NTFS filesystem only) instead of using Get-ChildItem (This is not somehting natively doable through a simple cmdlet though) .
Relying on a third party software and interface with (For example, Void Tools Everything search engine already parse MFT and build its own database, allowing users to search instantly through a Windows NTFS filesystem. It also have its own SDK you can plug in through Powershell and retrieve what you seek instantly. The caveats is that you need the software installed first for that solution to work.)
Example: Searching through all paths defined in the Path variable
# What you are looking for. Accept wildcards characters (*)
$Filter = 'notepad.exe'
# Get the System Environment Path variable in an array
$DefaultPaths = $env:Path -split ';'
$Paths =
Foreach ($P in $DefaultPaths) {
# Search for files matching the specified filter. Ignore errors (often if the path do not exist but is sin the Path)
$MatchingFiles = Get-ChildItem -Path $P -Filter $Filter -File -ErrorAction SilentlyContinue
if ($MatchingFiles.count -gt 0) {
$MatchingFiles.Directory.FullName
}
}
$Paths | out-string | Write-Host -ForegroundColor Cyan
Output for Notepad.exe search using this method.
C:\Windows\system32
C:\Windows

script that searches for word documents (.rtf) and change the resolution of the images

I need an script that searches in a folder for word documents (.rtf) and change the resolution of the images. The problem is that I have a lot of .rtf files that are taking a lot of space because they have high resolution images. If I change the resolution of the images the file reduces it space about 97%. Please help me.
Thank you.
Unfortunately, there is no programmatic way to do "Select Image > Picture Format > Compress Pictures". It might be worth setting up an AutoHotKey script to run through your files.
If your rtf files were originally created in word, they likely saved two copies of each image (original file and huge uncompressed version). You can change this behavior by setting ExportPictureWithMetafile=0 in the registry, then re-saving each file. This can be done with a script, for example:
# Set registry key: (use the correct version number, mine is 16.0)
Try { Get-ItemProperty HKCU:\SOFTWARE\Microsoft\Office\16.0\Word\Options\ -Name ExportPictureWithMetafile -ea Stop}
Catch { New-ItemProperty HKCU:\SOFTWARE\Microsoft\Office\16.0\Word\Options\ -Name ExportPictureWithMetafile -Value "0" | Out-Null }
# Get the list of files
$folder = Get-ChildItem "c:\temp\*.rtf" -File
# Set up save-as-filetype
$WdTypes = Add-Type -AssemblyName 'Microsoft.Office.Interop.Word, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' -Passthru
$RtfFormat = [Microsoft.Office.Interop.Word.WdSaveFormat]::wdFormatRTF
# Start Word
$word = New-Object -ComObject word.application
$word.Visible = $False
ForEach ($rtf in $folder) {
# save as new name temporarily (otherwise word skips the shrink process)
$doc = $word.documents.open($rtf.FullName)
$TempName=($rtf.Fullname).replace('.rtf','-temp.rtf')
$doc.saveas($TempName, $RtfFormat)
# check for success, then delete original file
# re-save to original name
# check for success again, then clean up temp file
if (Test-Path $TempName) { Remove-Item $rtf.FullName }
$doc.saveas($rtf.FullName, $RtfFormat)
if (Test-Path $rtf.FullName) { Remove-Item $TempName }
# close the document
$doc.SaveAs()
$doc.close()
}
$word.quit()
I made some default word files with a 2mb image, saved as rtf (without the registry change), and saw the rtf files were a ridiculous 19mb! I ran the script above, and it shrunk them down to 5mb.

Unable to copy item from mapped network drive using powershell as file contains wierd characters

I am trying to copy files from mapped network drive.Some of them gets copied but others are not copied as filename has got some wierd characters.
for example my mapped network drive Z: contains the following files:
skifteretsattest 1(1).pdf
MailBody.msg
k�rekort terje(3).pdf
I am able to copy first two files from mapped network drive but not the last one using the below command
Copy-Item -LiteralPath Z:\$name -Destination I:\Dat\SomePath\ss/ -Force
The error which I get is:
Copy-Item : Could not find file 'Z:\k�rekort terje(3).pdf
I tried [WildcardPattern]::Escape($name) but that also did not work
Kindly help if anybody knows the solution
Maybe you could use robocopy.exe oder xcopy.exe instead?
Maybe old "dir /x" can help to find out the old "8.3" filename (like "GET-GP~1.PS1" for "Get-GPProcessingTime.ps1") and this can be used to copy or rename the file?
I also remember something about bypassing file system logic using unc-like syntax like \\0\driveletter\directory or whatever - unfortunately I don't remember the exact syntax. Maybe someone else does?
Try something like this:
$files = Get-ChildItem -Path "Z:\"
$files | % { Copy-Item -Destination "I:\Dat\SomePath\ss" }

Edit js file in postbuild event

I have post build events set up already for copying files for me dependent on ConfigurationName and want to be able to set an "environment variable" in a config (js) file on client side of an angular application to allow debug info to be visible or not dependent upon environment running application in.
To this end I've created a powershell script (ReplaceText.ps1):
function replace-file-content([String] $path, [String] $replace, [String] $replaceWith)
{
(Get-Content $path) | Foreach-Object {$_ -replace $replace,$replaceWith} | Out-File $path
}
and added this line to the post build event of my web project.
if "$(ConfigurationName)"=="LIVE" (powershell -File "$(ProjectDir)Tools\ReplaceText.ps1" "$(ProjectDir)app\application.config.js" "DEBUG" "LIVE")
which I was hoping to change the word "DEBUG" to "LIVE" when built against LIVE build configuration in my application.config.js file which contains this line:
$provide.constant('currentEnv', 'DEBUG');
Build succeeds but no changes occur on my file. Can anyone identify where I'm going wrong?
I do know I could do this sort of stuff with Gulp or another task runner BTW, but was trying to do it without bringing in another dependency and just use VS post build events & PS. :)
Cheers
Your PS code only defines a function but there's nothing that invokes it.
Use param as the first statement in the script to convert command line into the script's parameters:
param([String] $path, [String] $replace, [String] $replaceWith)
(Get-Content -literalPath $path -raw) -replace $replace, $replaceWith |
Out-File $path -encoding UTF8
-literalPath - correctly handles paths with [] symbols otherwise interpreted as a wildcard;
-raw - reads the entire file as one string for speedup, available since PowerShell 3.

Windows Batch script to read pom.properties file within .jar

I'm looking for a simple way to read the 2nd line of the pom.properties file that is placed within the META-INF folder of a compiled .jar. (see here: http://maven.apache.org/guides/getting-started/index.html#How_do_I_add_resources_to_my_JAR). I often need to know the date in that file and it's just a pain to have to open the jar every time and dig down into it. I want a Windows batch script that I can run via right-clicking on a .jar (so I'll need help with the Windows registry command as well). The result of the batch command can just be displayed in a cmd window (a nice bonus would be the value being copied to the clipboard, too).
In short: I want to be able to right-click on a .jar file in Windows Explorer > select 'Get Maven Generated Date' (or whatever) > and have the 2nd line of the pom.properties file printed to the console (and copied to the clipboard).
I know this can't be too hard, I just don't know quite what to look for :).
Thanks in advance for any help.
Note that .NETv4.5 is required to use the System.IO.Compression.FileSystem class.
Add-Type -As System.IO.Compression.FileSystem;
$sourceJar = <source-jar-here>;
$jarArchive = [IO.Compression.ZipFile]::OpenRead($sourceJar).Entries
try
{
foreach($archiveEntry in $jarArchive)
{
if($archiveEntry.Name -like "*pom.properties")
{
$tempFile = [System.IO.Path]::GetTempFileName()
try
{
[System.IO.Compression.ZipFileExtensions]::ExtractToFile($archiveEntry, $tempFile, $true)
$mavenDate = Get-Content $tempFile -First 2
Write-Host $mavenDate
}
finally
{
Remove-Item $tempFile
}
}
}
}
finally
{
$jarArchive.Dispose
}

Resources