How to amend a string with a variable? - powershell

I am trying to copy PDFs from one server to another preserving the folder structure, I have come up with the following script.
I am trying to find the data contained in the variable $Server in another variable $newdes and remove it. However, this fails to happen. If you inspect the variable $newdes you will see that it contains the data stored in $Server, which I need to remove in order for the copy to commence.
As it stands the variable of $newdes contains
C:\Temp\ \file\homedrives\home
It might not show but I see double \ as a UNC file path.
I need it to read C:\temp\homedrives\home.
I am guessing because of the \ \file this fails to start the copy, if this is the case, somebody advise how to get this working.
Amended as requested:
$Criteria = *.pdf
$Trial = c:\temp\folders.txt
$Server = \\file
$Path = homedrives\home
$des = $Path
$safe = Get-Content $Trial
$safe | ForEach-Object {
# find drive-delimeter
$first = $_.IndexOf("\\");
if ($first -eq 1) {
# stripe it
$newdes = Join-Path -Path $des -ChildPath #($_.Substring(0, 1) + $_.Substring(2))[0]
} else {
$newdes = Join-Path -Path $des -ChildPath $_
}
$err = 0
> $folder = Split-Path -Path $newdes -Parent
$err = 0
# check if folder exists"
$void = Get-Item $folder -ErrorVariable err -ErrorAction SilentlyContinue
if ($err.Count -ne 0) {
# create when it doesn't
$void = New-Item -Path $folder -ItemType Directory -Force -Verbose
}
$void = Copy-Item -Path $_ -Destination $des -Force -Verbose
#$void = Copy-Item -Path $_ -Include $Criteria -Destination $Path $Choice -Recurse -Container
#$void = Copy-Item -Path $Files -Include $Criteria -Destination $newdes -Force -Verbose -Recurse -ErrorAction SilentlyContinue
Write-Host $_
}
Write-Host $newdes

Why you don't use the -Recurse switch?
$source = 'C:\source'
$dest = 'C:\dest'
$extensions = #('*.pdf')
Copy-Item -Path $source -Destination $dest -Include $extensions -Force -Recurse
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/copy-item?view=powershell-6

ok, thanks for the assistance, I have now solved the issue, but it has presented another. Will post another question.
The solution to the above is to use
-filter "*.pdf"
Below is a copy of my code
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
Function Select-Server
{
param([string]$Description="Select Folder",[string]$RootFolder="Desktop")
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$objForm = New-Object System.Windows.Forms.FolderBrowserDialog
$objForm.Rootfolder = $Server
$objForm.Description = $Description
$objForm.ShowNewFolderButton = $false
$Show = $objForm.ShowDialog()
If ($Show -eq "OK")
{
Return $objForm.SelectedPath + "\"
}
Else
{
Write-Error "Operation cancelled by user."
}
}
Function Select-FolderDialog
{
param([string]$Description="Select Folder",[string]$RootFolder="Desktop")
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
$objForm = New-Object System.Windows.Forms.FolderBrowserDialog
$objForm.Rootfolder = $RootFolder
$objForm.Description = $Description
$objForm.ShowNewFolderButton = $false
$Show = $objForm.ShowDialog()
If ($Show -eq "OK")
{
Return $objForm.SelectedPath
}
Else
{
Write-Error "Operation cancelled by user."
}
}
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$Server = "\\" + [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a Server to search", "Server Choice")
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$Choice = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a File Path to search", "File Path Choice") + "\"
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$Ext = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a File type i.e. *.PST", "Location Choice")
#$Ext.ToUpper()
$Criteria = "*." + $Ext
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
#$FPath = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a path to copy to", "Location Choice")
$Path = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a folder to store the data", "Path Choice") + "\"
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
#$Name = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a filename", "File Name Choice")
$Search = $Server +"\"+ $Choice
$FileName = $Path
$Info = $Path + "FileCopy.txt"
$Trial = $Path + "Folders.txt"
$Trial2 = $Path + "Ammended Folders.txt"
$Type = $Path + "$Ext's.txt".ToUpper()
#$Server2 = "\" + $Server
#$File = $Path + $Name
if( -Not (Test-Path -Path $Path ) )
{
New-Item -ItemType directory -Path $Path |out-null
}
Else{
[System.Windows.MessageBox]::Show('The directory already exists','Error','Ok','Error')
}
$properties = #(
'Directory'
' '
'Name'
' '
#{
Label = 'Size'
Expression = {
if ($_.Length -ge 1GB)
{
'{0:F2} GB' -f ($_.Length / 1GB)
}
elseif ($_.Length -ge 1MB)
{
'{0:F2} MB' -f ($_.Length / 1MB)
}
elseif ($_.Length -ge 1KB)
{
'{0:F2} KB' -f ($_.Length / 1KB)
}
else
{
'{0} bytes' -f $_.Length
}
}
}
$result = Get-ChildItem -Path $Search -Recurse -Include $Criteria -ErrorAction SilentlyContinue
) | Out-Null
$Result
#Get-ChildItem -Path $Search -Recurse -Include *.pst -ErrorAction SilentlyContinue |
$Folders = (get-childitem -Path $Search | where-object { $_.PSIsContainer }).Count
If (Test-Path $Search) {
<#Write-Host
Write-Host "Listing All Found In $Path" -ForegroundColor "Yellow"
Write-Host "=========================================" -ForegroundColor "Yellow"#>
Add-Type -assembly System.Windows.Forms
## -- Create The Progress-Bar
$ObjForm = New-Object System.Windows.Forms.Form
$ObjForm.Text = "Progress-Bar of searched folders"
$ObjForm.Height = 100
$ObjForm.Width = 500
$ObjForm.BackColor = "White"
$ObjForm.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
$ObjForm.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
## -- Create The Label
$ObjLabel = New-Object System.Windows.Forms.Label
$ObjLabel.Text = "Starting. Please wait ... "
$ObjLabel.Left = 5
$ObjLabel.Top = 10
$ObjLabel.Width = 500 - 20
$ObjLabel.Height = 15
$ObjLabel.Font = "Tahoma"
## -- Add the label to the Form
$ObjForm.Controls.Add($ObjLabel)
$PB = New-Object System.Windows.Forms.ProgressBar
$PB.Name = "PowerShellProgressBar"
$PB.Value = 0
$PB.Style="Continuous"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 500 - 40
$System_Drawing_Size.Height = 20
$PB.Size = $System_Drawing_Size
$PB.Left = 5
$PB.Top = 40
$ObjForm.Controls.Add($PB)
## -- Show the Progress-Bar and Start The PowerShell Script
$ObjForm.Show() | Out-Null
$ObjForm.Focus() | Out-NUll
$ObjLabel.Text = "Starting. Please wait ... "
$ObjForm.Refresh()
Start-Sleep -Seconds 1
Out-Null
## -- Execute The PowerShell Code and Update the Status of the Progress-Bar
$result = Get-ChildItem -Path $Search -Recurse -Include $Criteria -ErrorAction SilentlyContinue
$Counter = 0
ForEach ($Item In $Result) {
## -- Calculate The Percentage Completed
$Counter++
[Int]$Percentage = ($Counter/$Result.Count)*100
$PB.Value = $Percentage
$ObjLabel.Text = "Scanning $Folders Folders For $Criteria in $Search"
#$ObjLabel.Text = "Found $counter $Criteria in $Search"
$ObjForm.Refresh()
Start-Sleep -Milliseconds 150
# -- $Item.Name
#"`t" + $Item.Path
}
$ObjForm.Close()
#Write-Host "`n"
}
Else {
#Write-Host
#Write-Host "`t Cannot Execute The Script." -ForegroundColor "Yellow"
#Write-Host "`t $Search Does Not Exist in the System." -ForegroundColor "Yellow"
#Write-Host
}
Out-Null
Sort-Object -Property DirectoryName |
Format-Table -Property $properties |
out-file $Info
$Search | out-file -Append $Trial
#$Search | Out-File -Append $Trial2
$result | out-file -Append $Info
$result | Select Name | out-file -Append $Type
$des = $Path
#$PDFs= get-content $Type
$safe = Get-Content $Trial
#$Ten = #($Criteria)
$safe | ForEach-Object{
#find drive-delimeter
$first=$_.IndexOf("\\");
if($first -eq 1){
#stripe it
$newdes=Join-Path -Path $des -ChildPath #($_.Substring(0,1)+$_.Substring(2))[0]
}
else{
$newdes=Join-Path -Path $des -ChildPath $_
}
$err=0
$folder=Split-Path -Path $newdes -Parent
$err=0
#check if folder exists"
$void=Get-Item $folder -ErrorVariable err -ErrorAction SilentlyContinue
if($err.Count -ne 0){
#create when it doesn't
$void=New-Item -Path $folder -ItemType Directory -Force -Verbose
}
$void=Copy-Item -Path $_ -destination $newdes -Filter $Criteria -recurse -Container -Force -Verbose -ErrorAction SilentlyContinue
write-host $_
}
write-host $newdes
$void=Copy-Item -Path $_ -destination $newdes -Filter $Criteria -recurse -Container -Force -Verbose -ErrorAction SilentlyContinue

Related

For loop with list not working as expected Powershell

I'm trying to create a powershell script which checks a log file for lines of text and if the line exists restarts a service and resets/archives the log. I got it working before with 1 "checkstring" if you will, but I've been struggling to get it to work with a list of strings. Could anyone help me figure out where I'm going wrong?
This is the code I'm currently using:
$serviceName = "MySQL80"
$file = "test.txt"
$pwd = "C:\tmp\"
$checkStrings = New-Object System.Collections.ArrayList
# Add amount of checkstrings
$checkStrings.add("Unhandled error. Error message: Error retrieving response.")
$checkStrings.add("Unhandled error. Error message: Error retrieving response. Second")
$logName = "ServiceCheck.log"
$backupFolder = "Archive"
$logString = (Get-Date).ToString("ddMMyyyyHHmmss"), " - The service has been reset and the log moved to backup" -Join ""
Set-Location -Path $pwd
if(Test-Path -Path $file) {
if(Test-Path -Path $backupFolder) {
} else {
New-Item -Path $pwd -Name $backupFolder -ItemType "director"
}
foreach ($element in $checkStrings) {
$containsWord = $fileContent | %{$_ -match $element}
if ($containsWord -contains $true) {
Restart-Service -Name $serviceName
$backupPath = $pwd, "\", $backupFolder, "\", $date, ".log" -join ""
$currentFile = $pwd, "\", $file -join ""
Copy-Item $currentFile -Destination $backupPath
Get-Content $currentFile | select-string -pattern $checkString -notmatch | Out-File $currentFile
if(Test-Path -Path $logName) {
Add-Content $logName $logString
} else {
$logString | Out-File -FilePath $logName
}
}
}
}

Copying PDFs while keeping folder structure

So I am trying to copy all the folders and keep the structure that only contain pdf's. I am not sure if there is a way to do this, I have managed to get some of the script to work.
However, when I run it, it copies all the folders even if they don't have PDFs in them. Also I have noticed that my script fails to check the folder and creates in the next directory down. For example:
C:\temp copied once shows C:\temp.
If I was to run the script again it now shows C:\temp\temp
Below is my Code:
$Criteria = *.pdf
$Trial = c:\temp\folders.txt
$Server = \\file
$Path = homedrives\home
$des = $Path
$safe = Get-Content $Trial
$safe | ForEach-Object {
#find drive-delimeter
$first = $_.IndexOf("\\");
if ($first -eq 1) {
#stripe it
$newdes = Join-Path -Path $des -ChildPath #($_.Substring(0,1)+$_.Substring(2))[0]
} else {
$newdes = Join-Path -Path $des -ChildPath $_
}
$err = 0
$fr = 0
$folder = Split-Path -Path $newdes -Parent
#check if folder exists"
$void = Get-Item $folder -ErrorVariable err -ErrorAction SilentlyContinue
if ($err.Count -ne 0) {
#create when it doesn't
$void = New-Item -Path $folder -ItemType Directory -Force
}
#$void = Copy-Item -Path $_ -destination $newdes -Force -Verbose
$void = Copy-Item -Path $_ -destination $newdes -Filter $Criteria -Recurse -Force -ErrorVariable fr -ErrorAction SilentlyContinue
$CR = "`r`n"
$RR = $fr[0].CategoryInfo.TargetName.ToString()
"List of PDF's that Failed To Copy" + $CR + "--------------------------------------------------------------" + $CR + $RR | Out-file -Append $Er
Write-Host $_
}
Write-Host $newdes
ok, so looks like I have cracked it, for future reference, my code actually uses user input to determine locations, it then selects the criteria the user requested and then copies only files with the extensions defined. It copies the folder structure without duplicating and although the filename limitations of windows still exist, there is an error log that is produced that shows the files that have failed to copy. Thanks for all your assistance in this matter.
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
$Server = "\\" + [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a Server to search", "Server Choice")
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
$Choice = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a File Path to search", "File Path Choice") + "\"
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
$Ext = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a File type i.e. *.PST", "Location Choice")
#$Ext.ToUpper()
$Criteria = "*." + $Ext
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
#$FPath = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a path to copy to", "Location Choice")
$Path = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a folder to store the data", "Path Choice") + "\"
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null -ErrorAction Stop
#$Name = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a filename", "File Name Choice")
$Search = $Server +"\"+ $Choice
$FileName = $Path
$Info = $Path + "FileCopy.txt"
$Trial = $Path + "Folders.txt"
$Type = $Path + "$Ext's.txt"
$Er= $Path + "Failed Copying.txt"
$Trial2 = $Path + "Folders.txt"
#$Server2 = "\" + $Server
#$File = $Path + $Name
if( -Not (Test-Path -Path $Path ) )
{
New-Item -ItemType directory -Path $Path |out-null
}
Else{
[System.Windows.MessageBox]::Show('The directory already exists','Error','Ok','Error')
-ErrorAction SilentlyContinue
}
$properties = #(
'Directory'
' '
'Name'
' '
#{
Label = 'Size'
Expression = {
if ($_.Length -ge 1GB)
{
'{0:F2} GB' -f ($_.Length / 1GB)
}
elseif ($_.Length -ge 1MB)
{
'{0:F2} MB' -f ($_.Length / 1MB)
}
elseif ($_.Length -ge 1KB)
{
'{0:F2} KB' -f ($_.Length / 1KB)
}
else
{
'{0} bytes' -f $_.Length
}
}
}
$result = Get-ChildItem -Path $Search -Recurse -Include $Criteria -ErrorAction SilentlyContinue
) | Out-Null
$Result
#Get-ChildItem -Path $Search -Recurse -Include *.pst -ErrorAction SilentlyContinue |
$Folders = (get-childitem -Path $Search | where-object { $_.PSIsContainer }).Count
If (Test-Path $Search) {
<#Write-Host
Write-Host "Listing All Found In $Path" -ForegroundColor "Yellow"
Write-Host "=========================================" -ForegroundColor "Yellow"#>
Add-Type -assembly System.Windows.Forms
## -- Create The Progress-Bar
$ObjForm = New-Object System.Windows.Forms.Form
$ObjForm.Text = "Progress-Bar of searched folders"
$ObjForm.Height = 100
$ObjForm.Width = 500
$ObjForm.BackColor = "White"
$ObjForm.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
$ObjForm.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
## -- Create The Label
$ObjLabel = New-Object System.Windows.Forms.Label
$ObjLabel.Text = "Starting. Please wait ... "
$ObjLabel.Left = 5
$ObjLabel.Top = 10
$ObjLabel.Width = 500 - 20
$ObjLabel.Height = 15
$ObjLabel.Font = "Tahoma"
## -- Add the label to the Form
$ObjForm.Controls.Add($ObjLabel)
$PB = New-Object System.Windows.Forms.ProgressBar
$PB.Name = "PowerShellProgressBar"
$PB.Value = 0
$PB.Style="Continuous"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 500 - 40
$System_Drawing_Size.Height = 20
$PB.Size = $System_Drawing_Size
$PB.Left = 5
$PB.Top = 40
$ObjForm.Controls.Add($PB)
## -- Show the Progress-Bar and Start The PowerShell Script
$ObjForm.Show() | Out-Null
$ObjForm.Focus() | Out-NUll
$ObjLabel.Text = "Starting. Please wait ... "
$ObjForm.Refresh()
Start-Sleep -Seconds 1
Out-Null
## -- Execute The PowerShell Code and Update the Status of the Progress-Bar
$result = Get-ChildItem -Path $Search -Recurse -Include $Criteria -ErrorAction SilentlyContinue
$Counter = 0
ForEach ($Item In $Result) {
## -- Calculate The Percentage Completed
$Counter++
[Int]$Percentage = ($Counter/$Result.Count)*100
$PB.Value = $Percentage
$ObjLabel.Text = "Scanning $Folders Folders For $Criteria in $Search"
#$ObjLabel.Text = "Found $counter $Criteria in $Search"
$ObjForm.Refresh()
Start-Sleep -Milliseconds 150
# -- $Item.Name
#"`t" + $Item.Path
}
$ObjForm.Close()
#Write-Host "`n"
}
Else {
#Write-Host
#Write-Host "`t Cannot Execute The Script." -ForegroundColor "Yellow"
#Write-Host "`t $Search Does Not Exist in the System." -ForegroundColor "Yellow"
#Write-Host
}
Out-Null
Sort-Object -Property DirectoryName |
Format-Table -Property $properties |
out-file $Info
$Search| out-file -Append $Trial
#$Search | Out-File -Append $Trial2
$result | out-file -Append $Info
$result | Select Name | out-file -Append $Type
$CR = "`r`n"
"List of PDF's that Failed To Copy" + $CR + $CR + "--------------------------------------------------------------" | Out-file $Er
$des = $Path
#$PDFs= get-content $Type
$safe = Get-Content $Trial
#$Ten = #($Criteria)
$safe | ForEach-Object{
#find drive-delimeter
$first=$_.IndexOf("\\");
if($first -eq 0){
#stripe it
$newdes=Join-Path -Path $des -ChildPath #($_.Substring(0,1)+$_.Substring(2))[0]
}
$newdes=Join-Path -Path $des -ChildPath $_
$err=0
$fr=0
$folder=Split-Path -Path $newdes -Parent
$folders=Split-Path -Path $newdes -leaf
#$fy = $folder + "\" +$folders
#check if folder exists"
$void=Get-Item $newdes -ErrorVariable err -ErrorAction SilentlyContinue #-verbose
If(!(Test-Path -Path $newdes) ){
$err=1
}
if($err.Count -ne 0){
#create when it doesn't
$void=New-Item -Path $folder -ItemType Directory #-verbose
}
#$void=Copy-Item -Path $_ -destination $newdes -Force -Verbose
$void=Copy-Item -Path $_ -destination $folder -Filter $Criteria -Recurse -Container -Force -ErrorVariable fr -ErrorAction SilentlyContinue -verbose
write-host "------------------------------------------------------- Break -------------------------------------------------------" -ForegroundColor Green
foreach($re in $fr){
$RR = $re[0].CategoryInfo.TargetName.ToString()
$X5 = $re[0].CategoryInfo.Reason.ToString()
$X6 = $re[0].TargetObject.DirectoryName.ToString()
$X6 + $CR + $X5 + "---" + $RR + $CR | Out-file -Append $Er
}
write-host "`n" $_
}
write-host "`n------------------------------------------------------- End of Script -------------------------------------------------------" -ForegroundColor Blue`

Cannot bind argument to parameter

How do I get this powershell program to successfully execute?
$Source = "\\ahs-bind01\ftptest01\CRAR"
Get-ChildItem -Path $Source -recurse
#Declare the file path and sheet name
$file = "C:\Users\us6205\Desktop\DatabaseNameConfigs\Test\CareMoveFileParentDestPaths.xlsx"
$sheetName = "sheet1"
#Create an instance of Excel.Application and Open Excel file
$objExcel = New-Object -ComObject Excel.Application
$workbook = $objExcel.Workbooks.Open($file)
$sheet = $workbook.Worksheets.Item($sheetName)
$objExcel.Visible=$false
#Count max row
$rowMax = ($sheet.UsedRange.Rows).count
#Declare the starting positions
$rowLOC,$colLOC = 1,1
$rowUNC,$colUNC = 1,2
#loop to get values and store it
for ($i=1; $i -le $rowMax-1; $i++)
{
$LOC = $sheet.Cells.Item($rowLOC+$i,$colLOC).text
$UNC = $sheet.Cells.Item($rowUNC+$i,$colUNC).text
$Path = Get-ChildItem -Path $UNC -recurse |
Where-Object { ($_.PSIsContainer -eq $true) -and ( $_.FullName -match "$Source") }
$Dest = $Path | New-Item -path $Dest -itemtype directory | Move-Item -Path $Source -Destination $Dest -Force
}
#close excel file
$objExcel.quit()
You want to put these $Source = "\ahs-bind01\ftptest01\CRAR" Get-ChildItem -Path $Source -recurse each to its line like this:
$Source = "\ahs-bind01\ftptest01\CRAR"
Get-ChildItem -Path $Source -recurse
Same with $rowLOC,$colLOC = 1,1 $rowUNC,$colUNC = 1,2
$rowLOC,$colLOC = 1,1
$rowUNC,$colUNC = 1,2
Same with $LOC = $sheet.Cells.Item($rowLOC+$i,$colLOC).text $UNC = $sheet.Cells.Item($rowUNC+$i,$colUNC).text
$LOC = $sheet.Cells.Item($rowLOC+$i,$colLOC).text
$UNC = $sheet.Cells.Item($rowUNC+$i,$colUNC).text
Also edit ($.PSIsContainer -eq $true) -and ( $.FullName -match "$Source") to:
($_.PSIsContainer -eq $true) -and ( $_.FullName -match "$Source")

PowerShell Move-Item $filename

I searched, i googled.. about to smash my head on the table
how come this will not work?
move-Item $path$file $targetdir
it gives me an error
Move-Item : An object at the specified path C:\Repository\test.csv
does not exist.
now if i debug this and i output using
write-output move-Item $path$file $targetdir
and take that output and paste it (file name with path and destination) it works!
and trust me the file is there. =\
Code below
$path = 'C:\test\'
$TimeStamp = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
$LogFile = Get-Date -Format "MM_dd_yyyy"
$targetdir = "C:\test\Uploaded\"
#Get-ChildItem -path $path\* -Include *.csv | foreach-object {$_.Fullname} | Format-Table name -hidetableheaders | Out-File $path\list.txt
Get-ChildItem -path $path\* -Include *.csv | Format-Table name -hidetableheaders | Out-File $path\list2.txt
get-content C:\test\list2.txt | where {$_ -ne ""} | out-file C:\test\list.txt
Remove-Item C:\test\list2.txt
$list = get-content C:\test\list.txt
foreach ($file in $list)
{
$ftp = "ftp://REMOVED/$file"
"ftp url: $ftp"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
"Uploading $file..."
$succeeded = $true;
& {
trap { $script:succeeded = $false; continue }
$webclient.UploadFile($uri, $path+$file)
}
if ($succeeded)
{
echo $file 'Was successfully uploaded!' $Timestamp >> logfile$LogFile.log
move-Item -path $path$file -destination $targetdir
#test-path $path$file
}
else
{
echo $file 'Was not successfully uploaded, will retry later' $Timestamp >> logfile$LogFile.log
}
}
exit
Basics are:
Test-Path before you move it (file and destination)
Move the file, ensure you have permission (force it to move)
so:
echo $targetdir
echo "$path$file"
if (!(Test-Path $targetdir)) {
New-Item -ItemType directory $targetdir
}
if(Test-Path "$path$file") {
Move-Item "$path$file" $targetdir -Force
} else {
echo "file does not exist"
}
If you loop over a collection you have to use the ".FullName" property of the object:
Get-ChildItem $path | ForEach-Object { Move-Item $_.FullName $targetdir -Force }
Does the target directory already exist? I believe Move-Item will fail if the target directory doesn't exist. If that's the case, you can simply test for existence of the directory beforehand and then create as necessary.
If (!(Test-Path -Path $targetdir)) {
New-Item -ItemType directory -Path $targetdir
}
This worked for me. Thank you #TheMadTechnician. Hopes this helps everyone
$TimeStamp = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
$LogFile = Get-Date -Format "MM_dd_yyyy"
$path='C:\test\'
$targetDir = 'C:\test\Uploaded\'
$fileList = Get-ChildItem $path*.csv
If(!(Test-Path $TargetDir)){New-Item -ItemType Directory -Path $TargetDir|Out-Null}
$fileList | Select -ExpandProperty Name | Out-File 'C:\test\list.txt'
$list = get-content C:\test\list.txt
foreach ($file in $list)
{
$ftp = "ftp://REMOVED/$file"
"ftp url: $ftp"
$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)
"Uploading $file..."
$succeeded = $true;
& {
trap { $script:succeeded = $false; continue }
$webclient.UploadFile($uri, $path+$file)
}
if ($succeeded)
{
echo $file 'Was successfully uploaded!' $Timestamp >> logfile$LogFile.log
move-Item -path $path$file -destination $targetdir$Timestamp"_"$file
#test-path $path$file
}
else
{
echo $file 'Was not successfully uploaded, will retry later' $Timestamp >> logfile$LogFile.log
}
}
exit
How about this then:
ForEach($File in $List){
Join-Path $path $file | Move-Item -Dest $Targetdir
}
Edit: Also... your creation of list.txt, it bothered me so I had to comment. Format-Table should be used for formatting text, not for selecting a value to output to a file. There's a better way to do that, consider this alternative:
Get-ChildItem "$path*.csv" | Select -ExpandProperty Name | Out-File $pathlist.txt
Since you say that $path = 'C:\test\' you are adding extra backslashes in there that may cause issues for some commands.
Edit2: Ok, if that doesn't work, why not work with the files themselves instead of outputting to a file, importing from that file, and then working with things.
$path='c:\test\'
$TargetDir = 'c:\test\NewDir'
$FileList = Get-ChildItem $path*.csv
If(!(Test-Path $TargetDir)){New-Item -ItemType Directory -Path $TargetDir|Out-Null}
$FileList | Move-Item -Destination $TargetDir
Then if you really want a list of those file names just pipe $FileList to Select and then to Out-File
$FileList | Select -ExpandProperty Name | Out-File 'C:\Test\list.txt'
Here, look through this and see if there's anything you like. I made a few changes, such as declaring paths at the beginning for everything, I moved the WebClient object creation outside of the loop, and changed how things are displayed on screen. Plus I skip the entire exporting to text file and re-importing it.
$path = 'C:\test'
$ftpaddr = 'ftp://ftp.example.com/uploads'
$TimeStamp = Get-Date -Format "MM/dd/yyyy hh:mm:ss tt"
$LogFile = Get-Date -Format "MM_dd_yyyy"
$LogDir = "C:\Test\Logs"
If(!(test-path $LogDir)){New-Item -ItemType Directory -Path $LogDir | Out-Null}
$targetdir = 'C:\test\Uploaded'
If(!(test-path $targetdir)){New-Item -ItemType Directory -Path $targetdir | Out-Null}
$list = Get-ChildItem -path $path\* -Include *.csv
$webclient = New-Object System.Net.WebClient
"ftp url: $ftpaddr"
foreach ($file in ($list|select -ExpandProperty Name))
{
$uri = New-Object System.Uri(("$ftpaddr/$file"))
Write-Host "Uploading $file... " -NoNewline -ForegroundColor White
$succeeded = $true
& {
trap { $script:succeeded = $false; continue }
$webclient.UploadFile($uri, "$Path\$file")
}
if ($succeeded)
{
Write-Host "Success!" -ForegroundColor Green
"$Timestamp`t$File was successfully uploaded!" | Out-File "$logdir\logfile$LogFile.log" -Append
move-Item -path "$path\$file" -destination $targetdir
}
else
{
Write-Host "Failed! Will retry later." -ForegroundColor Red
"$Timestamp`t$File was not successfully uploaded, will retry later" | Out-File "$logdir\logfile$LogFile.log" -Append
}
}

"A device attached to the system is not functioning " error when using robocopy to move folder in sharepoint

We are using Sharepoint 2010. There is a requirement to archive folders/Subfolders from a given folder to Archive folder which is part of document library. So we used Robocopy from powershell environment. But we're getting error "A device attached to the system is not functioning". ERROR 31 (0x0000001F) Changing File Attributes
Can any one help me what I have to do fix the above error.
Here is my code
$sourceDir = "\\labserver\sites\XXX\YYY Accounts Documents"
$targetDir = "\\labserver\sites\XXXX\Archived YYY Accounts Documents"
$FilePath = "C:\InactiveAccount_SharepointFolder.xlsx"
$sourceDir1= "\\labserver\sites\xxx\yyy Accounts Documents"
$SheetName = "Sheet1"
# Create an Object Excel.Application using Com interface
$objExcel = New-Object -ComObject Excel.Application
# Disable the 'visible' property so the document won't open in excel
$objExcel.Visible = $false
# Open the Excel file and save it in $WorkBook
$WorkBook = $objExcel.Workbooks.Open($FilePath)
$strSheetName = "sheet1"
# Load the WorkSheet 'BuildSpecs'
if ($strSheetName -eq "")
{
$worksheet = $WorkBook.sheets.item(1)
}
else
{
$worksheet = $WorkBook.sheets.item($strSheetName)
}
try {
$intRowMax = ($worksheet.UsedRange.Rows).count
for($intRow = 2 ; $intRow -le $intRowMax ; $intRow++)
{
$isFodlerExists = $worksheet.cells.item($intRow,3).value2
if($isFodlerExists -match "Yes")
{
$accountName = $worksheet.cells.item($intRow,1).value2
#[system.io.directory]::CreateDirectory($tempSource + $accountName)
#write-host $accountName
$sFolder = $sourceDir + "\" + $accountName
$sFolder1 = $sourceDir1 + "\" + $accountName
write-host $sFolder
$tFolder = $targetDir
Add-Content -Path $ErrorLog -Value $sFolder
if((Test-path -Path $sFolder1) -eq $TRUE)
{
try {
#Copy-Item -Path $sFolder -Destination $tFolder -Recurse -force
robocopy $sFolder $tFolder /e /r:2 /log:$ErrorLog /tee
}
Catch {
Add-Content -Path $ErrorLog -Value "Exception write"
$DateTime = (Get-Date).ToShortDateString() + " " + (Get-Date).ToShortTimeString()
$Target = $_.TargetObject
$e = $_
Add-Content -Path $ErrorLog -Value "$DateTime - $e $Target"
#Write-Host "$e $Target"
$ErrorActionPreference = "Continue"
}
if($?)
{
add-content -path $ErrorLog -value ($?)
}
else
{
add-content -path $ErrorLog -value ($?)
}
}
}
#write-host $accountName
}
}
Catch {
Add-Content -Path $ErrorLog -Value "Exception write"
$DateTime = (Get-Date).ToShortDateString() + " " + (Get-Date).ToShortTimeString()
$Target = $_.TargetObject
$e = $_
Add-Content -Path $ErrorLog -force -Value "$DateTime - $e $Target"
#Write-Host "$e $Target"
$ErrorActionPreference = "Continue"
}
$WorkBook.close()
$objExcel.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($objExcel)
Can any one help me what I have to do fix the above error.