PowerShell Batch ConvertImage - powershell

I am working on a PowerShell function that will convert jpg to png. I got that to work. I cannot figure out how to get it to delete the original jpg file after finishing. I have attempted to use the del and remove command but cannot delete the original file because it is still being used in the process. I have also tried to end the process but it ended the whole process when I put it within the foreach loop. Is there a way to get it to end the process so the file can be deleted and then continue through the rest of the images? Below is the code that converts but does not delete. If there is a better way to do this I would like to know were I can improve. Thank you !
function ConvertImage{
param ([string]$path)
$path=Convert-Path . #path to files
if (Test-Path $path)
{
#Load required assemblies and get object reference
[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
foreach($file in (ls "$path\*.jpg")){
$convertfile = new-object System.Drawing.Bitmap($file.Fullname)
$newfilname = ($file.Fullname -replace '([^.]).jpg','$1') + ".png"
$convertfile.Save($newfilname, "png")
$file.Fullname
}
}
else
{
Write-Host "Path not found."
}
};ConvertImage -path $args[0]
How Do I use an integer with leading zeroes for the code below:
function ConvertImage{
param ([string]$path)
$Name = Read-Host -Prompt 'Input new name'
$Start = Read-Host -Prompt 'Input start number'
$Ext1 = Read-Host -Prompt 'Input Initial Extension'
$Ext2 = Read-Host -Prompt 'Input Ending Extension'
Write-Host "You input '$Name' and '$Start'"
Write-Host "You input '$Ext1' and '$Ext2'"
$i = "{0:D2}" -f [int]$Start
Get-ChildItem ("*.$Ext1") | %{Rename-Item $_ -NewName ("$Name"+"_"+"$i.$Ext1" -f $i++)}
Get-ChildItem ("*.$Ext2") | %{Rename-Item $_ -NewName ("$Name"+"_"+"$i.$Ext2" -f $i++)}
$path=Convert-Path . #path to files
if (Test-Path $path)
{
#Load required assemblies and get object reference
[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
foreach($file in (ls "$path\*.$Ext1")){
$convertfile = new-object System.Drawing.Bitmap($file.Fullname)
$newfilname = ($file.Fullname -replace "([^.]).$Ext1",'$1') + (".$Ext2")
$convertfile.Save($newfilname, "$Ext2")
$file.Fullname
# Dispose file to stop using it
$convertfile.dispose()
# In brackets in the event that the filepath has a space
Remove-Item "$($file.Fullname)"
}
}
else
{
Write-Host "Path not found."
}
};ConvertImage -path $args[0]

Just do a Remove-Item at the end of your foreach.
function ConvertImage{
param ([string]$path)
$path=Convert-Path . #path to files
if (Test-Path $path)
{
#Load required assemblies and get object reference
[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
foreach($file in (ls "$path\*.jpg")){
$convertfile = new-object System.Drawing.Bitmap($file.Fullname)
$newfilname = ($file.Fullname -replace '([^.]).jpg','$1') + ".png"
$convertfile.Save($newfilname, "png")
$file.Fullname
# Dispose file to stop using it
$convertfile.dispose()
# In brackets in the event that the filepath has a space
Remove-Item "$($file.Fullname)"
}
}
else
{
Write-Host "Path not found."
}
};ConvertImage -path $args[0]

Related

Powershell - Append text to end of filenames in sub-directories recursively

Overview
Hi StackOverflow!
I'm hoping someone on here could help me.
I have built the following code to append text to the end of filename on a network drive.
The files in question are primarily ".zip" files and usually range from 6 - 8 sub-directories in the parent folder with 8 - 10 ".zip" files per sub-directoy.
What I am hoping to achieve is to append text to the end of each filename recursively.
Code:
#Current Directory of creatives
$fileLocation = read-host "Type/Paste location of creatives"
if (Test-Path \\serverPath\name\* -PathType Leaf) {
$serverPathName = "\\serverPath\name\"
$driveLetter = "D:\"
$fileLocation = ($fileLocation -replace [regex]::Escape($serverPathName),$driveLetter)
}
$fileLocation = Resolve-Path $fileLocation
Write-Output $fileLocation
$newText = read-host "Please enter text to append"
$newText = $newText -replace '\s','-'
$addMarket = read-host "Are folders split by market? [Y/N]"
$ZipFiles = Get-ChildItem -Path "$currentDirectory" -Recurse -Filter "*.zip"
if ($addMarket -eq "N") {
foreach ($Zipfile in $ZipFiles) {
Get-ChildItem | %{$_|rename-item -NewName ((($_.BaseName -replace '\s','-') + "-" + $newText + $_.Extension))}
}
}
elseif($addMarket -eq "Y") {
foreach ($Zipfile in $ZipFiles) {
Get-ChildItem -File -Recurse | Rename-Item -NewName {(($_.BaseName -replace '\s','-') + "-" + (($_.Directory.Name -replace '\s','-')) + "-" + $newText + $_.Extension).ToLower()}
}
}
else {
write-host "ERROR! Incorrect Input!"
Write-Host "Exiting Script..."
Exit
}
#Clear Console
clear
#Read-Host -Prompt “Press Enter to exit”
Current Situation:
When I run the above (without the loop function), it works fine but I have to into each sub-directory and run the script directly there - which is obviously time-consuming and monotonous.
When I run it within the loop, it works but loops for a long time until the total count of ".zip" files have been reached. e.g. 8 sub-dirs, 9 ".zip" = loops 72 times - each time appending the same text.
Expected Situation:
I wish to run the script from the parent folder of the sub-dirs and the script will only append the text once per sub-dir to all ".zip" and then exit the script.
Problem(?)
I believe the issue lies in the following variable:
$ZipFiles
But I am unable to figure out how to rectify this. I've set it to find all ".zip" files in the parent folder. I've also set it to count he number of files per sub-dir:
Get-ChildItem -Directory | ForEach-Object { Write-Host $_.FullName $(Get-ChildItem $_ | Measure-Object).Count}
But neither has worked for me.
Summary:
I'm hoping someone can point out to me the error I am making and where the fix needs to be.
I am open to all suggestions. If there is a better approach, please also let me know.
I don't mind changing how the code works, if it means the same end result.
Thanks for reading!
Rajiv Ahmed
You have some errors/mistakes in your code:
- You ask to provide a $fileLocation but you don't use it in your code.
- Instead you use a variable $currentDirectory but that's not defined.
- Then you collect all zip files in a variable $ZipFiles, you iterate over this array where you already have zip files but you use Get-ChildItem to get them again. ;-)
Something like this should work actually:
$fileLocation = read-host "Type/Paste location of creatives"
if (Test-Path \\serverPath\name\* -PathType Leaf) {
$serverPathName = "\\serverPath\name\"
$driveLetter = "D:\"
$fileLocation = ($fileLocation -replace [regex]::Escape($serverPathName), $driveLetter)
}
$fileLocation = Resolve-Path $fileLocation
Write-Output $fileLocation
$newText = read-host "Please enter text to append"
$newText = $newText -replace '\s', '-'
$addMarket = read-host "Are folders split by market? [Y/N]"
if ($addMarket -eq "N") {
Get-ChildItem -Path $fileLocation -Recurse -Filter "*.zip" -File |
ForEach-Object {
Rename-Item -Path $_.FullName -NewName ((($_.BaseName -replace '\s', '-') + "-" + $newText + $_.Extension))
}
}
elseif ($addMarket -eq "Y") {
Get-ChildItem -Path $fileLocation -Recurse -Filter "*.zip" -File |
ForEach-Object {
Rename-Item -Path $_.FullName -NewName ((($_.BaseName -replace '\s', '-') + "-" + (($_.Directory.Name -replace '\s', '-')) + "-" + $newText + $_.Extension).ToLower())
}
}
else {
write-host "ERROR! Incorrect Input!"
Write-Host "Exiting Script..."
Exit
}
Clear-Host

Extract file from zips in sub folders

I'm relatively new to PowerShell and have only been doing "light" scripting to automate a few tasks at work.
Most of the time, I can Google and get the answer(s) I need, with maybe some minor tweaking/experimenting.
But I need some help with this one as I can't find the answer I'm looking so hoping someone here might be able to help me.
DETAILS:
I am provided a directory link on the network drive to either sub-folders containing ".zips" or a folder with ".zips" only.
The latter case works for my current script (will be provided further down) to do it's job but the former is where I'm struggling.
TL;DR - I need the script to go into each folder, extract each ".zip" into a "Temp" folder and then look for a "backup" image file (file type may vary) and then copy it out to the sub-folder and rename to the same as the ".zip" it was extracted from.
Again, my script works if I'm physically in the folder with the ".zip" files but not if the ".zip" files are in sub-folders as I can't get it recursively go into each folder and run the script.
EXAMPLE SETUP:
FolderA\FolderB\1.zip
FolderA\FolderB\2.zip
FolderA\FolderB\3.zip
FolderA\FolderC\1.zip
FolderA\FolderC\1.zip
FolderA\FolderC\1.zip
Script below:
#Current Directory of ".zip" files
$fileLocation = read-host "Type/Paste location of creatives"
#replace server path with drive letter
if (Test-Path \\server\path\* -PathType Leaf) {
$serverPathName = "\\server\path\"
$driveLetter = "D:\"
$fileLocation = ($fileLocation -replace [regex]::Escape($serverPathName),$driveLetter)
}
$fileLocation = Resolve-Path $fileLocation
Write-Output $fileLocation
#change directory to the one provided
$zipFilesPath = cd "$fileLocation"
$currentDirectory = pwd
#File type of backup
#Note: `n = new line
write-host "`nChoose Creative Backup File Type"
Write-Host "1. JPG"
Write-host "2. JPEG"
Write-Host "3. PNG"
Write-Host "4. GIF"
$typeFilter = Read-Host "`nType? 1/2/3/4"
if($typeFilter -eq '1'){
$typeFilter = 'jpg'
}
elseif($typeFilter -eq '2'){
$typeFilter = 'jpeg'
}
elseif($typeFilter -eq '3'){
$typeFilter = 'png'
}
elseif($typeFilter -eq '4'){
$typeFilter = 'gif'
}
else {
write-host "ERROR! Incorrect Input!"
Write-Host "Exiting Script..."
start-sleep -seconds 1.5
Exit
}
#Files Location
$ZipFilesPath = "$currentDirectory\*.zip"
#Unzip To Same Location
$UnzipPath = "$currentDirectory"
#Check if Temp Folder exists
$TempCheck = Test-Path "$currentDirectory\Temp"
If ($TempCheck -eq $false) {
#Create Temp Folder
New-Item -ItemType directory -Path "$currentDirectory\Temp" -Force
}
$TempPath = "$currentDirectory\Temp"
$Shell = New-Object -com Shell.Application
$Location = $Shell.NameSpace($TempPath)
$ZipFiles = Get-Childitem $ZipFilesPath -Recurse -Include *.ZIP
$FileCounter = 1
#Clear Initilisation Vars from Console
clear
foreach ($ZipFile in $ZipFiles) {
#Get The Base Filename without the extension
$ZipFileActualName = [io.path]::GetFileNameWithoutExtension($ZipFile.FullName)
write-host File: $ZipFileActualName
$ZipFolder = $Shell.NameSpace($ZipFile.fullname)
$Location.Copyhere($ZipFolder.items(), 1040)
#Find and rename backups
$BackupFiles = Get-ChildItem $TempPath -Filter *backup*.$typeFilter -Recurse
$BackupFiles |% {Move-Item $_.Fullname $UnzipPath/$ZipFileActualName'_backup'.$typefilter}
#Clear Temp Folder
Get-ChildItem -Path "$currentDirectory\Temp" -Include *.* -File -Recurse | foreach { $_.Delete()}
#Move Along to Next File
$FileCounter++
}
#Delete Temp Folder
Remove-Item "$currentDirectory\Temp" -Force -Recurse
#Clear Console
clear
#Read-Host -Prompt “Press Enter to exit”
#start .\
I'm open to any suggestions provided or areas of improvement. If I need to completely change the code, I don't mind. Long as it works for both scenarios.
Thanks.
UPDATE
Modified script as per HAL9256's instruction:
#Current Directory of creatives
$fileLocation = read-host "Type/Paste location of creatives"
if (Test-Path \\server\path\* -PathType Leaf) {
$serverPathName = "\\server\path\"
$driveLetter = "D:\"
$fileLocation = ($fileLocation -replace [regex]::Escape($serverPathName),$driveLetter)
}
$fileLocation = Resolve-Path $fileLocation
Write-Output $fileLocation
$zipFilesPath = cd "$fileLocation"
$currentDirectory = pwd
#File type of backup
#Note: `n = new line
write-host "`nChoose Creative Backup File Type"
Write-Host "1. JPG"
Write-host "2. JPEG"
Write-Host "3. PNG"
Write-Host "4. GIF"
$typeFilter = Read-Host "`nType? 1/2/3/4"
if($typeFilter -eq '1'){
$typeFilter = 'jpg'
}
elseif($typeFilter -eq '2'){
$typeFilter = 'jpeg'
}
elseif($typeFilter -eq '3'){
$typeFilter = 'png'
}
elseif($typeFilter -eq '4'){
$typeFilter = 'gif'
}
else {
write-host "ERROR! Incorrect Input!"
Write-Host "Exiting Script..."
start-sleep -seconds 1.5
Exit
}
#Files Location
$ZipFilesPath = "$currentDirectory"
#Unzip To Same Location
$UnzipPath = "$currentDirectory"
#Check if Temp Folder exists
$TempCheck = Test-Path "$currentDirectory\Temp"
If ($TempCheck -eq $false) {
#Create Temp Folder
New-Item -ItemType directory -Path "$currentDirectory\Temp" -Force
}
$TempPath = "$currentDirectory\Temp"
$Shell = New-Object -com Shell.Application
$Location = $Shell.NameSpace($TempPath)
$ZipFiles = Get-Childitem $ZipFilesPath -Recurse -Include *.ZIP
$FileCounter = 1
#Clear Initilisation Vars from Console
clear
foreach ($ZipFile in $ZipFiles) {
#Get The Base Filename without the extension
$ZipFileActualName = [io.path]::GetFileNameWithoutExtension($ZipFile.FullName)
write-host File: $ZipFileActualName
$ZipFolder = $Shell.NameSpace($ZipFile.fullname)
$Location.Copyhere($ZipFolder.items(), 1040)
#Find and rename backups
$BackupFiles = Get-ChildItem $TempPath -Filter *backup*.$typeFilter -Recurse
$BackupFiles |% {Move-Item $_.Fullname $upzipPath/$ZipFileActualName'_backup'.$typefilter}
#Clear Temp Folder
Get-ChildItem -Path "$currentDirectory\Temp" -Include *.* -File -Recurse | foreach { $_.Delete()}
#Move Along to Next File
$FileCounter++
}
#Delete Temp Folder
Remove-Item "$currentDirectory\Temp" -Force -Recurse
#Clear Console
clear
#Read-Host -Prompt “Press Enter to exit”
#start .\
That did what I need to do. But how can I modify my script so it stores the backups in their respective folder? So the backups extracted from "FolderB" stay in "FolderB", etc? Is there something I can do?
UPDATE 2
Final code - Thanks to help from HAL9256:
#Current Directory of creatives
$fileLocation = read-host "Type/Paste location of creatives"
if (Test-Path \\server\path\* -PathType Leaf) {
$serverPathName = "\\server\path\"
$driveLetter = "D:\"
$fileLocation = ($fileLocation -replace [regex]::Escape($serverPathName),$driveLetter)
}
$fileLocation = Resolve-Path $fileLocation
Write-Output $fileLocation
$zipFilesPath = cd "$fileLocation"
$currentDirectory = pwd
#File type of backup
#Note: `n = new line
write-host "`nChoose Creative Backup File Type"
Write-Host "1. JPG"
Write-host "2. JPEG"
Write-Host "3. PNG"
Write-Host "4. GIF"
$typeFilter = Read-Host "`nType? 1/2/3/4"
if($typeFilter -eq '1'){
$typeFilter = 'jpg'
}
elseif($typeFilter -eq '2'){
$typeFilter = 'jpeg'
}
elseif($typeFilter -eq '3'){
$typeFilter = 'png'
}
elseif($typeFilter -eq '4'){
$typeFilter = 'gif'
}
else {
write-host "ERROR! Incorrect Input!"
Write-Host "Exiting Script..."
start-sleep -seconds 1.5
Exit
}
#Files Location
$ZipFilesPath = "$currentDirectory"
#Unzip To Same Location
$UnzipPath = "$currentDirectory"
#Check if Temp Folder exists
$TempCheck = Test-Path "$currentDirectory\Temp"
If ($TempCheck -eq $false) {
#Create Temp Folder
New-Item -ItemType directory -Path "$currentDirectory\Temp" -Force
}
$TempPath = "$currentDirectory\Temp"
$Shell = New-Object -com Shell.Application
$Location = $Shell.NameSpace($TempPath)
$ZipFiles = Get-Childitem $ZipFilesPath -Recurse -Include *.ZIP
$FileCounter = 1
#Clear Initilisation Vars from Console
clear
foreach ($ZipFile in $ZipFiles) {
#Get The Base Filename without the extension
$ZipFileActualName = [io.path]::GetFileNameWithoutExtension($ZipFile.FullName)
write-host File: $ZipFileActualName
$ZipFolder = $Shell.NameSpace($ZipFile.fullname)
$Location.Copyhere($ZipFolder.items(), 1040)
$DestinationDir = $ZipFile.DirectoryName.Replace($ZipFilesPath,$unzipPath)
#Find and rename backups
$BackupFiles = Get-ChildItem $TempPath -Filter *backup*.$typeFilter -Recurse
$BackupFiles |% {Move-Item $_.Fullname $DestinationDir/$ZipFileActualName'_backup'.$typefilter}
#Clear Temp Folder
Get-ChildItem -Path "$currentDirectory\Temp" -Include *.* -File -Recurse | foreach { $_.Delete()}
#Move Along to Next File
$FileCounter++
}
#Delete Temp Folder
Remove-Item "$currentDirectory\Temp" -Force -Recurse
#Clear Console
clear
#Read-Host -Prompt “Press Enter to exit”
#start .\
When you specify the path:
#Files Location
$ZipFilesPath = "$currentDirectory\*.zip"
Then trying to get the files:
$ZipFiles = Get-Childitem $ZipFilesPath -Recurse -Include *.ZIP
What you essentially are saying is Get-Childitem and get only *.zip files. Because the path parameter has the wildcard filter, it will only get all the *.zip files in that directory and will not get any folders. Since you have no folders matching the *.zip wildcard, Get-Childitem won't have any folders to continue to recurse through.
The solution is to only give a base folder to the path parameter for the Get-Childitem to recurse through, and, correctly, use the -Include to apply the filter for the type. e.g.:
#Files Location
$ZipFilesPath = "$currentDirectory"
...
$ZipFiles = Get-Childitem $ZipFilesPath -Recurse -Include *.ZIP
EDIT:
To move the file to the same folder structure, when inside the loop, you simply use the replace function to replace the source Directory path (the first part of the Directory Name) with your destination base path. Then the sub folders will remain the same. e.g.
...
$DestinationDir = $ZipFile.DirectoryName.Replace($ZipFilesPath,$upzipPath)
...
$BackupFiles |% {Move-Item $_.Fullname $DestinationDir/$ZipFileActualName'_backup'.$typefilter}

Powershell script executed on each file in a folder?

I currently have a powershell script, which print out some information regarding the files which passed in as argument..
The command for executing the script, it done as such:
.\myscript.ps1 -accessitem C:\folder
I want to apply the script on all files and folder on the drive C:, is it possible i for loop to list all files, and pass the path as argument for the script?
The script:
[CmdletBinding()]
Param (
[Parameter(Mandatory=$True,Position=0)]
[String]$AccessItem
)
$ErrorActionPreference = "SilentlyContinue"
If ($Error) {
$Error.Clear()
}
$RepPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$RepPath = $RepPath.Trim()
$str = $AccessItem -replace ':',''
$str = $AccessItem -replace '/','.'
$FinalReport = "$RepPath\"+$str+".csv"
$ReportFile1 = "$RepPath\NTFSPermission_Report.txt"
If (!(Test-Path $AccessItem)) {
Write-Host
Write-Host "`t Item $AccessItem Not Found." -ForegroundColor "Yellow"
Write-Host
}
Else {
If (Test-Path $FinalReport) {
Remove-Item $FinalReport
}
If (Test-Path $ReportFile1) {
Remove-Item $ReportFile1
}
Write-Host
Write-Host "`t Working. Please wait ... " -ForegroundColor "Yellow"
Write-Host
## -- Create The Report File
$ObjFSO = New-Object -ComObject Scripting.FileSystemObject
$ObjFile = $ObjFSO.CreateTextFile($ReportFile1, $True)
$ObjFile.Write("NTFS Permission Set On -- $AccessItem `r`n")
$ObjFile.Close()
$ObjFile = $ObjFSO.CreateTextFile($FinalReport, $True)
$ObjFile.Close()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ObjFSO) | Out-Null
Remove-Variable ObjFile
Remove-Variable ObjFSO
If((Get-Item $AccessItem).PSIsContainer -EQ $True) {
$Result = "ItemType -- Folder"
}
Else {
$Result = "ItemType -- File"
}
$DT = Get-Date -Format F
Add-Content $ReportFile1 -Value ("Report Created As On $DT")
Add-Content $ReportFile1 "=================================================================="
$Owner = (Get-Item -LiteralPath $AccessItem).GetAccessControl() | Select Owner
$Owner = $($Owner.Owner)
$Result = "$Result `t Owner -- $Owner"
Add-Content $ReportFile1 "$Result `n"
(Get-Item -LiteralPath $AccessItem).GetAccessControl() | Select * -Expand Access | Select IdentityReference, FileSystemRights, AccessControlType, IsInherited, InheritanceFlags, PropagationFlags | Export-CSV -Path "$RepPath\NTFSPermission_Report2.csv" -NoTypeInformation
Add-Content $FinalReport -Value (Get-Content $ReportFile1)
Add-Content $FinalReport -Value (Get-Content "$RepPath\NTFSPermission_Report2.csv")
Remove-Item $ReportFile1
Remove-Item "$RepPath\NTFSPermission_Report2.csv"
Invoke-Item $FinalReport
}
If ($Error) {
$Error.Clear()
}
I would prefer a outside command doing this, as workings of the script should not be altered, it it used for single file testing..
There are two ways to do this:
Add -Recurse Flag to the script
Run the script on each directory
I'm going with option two since the script looks complicated enough that I don't want to touch it.
$path_to_script = "C:\path\to\myscript.ps1"
$start_directory = "C:\folder"
# Call Script on Parent Directory
& "$path_to_script" -AccessItem "$start_directory"
# Call Script on any Child Directories within the "$start_directory"
foreach($child in (ls "$start_directory" -Recurse -Directory))
{
$path = $child.FullName
& "$path_to_script" -AccessItem "$path"
}
Basically, I'm calling the script on the parent directory and any sub-directories within the parent directory.

How to move a file to a different folder based on user input in powershell

HI Everyone I am trying to write a script for my powershell practice to move a file from one folder to another based on user input. The script works fine but only if the file exists in the folder same as the script. Can someone please help me what i am doing wrong or try to help with logic
$destination = 'P:\Powershell practice\Movefolder'
$ListFile = "P:\Powershell practice\"
get-childitem $ListFile
$Filename = Read-host -prompt "Please Enter File to be moved"
$FileExists = test-path $Filename
If ($FileExists -eq $True) {
move-item $Filename $destination
Write-Host "File is moved to $destination "
}
else
{write-host "No File Found"}
You need to determine the full file path otherwise the test-path check whether the file exists at the current location. You can use the Join-Path cmdlet to join the pass:
$FilePath = Join-Path $ListFile $FileName
$FileExists = test-path $FilePath
If ($FileExists -eq $True) {
move-item $FilePath $destination
...
Offtopic:
You could also use a Grid-View where the user can select multiple files and press the ok button at the bottom to copy the files ;-):
$destination = 'P:\Powershell practice\Movefolder'
$ListFile = 'P:\Powershell practice\'
$filesToMove = get-childitem $ListFile | Out-GridView -OutputMode Multiple
$filesToMove | % { move-item $_.FullName $destination}
Incase if someone needs. Below is the correct working script for this
$destination = 'P:\Powershell practice\Movefolder'
$ListFile = 'P:\Powershell practice\'
get-childitem $ListFile
$Filename = Read-host -prompt "Please Enter File to be moved"
$FilePath = Join-Path $ListFile $FileName
$FileExists = test-path $FilePath
If ($FileExists -eq $True) {
move-item $FilePath $destination
Write-Host "File is moved to $destination "
}
else
{write-host "No File Found"}

How can i get a prompt to ask for the path, when using Get-ChildItem in PowerShell?

I'm rather new to PowerShell.
I found a few guides and mashed a little script together, though i do not seem to be able to set a prompt to ask for the source/destination.
The script is as following:
gci -path | Get-Random -Count 4 | mi -Destination C:\Temp
while(1) { sleep -sec 20; .\Power.ps1 }
For any response,
thanks in advance!
Use Read-Host:
Get-ChildItem -Path (Read-Host -Prompt 'Get path')
Here's an example, FWIW:
$source,$target = $null,$null
while ($source -eq $null){
$source = read-host "Enter source file name"
if (-not(test-path $source)){
Write-host "Invalid file path, re-enter."
$source = $null
}
elseif ((get-item $source).psiscontainer){
Write-host "Source must be a file, re-enter."
$source = $null
}
}
while ($target -eq $null){
$target = read-host "Enter source directory name"
if (-not(test-path $target)){
Write-host "Invalid directory path, re-enter."
$target = $null
}
elseif (-not (get-item $target).psiscontainer){
Write-host "Target must be a directory, re-enter."
$target = $null
}
}