Create a Timestamped ZIP Archive from Windows Command Prompt - windows

I've made a simple script to create a timestamped zip archive using a combination of PowerShell and a DOS command, but is there a better way to do this just using a single PowerShell command with piping?
FOR /F "tokens=* USEBACKQ" %%F IN (`powershell get-date -format "{yyyymmdd-HHmmss}"`) DO (
SET ARCHTIMESTAMP=%%F
)
powershell Compress-Archive -Path yourpath -DestinationPath yourdestpath\yourname-%ARCHTIMESTAMP%.zip

You're incredibly close with what you have here. Just drop the get-date in where you're creating the string for your destination path.
Compress-Archive -Path yourpath -DestinationPath "yourdestpath\yourname-$(get-date -format "{yyyyMMdd-HHmmss}").zip"

Related

CMD Dir : i can use * instead subfolder

This is my tree:
f:\mega\user1\rubbish\
f:\mega\user2\rubbish\
f:\mega\user3\rubbish\
.....
f:\mega\usern\rubbish\
I would like (ONLY) list all files inside the various "rubbish" folders.
I tried without success this command:
DIR F:\mega\*\rubbish\
Any suggestions?
Try this from a cmd.exe prompt.
powershell -NoLogo -NoProfile -Command ^
"Get-ChildItem -Directory -Path 'F:\mega\*\rubbish'"
Of course, it is easier in a PowerShell console or .ps1 file script.
Get-ChildItem -Directory -Path 'F:\mega\*\rubbish'
Or, possibly this to limit the names to 'user*' subdirectories.
Get-ChildItem -Directory -Path 'F:\mega\user*\rubbish'
To get only the fully qualified path to the files...
(Get-ChildItem -Directory -Path 'F:\mega\user*\rubbish').FullName
Wildcards can only be used in the last element of a path but not somewhere else.
You could however use a for /D loop to resolve the sub-directories:
for /D %I in ("F:\mega\user*") do #dir "%~I\rubbish"
To use that code in a batch file do not forget to double the %-signs:
for /D %%I in ("F:\mega\user*") do #dir "%%~I\rubbish"

Unable to execute PowerShell Script using 'Run with Powershell' option

Hi I wrote a simple powershell script to:
Create a IE shortcut to a site
Disable Mixed Code Security Verification for Java control panel
Add a few sites as trusted sites
The script runs fine when I manually copy and paste it into powershell.
However, when I save it as a .ps1 file and 'Run with Powershell' - it doesn't seemingly execute (changes aren't made).
I tried changing execution policy to Bypass but it still does not execute.
Any thoughts on how I can get the .ps1 script to execute by using 'Run with Powershell'?
This is so my users can simply run this script without having to copy and paste into powershell.
Thank you,
Asif
Here is the full script for reference:
& powershell.exe -executionpolicy bypass -file C:\Users\AZahir\Desktop\ps2.ps1
$Shell = New-Object -ComObject ("WScript.Shell")
$ShortCut = $Shell.CreateShortcut($env:USERPROFILE + "\Desktop\Jacada.lnk")
$ShortCut.TargetPath = "C:\Program Files (x86)\Internet Explorer\iexplore.exe"
$ShortCut.Arguments = "http://facebook.com"
$ShortCut.WorkingDirectory = "C:\Program Files (x86)\Internet Explorer";
$ShortCut.WindowStyle = 1;
$ShortCut.IconLocation = "C:\Program Files (x86)\Internet Explorer\iexplore.exe"
$ShortCut.Save()
Add-Content -Path "$env:USERPROFILE\AppData\LocalLow\Sun\Java\Deployment\deployment.properties" -Value ('deployment.security.mixcode=DISABLE')
Set-Location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
Set-Location ZoneMap\Domains
New-Item bpoazusargdb01d
Set-Location bpoazusargdb01d
New-ItemProperty . -Name http -Value 2 -Type DWORD
Set-Location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
Set-Location ZoneMap\Domains
New-Item "172.30.1.3"
Set-Location "172.30.1.3"
New-ItemProperty . -Name http -Value 2 -Type DWORD
Set-Location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
Set-Location ZoneMap\Domains
New-Item "172.30.1.49"
Set-Location "172.30.1.49"
New-ItemProperty . -Name http -Value 2 -Type DWORD
Set-Location "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
Set-Location ZoneMap\Domains
New-Item "172.30.1.89"
Set-Location "172.30.1.89"
New-ItemProperty . -Name http -Value 2 -Type DWORD
Leaving my original answer below but I've since found a more effective way without the file copy:
# 2>NUL & #powershell -nop -ep bypass "(gc '%~f0')-join[Environment]::NewLine|iex" && #EXIT /B 0
This is to be included as your first line of the powershell script, saved as a .cmd file.
Breakdown:
# 2>NUL &
This handles the batch part of our file so we can get that click-execution functionality. Since # isn't a filename or command, it throws an error we ignore with 2>NUL and skip to the next command with &.
#powershell ...
This is our call to powershell, grabbing the contents of the file (gc: Get-Content) and executing them (iex: Invoke-Expression). We use # so the command isn't echoed to the cli.
&& EXIT /B 0
This will exit the script gracefully if no errors were thrown.
If your only goal is to have a shortcut-clickable link for users to run your powershell script, you can accomplish that with this by pasting your script contents under this header (saved as myscript.cmd or whatever you want to name it):
::<#
#ECHO OFF
REM https://stackoverflow.com/questions/3759456/create-a-executable-exe-file-from-powershell-script#answer-4629494
REM https://blogs.msdn.microsoft.com/zainala/2008/08/05/using-0-inside-the-batch-file-to-get-the-file-info/
SET "pwsh=%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\powershell.exe"
SET "args=-NoProfile -NoLogo -ExecutionPolicy Bypass -Command"
SET "cmd="#(Get-Content -Path '%~f0') -replace '^^::'^|Set-Content -Path '%~dpn0.ps1';. '%~dpn0.ps1' %*""
%pwsh% %args% %cmd%
DEL "%~dpn0.ps1" /Q /F
EXIT
::#>
Simply put, it handles the execution policy and saves itself as a powershell script after replacing the batch-parts as a block comment.
This is so my users can simply run this script without having to copy
and paste into powershell.
Use a bat file side by.
include
PowerShell.exe -executionpolicy bypass -file "%~dp0ps2.ps1"
Remove below from your powershel script.
& powershell.exe -executionpolicy bypass -file C:\Users\AZahir\Desktop\ps2.ps1
When a user double clicks the bat file, they will run the ps2.ps1.
I don't see errors , when i run it . It creates the shortcut and the reg keys. In case, if you are trying to run it second time, it will generate errors saying the reg keys exists..
Also its wise to use """ instead of " more details How to pass msi ArgumentList with $ScriptDir with spaces in powershell?
or else your users may find difficulties running your script, if they put this script in a path with space such as c:\new folder\

Copy all .jpg from subfolders to a single folder by cmd

I have a folder that has 148 folders in it, and in each of these folders they have a .jpg file. I need to get all these .jpg and put in a single folder
each folder is at least 1 .jpg
I can do this on Linux as well
`#!/bin/bash
for file in `find source -name * .jpg`;
of the mv "$ file" Destination;
done;
but I can not play this in Windows. Only the find command that I can reproduce the same result: dir /S /B *.jpg
for /r %f in (*.jpg) do move %f %destination%
Note: This is the interactive version. In a command script, you need to protect the %f's from too-early variable substitution.
for /r %%f in (*.jpg) do move %%f %destination%
Another way to do it using PowerShell. When you see that the files are being moved as you expect, remove the WhatIf from the Move-Item cmdlet.
Get-ChildItem -Recurse -File -Filter '*.jpg' |
ForEach-Object { Move-Item -Path $_.FullName -Destination 'C:\the\other\dir' -WhatIf }
You can run this in a cmd.exe shell or .bat script.
powershell -NoLogo -NoProfile -Command ^
"Get-ChildItem -Recurse -File -Filter '*.jpg' |" ^
"ForEach-Object { Move-Item -Path $_.FullName -Destination 'C:\the\other\dir' -WhatIf }"
The easiest way to achieve this is in Windows is to open to root folder with the Windows Explorer at which you want to start searching all the elements. Then go to the small input field for searching and enter *.jpg the result will show all the jpg in the root folder and all subfolders. Then you can simply copy and paste the files to your destination folder.

How to pass variable from Batch File to a Powershell Script

I have a batch file that copies user files from one computer to another networked computer.
#echo off
cls
#echo Type the old Computer Name
set /p asset=
REM robocopy.exe \\%asset%\c$\ C:\ /S /Z /XJD /XJ /XA:SH /XA:T /XD "Dir1" "Dir2" /XF *.dll *.log *.txt *.exe /log+:"\\server\path\%asset%-to-%computername%-Transfer.log" /NP /FP /V /TEE
PowerShell.exe -Command "& {Start-Process PowerShell.exe -ArgumentList '-ExecutionPolicy Bypass -File ""%~dpn0.ps1""' -Verb RunAs}"
pause
This is my PowerShell script:
$source = "\\${env:asset}\C$\Temp\Source"
$dest = "C:\Temp\Dest"
Write-Output $source
Read-Host "Press ENTER to quit"
I then need to call a PowerShell script that invokes an admin login, then pass the %asset% and %useraiu% variables.
I can't seem to figure out how to pass the %asset% and %useraiu% from my batch file to the PowerShell script.
I have found that if you are calling the Powershell script from a batch file and need to have the Powershell script run with admin, you would need to use this syntax.
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File """"%~dpn0.ps1"""" """"%asset%"""" ' -Verb RunAs}"
The PowerShell script name and parameters need to be wrapped in 4 double quotes in order to properly handle paths/values with spaces
This is the only solution that worked for me so far.

Bat script to retrieve folder size (windows)

I need to write a script .bat that give me the free space of a certain disk and the detail of all folders with the relative dimension and write it in a simple text file (just to check the distribution of used space).
Thanks a lot in advance!
dir /a /s | findstr /b /c:" " > file.txt
The FileSystemObject can do this for you. It is accessible from PowerShell (among other sources).
PowerShell -NoProfile -Command "$fso = New-Object -COMObject Scripting.FileSystemObject; Get-ChildItem YOUR_ROOT_DIRECTORY -Recurse -Directory | %% { $f = $fso.GetFolder($_.FullName); '{0},{1}' -f $f.Size,$_.FullName };"

Resources