Bulk Append File Names with numbers with cmd - windows

How can I batch append a directory of files using the window cmd so that they change from.
"file1"
"file2"
"file3"
to
"001 file1"
"002 file2"
"003 file3"

If you're willing to PowerShell instead of batch, you could do this as a one-off:
gci |% { ren $_ (('{0:d3} ' -f $i++) + $_.Name) }
Which is more fully written as:
$counter = 0
Get-ChildItem | ForEach-Object {
$prefix = '{0:d3}' -f $counter++
Rename-Item -Path $_.FullName -NewName "$prefix $($_.Name)"
}

Related

I can't access Simbolic Links remotely

I have created the following powershell script that copies the files from the source folder and moves them to the destination folder, and instead of these moved files it creates symbolic links for these files.
I have given all possible sharing permissions and locally it works perfectly and I can open these files but when I try to do it remotely it doesn't open the files, I can see them but they don't open.
> $sourceDir = "C:\sorce"
> $destinationDir = "D:\Destiny"
> $logfile = "C:\Temp\log.txt"
> Copy folder structure to destination
> Get-ChildItem -Path $sourceDir -Recurse |
> ?{ $_.PSIsContainer } |
> Copy-Item -Destination {Join-Path $destinationDir $_.Parent.FullName.Substring($sourceDir.length)} -Force -ErrorAction Continue
>
> Move files and folders to destination
> `$items = Get-ChildItem $sourceDir -Recurse
> foreach ($item in $items)
> {
> $filename = Split-Path -Path $item.FullName -Leaf
> $sourcepath = Split-Path -Path $item.FullName
> $destination = ($item.FullName -replace [regex]::Escape($sourceDir), $destinationDir)
> Move-Item -Force -Path $item.FullName -Destination $destination -Verbose -ErrorVariable err -ErrorAction Continue *>> $logfile
> $err >> $logfile
>
> Create symbolic link in original location
> New-Item -ItemType SymbolicLink -Path $sourcepath -Name $filename -Value $destination -Force -Verbose -ErrorVariable err -ErrorAction Continue *>> $logfile
> $err >> $logFile
> }
Open the files remotely

PowerShell - Print Move-Item in Console

I have the following code:
$SchoolFolder = "C:\Users\MyUser\Desktop\School Folder\$StudentName\$Month. $MonthWrite\$Day. $DayWrite"
$MP4Lenght = (Get-ChildItem -Path $RenderFolder).Length -ne "0"
$MP4existsToCopy = Test-Path -Path "$RenderFolder\*.mp4"
If (($MP4existsToCopy -eq $True) -and ($MP4Lenght -eq $True)) {
Get-ChildItem $MyFolder |
Where-Object { $_.Length -gt 0KB} |
Move-Item -Destination (new-item -type directory -force ($SchoolFolder + $newSub)) -force -ea 0
Write-Host "Done!"
}
I would like to know how do I make all correspondence in $MP4Lenght be printed in the console with the format $MP4Lenght + "was moved", because that way I can know which files were moved.
Your "exist to copy" logic isn't really required, because if the file doesn't exist then get-childitem is not going to find it. Similarly with the check if MP4lenght is true.
The following will check if the file does not exist in the source and does exist in the destination and if that is true then write to the host that the file has moved:
$source = 'C:\Users\myuser\playground\powershell\Source\'
$destination = 'C:\Users\myuser\playground\powershell\Destination'
$files = Get-ChildItem $source -File | where-object {$_.Length -ne 0}
foreach ($file in $files) {
Move-Item $file.FullName -Destination .\Destination
if (-not(Test-Path $file.FullName) -and (test-path (Join-Path -Path $destination -ChildPath $file.Name))) {
Write-Host "$($file.name) has moved"
}
}
Why not just use -verbose?
Move-Item -Destination (new-item -type directory -force ($SchoolFolder + $newSub)) -force -ea 0 -Verbose
Update as per your comment.
Try it this way...
$source = 'C:\Users\myuser\playground\powershell\Source\'
$destination = 'C:\Users\myuser\playground\powershell\Destination'
Get-ChildItem $source -File |
where-object {$PSItem.Length -ne 0} |
ForEach-Object{
Move-Item $PSItem.FullName -Destination '.\Destination'
if (-not(Test-Path $PSItem.FullName) -and (test-path (Join-Path -Path $destination -ChildPath $PSItem.Name))) {
"$($PSItem.name) has moved"
}
}
Final script:
$StudentName = Tyler
$RenderFolder = "C:\Users\MyUser\Desktop\Render"
$MP4existsToCopy = Get-ChildItem $RenderFolder -File | where-object {$_.Length -ne 0}
$SchoolFolder = "C:\Users\MyUser\Desktop\School Folder\$StudentName\$Month. $MonthWrite\$Day. $DayWrite"
foreach ($file in $MP4existsToCopy) {
Move-Item $file.FullName -Destination (new-item -type directory -force ($SchoolFolder)) # new-item - Serves to create the folder if it does not exist
if (-not(Test-Path $file.FullName) -and (test-path (Join-Path -Path $SchoolFolder -ChildPath $file.Name))) {
Write-Host "$($file.name) was moved!"
}

Compress and Delete multiple folders one by one

Ho Guys,
I was trying a powershell script which can compress and delete the subfolders with folder name of 8 numbers.
The script is working fine. But the problem is the script works like, first the whole compression process gets done and then goes for the whole deletion. So that if am running this script through 1tb folder...During the compression process it goes upto 1.5tb . To overcome this, how can I change the script so that the script should compress and delete one folder and moves to next folder compress and delete and so on.
Here is what I tried.
$path = Read-host "Enter the desired path"
$directory = "$path"
Add-Type -AssemblyName System.IO.Compression.FileSystem
$folders = Get-ChildItem $directory -recurse | Where-Object {$_.PSIsContainer -eq $true -and $_.Name.Length -ge "8" -and $_.Name -match '^\d+$'} | Select-Object -ExpandProperty FullName
foreach ($folder in $folders) {
Write-Verbose "Archiving $archive"
$archive = $folder + '.zip'
[System.IO.Compression.ZipFile]::CreateFromDirectory($folder, $archive, 'Optimal', $True) | wait-process
}
Foreach-Object {
Remove-Item -Path $folders -Force -Recurse -Confirm:$false -Verbose
}
What about this?
$path = Read-host "Enter the desired path"
$directory = "$path"
Add-Type -AssemblyName System.IO.Compression.FileSystem
$folders = Get-ChildItem $directory -recurse | Where-Object {$_.PSIsContainer -eq $true -and $_.Name.Length -ge "8" -and $_.Name -match '^\d+$'} | Select-Object -ExpandProperty FullName
foreach ($folder in $folders) {
Write-Verbose "Archiving $archive"
$archive = $folder + '.zip'
[System.IO.Compression.ZipFile]::CreateFromDirectory($folder, $archive, 'Optimal', $True)
Remove-Item $folder -recurse -force
}

Update Host file to update last entry based on Hostname

For some reason, one of our customers has a lot of problems connecting to our ftp, main reason being that he cant resolve our hostname (via IP no problem)
I've been looking around and found this code to add a line to the bottom of my host file (but its not working, just outputs the host file in its entirety)
Can someone explain how I can change this? It is fetching the IP perfectly, just need to either delete the non commented lines on host file or delete the last IP
$targethost="HOSTNAME"
$dnsserver="8.8.8.8"
$pattern = '^*' + $targethost + '.*$'
$file = "$($env:SystemRoot)\System32\drivers\etc\hosts"
$ip = Resolve-DnsName -Name $targethost -Type A -DnsOnly -Server $dnsserver
$hosts = Get-Content -Path $file
$hosts = $hosts | Foreach {
if ($_ -match $pattern)
{
$ip.IpAddress + " HOSTNAME "
}
else
{
# Keep current line
$_
}
}
#Uncomment this line to just view the output, no harm is done to the hosts file.
$hosts
# Uncomment this line to actually write the hosts file. Elevated privileges required.
#$hosts | Out-File $file -enc ASCII
Try
$hosts | Out-File -Encoding Ascii -append $file
or
$hosts | Add-Content $file #(ASCII by default)
A janky one, but it works
Clear-Content c:\windows\System32\drivers\etc\hosts
Set-Content -Path c:\windows\System32\drivers\etc\hosts -Value "Hello, World"
$targethost="HOSTNAME"
$dnsserver="8.8.8.8"
$pattern = '^*' + $targethost + '.*$'
$file = "$($env:SystemRoot)\System32\drivers\etc\hosts"
$ip = Resolve-DnsName -Name $targethost -Type A -DnsOnly -Server $dnsserver
$hosts = Get-Content -Path $file
$hosts = $hosts | Foreach {
if ($_ -match $pattern)
{
# Keep current line
$_
}
else
{
$ip.IpAddress + " HOSTNAME "
}
}
#Uncomment this line to just view the output, no harm is done to the hosts file.
$hosts
# Uncomment this line to actually write the hosts file. Elevated privileges required.
$hosts | Out-File $file -enc ASCII

Reading a file line-by-line / field-by-field (pipe-delimited) in powershell

Actually beginner in PowerShell. I want to convert shell script into powershell.
I have sample.txt file which contains 3 lines. I want to select each word in line to different variable and which variables are need to use in next if condition.
get-content sample.txt
wordone|secondword|thridword|fourthword
wordone1|secondword1|thridword1|fourthword1
wordone2|secondword2|thridword2|fourthword2
I have already shell script:
grep "^[^#]" ./sample.txt > test.txt
for line in `cat test.txt`
do
dir=`echo $line | cut -d'|' -f1`
metadata_name=`echo $line | cut -d'|' -f2`
metadata_file=`echo $line | cut -d'|' -f3`
config_file=`echo $line | cut -d'|' -f4`
if [ "${config_file}" != "" ]
then
cp ${dir}.xml folder1/.
Please help me how to convert shell to powershell.
Is this what you are looking for?
$textfile = get-content "sample.txt"
$sample = "sample.txt"
for ($i=0;$i -lt $textfile.count;$i++){
$textrow = ($textfile[$i]).split("|")
$dir = $textrow[0]
$metadata_name = $textrow[1]
$metadata_file = $textrow[2]
$config_file = $textrow[3]
If($config_file -ne ""){
New-Item $dir/ConfigurationPlan -type directory -force
$sample | Out-File "$dir/ConfigurationPlan/$($config_file)_sample.xml"
}
}
I'd treat your .\sample.txt file as a csv file and use Import-Csv with -Delimiter '|' and -Header dir,metadata_name,metadata_file,config_file parameters.
Then iterate the lines checking for dir and existence of the file to copy.
$Sample = Import-Csv sample.txt -delimiter '|' -Header dir,metadata_name,metadata_file,config_file
$Sample
"----"
ForEach ($Line in $Sample){
if ($Line.config_file -ne ""){
$File = "$($line.dir).xml"
"config_file is $($Line.config_file) checking $File"
if (Test-Path $File){
Copy-ITem -Path $File -Destination "folder1\" -whatif
}
}
}
Sample output:
> Q:\Test\2017\07\21\SO_45239319.ps1
dir metadata_name metadata_file config_file
--- ------------- ------------- -----------
wordone secondword thridword fourthword
wordone1 secondword1 thridword1 fourthword1
wordone2 secondword2 thridword2 fourthword2
----
config_file is fourthword checking wordone.xml
config_file is fourthword1 checking wordone1.xml
config_file is fourthword2 checking wordone2.xml
If your output looks OK, remove the -WhatIf parameter of Copy-Item

Resources