PowerShell Delete File If Exists - powershell

Could you help me with a powershell script?
I want to check if multiple files exist, if they exist then delete the files.
Than provide information if the file has been deleted or information if the file does not exist.
I have found the script below, it only works with 1 file, and it doesn't give an message if the file doesn't exist.
Can you help me adjust this? I would like to delete file c:\temp\1.txt, c:\temp\2.txt, c:\temp\3.txt if they exist.
If these do not exist, a message that they do not exist. Powershell should not throw an error or stop if a file doesn't exist.
$FileName = "C:\Test\1.txt"
if (Test-Path $FileName) {
Remove-Item $FileName -verbose
}
Thanks for the help!
Tom

You can create a list of path which you want to delete and loop through that list like this
$paths = "c:\temp\1.txt", "c:\temp\2.txt", "c:\temp\3.txt"
foreach($filePath in $paths)
{
if (Test-Path $filePath) {
Remove-Item $filePath -verbose
} else {
Write-Host "Path doesn't exits"
}
}

Step 1: You want multiple files. You can do that two ways:
$files = "C:\file1.txt","C:\file2.txt","C:\file3.txt"
That would work, is cumbersome. Easier? Have all files in one .csv list, import that. Remember, the first row is not read, since its consider the header:
$files = Import-Csv "C:\yourcsv.csv"
Alright Step 2: now you got your files, now we want to cycle them:
Foreach ($file in $files) {
If (Test-Path $file) {
Remove-Item $file -verbose | Add-Content C:\mylog.txt }
else { Write-Host "$file not found" }}
Foreach loops take each individual "entry" in one variable and do whatever you want with them.
That should do what you want.

Related

Error on Move-Item moving home area to file server

This is the last section of my script that I use to transfer student leavers areas to an archive file server. The script runs and does everything as expected but still throws an error out saying
Move-Item : Cannot find path '\\domain\students$\E-J$\MH201507' because it does not exist. The script does find this path and moves the home area so I'm not sure why I get this error. Or is there any way to fix this or is it easier to hide the error somehow?
The CSV document contains a list of the sam account name and contains their home area location on the domain so it knows where to copy the path over from.
Any help would be massively appreicaited! Kind Regards
#Declaring the .csv file that contains a list of all leavers home directories.
$HomeDirectoryList = Import-CSV "C:\Scripts\Leavers\HomeDirectoryExport.csv"
$Username = $HomeDirectoryList.samAccountName
$HomeDirectory = $HomeDirectoryList.HomeDirectory
$Archive = "\\myfileserver.ac.uk\D$\21-22 Leavers"
ForEach ($Username in $HomeDirectoryList)
{
Move-Item -Path $HomeDirectory -Destination $Archive
}
Sample data with which the error occurs:
samAccountName HomeDirectory
WB214589 \\domain\students$\A-D$\WB214589
MH201507 \\domain\students$\E-J$\MH201507
You are setting the variable $HomeDirectory outside the loop, so that will contain an array of home directory paths.
Then you use variable $Username to iterate the data from the CSV file, but inside that loop you never use it.
Try:
$HomeDirectoryList = Import-CSV 'C:\Scripts\Leavers\HomeDirectoryExport.csv'
$Archive = '\\myfileserver.ac.uk\D$\21-22 Leavers'
foreach ($student in $HomeDirectoryList) {
Write-Host "Moving HomeDirectory folder for student '$($student.samAccountName)'"
Move-Item -Path $student.HomeDirectory -Destination $Archive -Force
}
If you need to catch errors happening, change the loop to:
foreach ($student in $HomeDirectoryList) {
Write-Host "Moving HomeDirectory folder for student '$($student.samAccountName)'"
try {
Move-Item -Path $student.HomeDirectory -Destination $Archive -Force -ErrorAction Stop
}
catch {
Write-Warning "Error moving homedirectory '$($student.HomeDirectory)':`r`n$($_.Exception.Message)"
}
}

Powershell Test-Path in loop, variable path

I started learning Powershell yesterday.
I want to write a script that run batches in multiple folders, however only if subfolder contain work_folder.
I have the following folder structure
*folder1
--work_folder
--script.bat
*folder2
--script.bat
*folder3
--script.bat
*test.ps1
powershell
cd C:\a\test\
Get-ChildItem -Path $PWD\*\script.bat | ForEach-Object {
if ( -not ( Test-Path $PWD\*\work_folder -PathType Container ) )
{
Write-host "Not exist"
return
} else {
Write-host "Exist"
}
& $_
}
If I use
powershell
$myPath = "$PWD\*\"
it will not work as I want.
Please give me a hint or example.
There's a couple problems with your code. Because you use the return keyword if the work_folder directory doesn't exist, your script ends entirely on the first folder it spots like this. I think you meant to use the continue keyword, which would skip to the next iteration of the loop.
Also, you were iterating on every instance of script.bat, when you should have been iterating on every directory containing script.bat.
You can write your code a lot cleaner if you do it this way:
(Get-ChildItem -Path $PWD -Directory).FullName | ForEach-Object {
if (Test-Path "$_/work_folder" -PathType Container)
{
Write-host "Exist"
& "$_/script.bat"
} else {
Write-host "Not exist"
}
}

Renaming folders from a list

I have a text file list of 56 folders that includes the full paths to a set of folders. I need to rename the folder at the end of the path.
Example:
Original: \this folder\needs to\move
New: \this folder\needs to\move.moved
I am totally new at powershell and trying to learn. I thought this might be a good way to start. Any help would be greatly appreciated.
# Get the content of the list
# in this case, a text file with no heading, and one path per line
$listContent = Get-Content $ENV:USERPROFILE\Desktop\list.txt
# Loop over each child folder and rename it
foreach($line in $listContent)
{
# check if the current path is valid
$pathTest = Test-Path -Path $line
if($pathTest -eq $True)
{
Write-Output "`nOld path: $($line)"
$newName = $line + ".moved"
Write-Output "New name: $newName"
try
{
# on success, write out message
Rename-Item -Path $line -NewName $newName -Force
# split the string from the file and get the data after the last \ for readability
Write-Output "`nSuccessfully changed directory name $($line.split('\')[-1]) to $newName"
}
catch
{
# on error, throw first error in the Error array
throw $Error[0]
}
}
else {
Write-Output "$($line) is not a valid path"
}
}
Write-Output "`nEnd of script!"

In Powershell, how do I copy/paste a file, if file already exists, to roll the new copy of the file?

I am running a powershell script, with the following
Copy-Item -Path c:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.config -Destination c:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG\machine.orig
If the machine.orig already exists, how can i make it copy it to machine.orig1, and if that already exists, machine.orgin2?
If I may make a suggestion. Personally, I like the idea of a date/time stamp on the file rather than an incremental number. This way you know when the file was backed up, and you're far less likely to run into confusion over the file. Plus the script code is simpler.
Hope this helps.
$TimeStamp = get-date -f "MMddyyyyHHmmss"
$SourceFile = Dir c:\folder\file.txt
$DestinationFile = "{0}\{1}_{2}.{3}" -f $SourceFile.DirectoryName, $SourceFile.BaseName, $TimeStamp, $SourceFile.Extension
copy-Item $sourcefile $DestinationFile
#let us first define the destination path
$path = "R:\WorkindDirectory"
#name of the file
$file = "machine.orgin"
#let us list the number of the files which are similar to the $file that you are trying to create
$list = Get-ChildItem $path | select name | where name -match $file
#let us count the number of files which match the name $file
$a = ($list.name).count
#if such count of the files matching $file is less than 0 (which means such file dont exist)
if ($a -lt 1)
{
New-Item -Path $path -ItemType file -Name machine.orgin
}
#if such count of the files matching $file is greater than 0 (which means such/similar file exists)
if ($a -gt 0)
{
$file = $file+$a
New-Item -Path $path -ItemType file -Name $file
}
Note: This works assuming that the names of the files are in series. Let us say using this script you create
machine.orgin
machine.orgin1
machine.orgin2
machine.orgin3
and later delete machine.orgin2 and re run the same script then it won't work.
Here i have given an example where i have tried to create a new file and you can safely modify the same to copy such file using copy-item instead of new-item

How many ways to check if a script was "successful" by using Powershell?

I am still very new and I have for example one script to backup some folders by zipping and copying them to a newly created folder.
Now I want to know if the zip and copy process was successful, by successful i mean if my computer zipped and copied it. I don't want to check the content, so I assume that my script took the right folders and zipped them.
Here is my script :
$backupversion = "1.65"
# declare variables for zip
$folder = "C:\com\services" , "C:\com\www"
$destPath = "C:\com\backup\$backupversion\"
# Create Folder for the zipped services
New-Item -ItemType directory -Path "$destPath"
#Define zip function
function create-7zip{
param([String] $folder,
[String] $destinationFilePath)
write-host $folder $destinationFilePath
[string]$pathToZipExe = "C:\Program Files (x86)\7-Zip\7zG.exe";
[Array]$arguments = "a", "-tzip", "$destinationFilePath", "$folder";
& $pathToZipExe $arguments;
}
Get-ChildItem $folder | ? { $_.PSIsContainer} | % {
write-host $_.BaseName $_.Name;
$dest= [System.String]::Concat($destPath,$_.Name,".zip");
(create-7zip $_.FullName $dest)
}
Now I can either check if in the parentfolder is a newly created folder by time.
Or i can check if there are zip folders in my subfolders I created.
What way would you suggest? I probably just know this ways, but there are a million way to do this.
Whats your idea? The only rule is , that powershell should be used.
thanks in advance
You could try using the Try and Catch method by wrapping the (create-7zip $_.FullName $dest) with a try and then catch any errors:
Try{ (create-7zip $_.FullName $dest) }
Catch{ Write-Host $error[0] }
This will Try the function create-7zip and write any the errors that many accrue to the shell.
One thing that can be tried is checking the $? variable for the status of the command.
$? stores the status of the last command run,
So for
create-7zip $_.FullName $dest
If you then echo out $? you will see either true or false.
Another option is the $error variable
You can also combine these in all sorts of ways (Or with the exception handling).
For example, run your command
foreach-object {
create-7zip $_.FullName $dest
if (!$?) {"$_.FullName $ErrorVariable" | out-file Errors.txt}
}
That script is more pseudocode for ideas than working code, but it should at least get you close to using it!