Error while running powershell script - powershell

I want to remove bak files after zip from all subfolder for given path, so all duplicate files with extension .bak will be removed,i run below script but getting error.
$filePath = "d:\Test\"
$Afiles = Get-ChildItem -Recurse -Path $filePath | Where-Object {$_.Extension -eq ".bak"}
$Bfiles = Get-ChildItem -Recurse -Path $filePath | Where-Object {$_.Extension -eq ".7z"}
$Alist = #()
$Blist = #()
foreach( $A in $Afiles) {
$Alist += $A.baseName
}
foreach( $B in $Bfiles) {
$Blist += $B.baseName
}
foreach($A in $Alist) {
if($Blist -contains $a)
{
rm ("$A.bak")
}
}
I am receiving below error :
Remove-Item : Cannot find path 'C:\Users\******\Desktop\master_backup_2015_08_21_013722_8370267.bak' because it does not exist.
At C:\Users\*****\Desktop\duplicatedelete1.ps1:26 char:10
+ rm <<<< ("$A.bak")
+ CategoryInfo : ObjectNotFound: (C:\Users\****....722_8370267.bak:String) [Remove-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.RemoveItemCommand

You're receiving error because you're not specifying full path for rm command and PowerShell tries to delete file in your current directory.
Try this:
$Path = 'D:\Test'
Get-ChildItem -Path $Path -Recurse -Filter '*.7z' | ForEach-Object {
$BackupFile = Join-Path -Path (Split-Path $_.FullName -Parent) -ChildPath ($_.BaseName + '.bak')
if(Test-Path -Path $BackupFile){
Remove-Item -Path $BackupFile
}
}

Related

Move Item path null

I have to move files from a folder corresponding to a CSV column like that :
id
name
1a
file1
2b
file2
3c
file3
4d
file4
So if in my folder I have a file named file1 I need to create a folder named 1a and put file1 inside.
I have the following script
$CsvId = Import-Csv './test.csv'
$sourcePath= "C:\Users\olong\Desktop\object"
$dirPath = "C:\Users\olong\Desktop\dir"
$files = Get-ChildItem -Path $sourcePath | ForEach-Object -Process {[System.IO.Path]::GetFileNameWithoutExtension($_)}
$pattern = '(?<=_).*(?=_)'
ForEach ($item In $CsvId) {
$objectID = $item.'id'
$docID = $item.'name'
$location = $dirPath+ "\" + $objectID
Foreach ($file in $files) {
if($file -contains $docID) {
if (-not (Test-Path -Path $location)) {
mkdir -Path $location
}
Move-Item ($file.FullName) -Destination $location -Verbose -Force
}
}
}
But it gives me that error :
Move-Item : Cannot bind argument to parameter 'Path' because it is null.
At C:\Users\olong\Desktop\scriptMove.ps1:19 char:15
+ Move-Item ($file.FullName) -Destination $location -Verbose -Force
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Move-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.MoveItemCommand
With PowerShell's debugger $file is not null and with or without parenthesis on $file.FullName does nothing
I think what you want to do is to get the file(s) as mentioned in the csv under header 'name' having any extension into a subfolder as mentioned in field 'id' and create that subfolder first if it does not already exist.
If my assumtion is correct, you can try below:
$sourcePath = "C:\Users\olong\Desktop\object"
$destinationPath = "C:\Users\olong\Desktop\dir"
Import-Csv -Path './test.csv' | ForEach-Object {
$targetDirectory = Join-Path -Path $destinationPath -ChildPath $_.id
# create the output subfolder if it does not already exist
$null = New-Item -Path $targetDirectory -ItemType Directory -Force
# next use the file basename from the $_.name column as filter and move the file(s)
Get-ChildItem -Path $sourcePath -Filter "$($_.name).*" -File | Move-Item -Destination $targetDirectory
}

Powershell - Rename File and Upload

I have the below script which is working fine for what we need thus far however running into an error as the file names have changed.
With the below script it is providing a Cannot Find Path error as the filenames have changed.
Where am i going wrong with this one?
## Add ShareFile PowerShell Snap-in
Add-PSSnapin ShareFile
## Create new authentiation file
#New-SfClient -Name "C:\Sharefile\SVCACC.sfps" -Account midl
## Variables ##
$OutputAppReqFID = "fo4a3b58-bdd6-44c8-ba11-763e211c183f"
$Project = 'M000'
$LocalPath = "\\file.server.au\$project\DATA\DATA CUSTODIAN\OUTPUT\"
$sfClient = Get-SfClient -Name C:\sharefile\SVCACC.sfps
$OutputAppReqFID_URL = (Send-SfRequest $sfClient -Entity Items -id $OutputAppReqFID).Url
## Create PS Drive ##
New-PSDrive -Name "sfDrive-$($project)" -PSProvider ShareFile -Client $sfClient -Root "\" -RootUri $OutputAppReqFID_URL
## Copy all files from folders to ShareFile
foreach ($file in Get-ChildItem -Path $LocalPath -Recurse -Force | Where-Object {$_.Mode -ne "d-----"} | Select FullName -ExpandProperty FullName) {
Get-ChildItem $file -Recurse | Rename-Item -NewName { $_.Directory.Name+'_'+$_.Name}
Copy-SfItem -Path $file -Destination "sfDrive-$($project):"
#remove-item $file
}
<## Remove all folders from UNC directory
foreach ($folder in Get-childitem -Path $LocalPath -Recurse | Where-Object {$_.Mode -eq "d-----"} | Select-Object -ExpandProperty FullName) {
remove-item $folder
}
#>
## Remove PS Drive ##
Remove-PSDrive "sfdrive-$($project)"
Error recieved is below:
Copy-SfItem : Cannot find path '\\file.server.au\M000\DATA\DATA CUSTODIAN\OUTPUT\New Text Document.txt' because it does not exist.
At line:43 char:6
+ Copy-SfItem -Path $file -Destination "sfDrive-$($project):"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (\\file.serve...xt Document.txt:String) [Copy-SfItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,ShareFile.Api.Powershell.CopySfItem
The problem is that you are renaming $file and then trying to Copy-SfItem -Path $file in the very next line. This reference to $file is still pointing to the old name before the rename. You need to instead capture the path to the newly renamed filepath and then reference that in your Copy-SfItem command
foreach ($file in Get-ChildItem -Path $LocalPath -Recurse -Force |
Where-Object { $_.Mode -ne 'd-----' } |
Select-Object -ExpandProperty FullName) {
# capture reference to the new file name by using -PassThru switch with
# the Rename-Item cmdlet and saving in a variable ($renamedFile)
$renamedFile = Get-ChildItem $file -Recurse |
Rename-Item -NewName { $_.Directory.Name + '_' + $_.Name } -PassThru
# Now we copy using our $newFile reference
Copy-SfItem -Path $renamedFile -Destination "sfDrive-$($project):"
# followed by removing the file if needed
# remove-item $renamedFile
}
This can be cleaned up some as well.
Adding the -File switch to Get-ChildItem will give us only files removing the need for | Where-Object {$_.Mode -ne "d-----"}
Taking off the | Select-Object -ExpandProperty FullName from the end of the foreach will eliminate the need to calling Get-ChildItem again in the first foreach loop.
foreach ($file in Get-ChildItem -Path $LocalPath -Recurse -Force -File ) {
# capture reference to the new file name by using -PassThru switch with
# the Rename-Item cmdlet and saving in a variable ($newFile)
$renamedFile = $file | Rename-Item -NewName { $_.Directory.Name + '_' + $_.Name } -PassThru
# Now we copy using our $newFile reference
Copy-SfItem -Path $renamedFile -Destination "sfDrive-$($project):"
# followed by removing the file if needed
# remove-item $renamedFile
}
Updates based on your comments
foreach ($file in Get-ChildItem -Path $LocalPath -Recurse -Force -File ) {
$file = if ($file.Directory.FullName -ne $LocalPath) {
# capture reference to the new file name by using -PassThru switch with
# the Rename-Item cmdlet and saving in a variable ($file)
$file | Rename-Item -NewName { $_.Directory.Name + '_' + $_.Name } -PassThru
}
else {
#Pass thru $file with no changes
$file
}
# Now we copy using our $file reference
Copy-SfItem -Path $file -Destination "sfDrive-$($project):"
# followed by removing the file if needed
# remove-item $file
}

Rename Folders After Copy

I'm having problems after a folder is copied to a different location, I need to rename the folders in the directory to remove ".deploy" from the end, but I get the following error below. I have Googled around for PowerShell admin permissions, but cannot seem to find a 'catch-all' for my scenario.
Get-Content : Access to the path 'C:\OldUserBackup\a.deploy' is denied.
At C:\PSScripts\DesktopSwap\TestMergeDir.ps1:28 char:14
+ (Get-Content $file.PSPath) |
+ ~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : PermissionDenied: (C:\OldUserBackup\a.deploy:String) [Get-Content], UnauthorizedAccessException
+ FullyQualifiedErrorId : GetContentReaderUnauthorizedAccessError,Microsoft.PowerShell.Commands.GetContentCommand
Here is what I have:
$UserName = [Environment]::UserName
$CurrUser = [Environment]::UserName + '.deploy'
$OldUserDir = 'C:\OldUserBackup'
$CurrDate = Get-Date -format G
$PathExist = Test-Path $OldUserDir
if ($PathExist -eq $true) {
#Copy Desktop, Downloads, Favorites, Documents, Music, Pictures, Videos
Copy-Item -Path $OldUserDir -Destination C:\Users\$UserName\Desktop\CopyTest -Recurse -Force
$configFiles = Get-ChildItem $OldUserDir *.deploy -rec
foreach ($file in $configFiles) {
(Get-Content $file.PSPath) |
Foreach-Object { $_ -replace ".deploy", "" } |
Set-Content $file.PSPath
}
}
You should use the -Directory switch on the Get-ChildItem cmdlet to only get directories. Then use the Rename-Item cmdlet to rename the folders. I use the -replace function with a simple regex to get the new folder name:
$deployFolders = Get-ChildItem $OldUserDir *.deploy -rec -Directory
$deployFolders | Foreach {
$_ | Rename-Item -NewName ($_.Name -replace ('\.deploy$') )
}
You don't even have to use the Foreach-Object cmdlet (Thanks to AnsgarWiechers):
Get-ChildItem $OldUserDir *.deploy -rec -Directory |
Rename-Item -NewName { $_.Name -replace ('\.deploy$') }

Get-ChildItem: Illegal characters in path

I'm trying to login to multiple servers and then get list of files from those servers.
Below is my script:
$ServerName=Get-content "D:\HOMEWARE\BLRMorningCheck\Jerry\servername.txt"
foreach ($server in $ServerName)
{
$server_host=echo $server | %{$data = $_.split(";"); Write-Output "$($data[0])"}
$Targetfolder=echo $server | %{$data = $_.split(";"); Write-Output "$($data[1])"}
$Extension =#("*.log","*.txt*")
$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse
echo $Files
}
When I run I debug mode I see that it really doesnt pick the files.
Error:
Get-ChildItem : Illegal characters in path.
At D:\HOMEWARE\BLRMorningCheck\Jerry\test.ps1:14 char:23
+ $Files = Get-Childitem <<<< $TargetFolder -Include $Extension -Recurse
+ CategoryInfo : InvalidArgument: (D:\HOMEWARE\BLR...ck\Jerry\Check":String) [Get-ChildItem], ArgumentException
+ FullyQualifiedErrorId : ItemExistsArgumentError,Microsoft.PowerShell.Commands.GetChildItemCommand
Get-ChildItem : Cannot find path 'D:\HOMEWARE\BLRMorningCheck\Jerry\"\srvparrtfh01\d$\HOMEWARE\BLRMorningCheck\Jerry\Check"' because it does not exist.
At D:\HOMEWARE\BLRMorningCheck\Jerry\test.ps1:14 char:23
+ $Files = Get-Childitem <<<< $TargetFolder -Include $Extension -Recurse
+ CategoryInfo : ObjectNotFound: (D:\HOMEWARE\BLR...ck\Jerry\Check":String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
Note: If I run it manually, example
$Files = Get-Childitem \\servername\d$\HOMEWARE\BLRMorningCheck\Jerry\Check -Include "*.log","*.txt*" -Recurse
I get the output.
As #arco444 and #PetSerAl mentioned in the comments: your path string has leading/trailing double quotes, which are invalid characters in a path. You need to remove them to make the path work as intended:
$Files = Get-Childitem ($TargetFolder -replace '^"|"$') -Include $Extension -Recurse
Of course, since your input file seems to be a some sort of CSV, you could use Import-Csv instead of reading the file with Get-Content and manually splitting the fields. That would already take care of the double quotes on file import.
$filename = 'D:\HOMEWARE\BLRMorningCheck\Jerry\servername.txt'
$extension = '*.log', '*.txt*'
Import-Csv $filename -Delimiter ';' -Header 'ComputerName', 'TargetFolder' | % {
Get-Childitem $_.TargetFolder -Include $extension -Recurse
}
This was an absolute nightmare, get-childitem cannot except a string variable if there are multiple paths.
Get-ChildItem -Path "\server1\c$\temp", "\server1\d$\temp" -File
-recurse # works
$path = '"\server1\c$\temp", "\server1\d$\temp"'; Get-ChildItem -Path "\server1\c$\temp", "\server1\d$\temp" -File
-recurse # fails with cannot find path
$path = "'"\server1\c$\temp", "\server1\d$\temp'""; Get-ChildItem -Path "\server1\c$\temp", "\server1\d$\temp" -File
-recurse # fails with illegal character message (the tick)
Any string that has multiple paths fails, however an array with += as shown below will work.
$servers = #("server1", "server2");
$partialPaths = #("\c$\temp\", "\d$\temp\");
foreach ($server in $servers)
{
$paths = #();
foreach ($partialPath in $partialPaths)
{
$paths += "\\" + $server + $partialPath;
}
}
Get-ChildItem -Path $paths -File -recurse;

Move-Item not reading the path correctly

I have this script where i want to move files from one path to another:
$logArchieveDirectory='C:\LogArchieve\'+$archiveTillDate.Day+$archiveTillDate.Month+$archiveTillDate.Year;
$sourcePathServer = 'C:\DDS\Server\LOGS';
$destPathServer=$logArchieveDirectory+'\Server';
#Create Directories
New-Item -ItemType directory -Path $logArchieveDirectory;
New-Item -ItemType directory -Path $destPathServer;
#Moving Logs to new temporary log archieve directories
foreach( $item in (Get-ChildItem $sourcePathServer | Where-Object { $_.CreationTime -le $archiveTillDate }) )
{
Move-Item $item $destPathServer -force;
}
However, i have specified both paths fine But i keep getting this error when i run this script.
Move-Item : Cannot find path 'C:\DDS\WorkFolder\WebAdapter' because it does not exist.
At C:\DDS\WorkFolder\powerShellScript08062014.ps1:38 char:11
+ Move-Item <<<< $item $destPathController;
+ CategoryInfo : ObjectNotFound: (C:\DDS\WorkFolder\WebAdapter:String) [Move-Item], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.MoveItemCommand
The C:\DDS\WorkFolder\ is actually the folder where my script file is located. But what i am not understanding is why it is looking for the folder here and not where the path is given i.e. $sourcePathServer?
Your script passes relative paths to Move-Item and it defaults to the working directory. An easy solution is to pass absolute paths using .FullName property:
foreach ($item in (Get-ChildItem $sourcePathServer `
| Where-Object { $_.CreationTime -le $archiveTillDate })) {
Move-Item $item.FullName $destPathServer -force
}
Also using foreach in conjunction with pipelines doesn't look very elegant because of all the parentheses. You can get rid of it:
Get-ChildItem $sourcePathServer `
| Where-Object { $_.CreationTime -le $archiveTillDate } | Foreach-Object {
Move-Item $_.FullName $destPathServer -Force
}