Hi am not able to rename a file using the below code. Please help me on this
$date = Get-Date -format "yyyyMMdd"
$path='D:\Users\user\Desktop\Working\'
$fn = $path+'xxx_'+$date+'.txt'
$tn = $path+'yyy'+$date+'.dat'
Rename-Item -Path $fn -NewName $tn
Am getting the below error.
Rename-Item : Cannot process argument because the value of argument "path" is not valid. Change the value of the
"path" argument and run the operation again.
At line:1 char:1
+ Rename-Item -Path $fn -NewName $tn
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Rename-Item], PSArgumentException
+ FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.RenameItemCommand
I'd use Join-Path and Test-Path
$date = Get-Date -format "yyyyMMdd"
$path='D:\Users\user\Desktop\Working\'
$fn = Join-Path $path ("xxx_{0}.txt" -f $date)
$tn = Join-Path $path ("yyy_{0}.txt" -f $date)
If ((Test-Path $fn) -and !(Test-Path $tn)){
Rename-Item -Path $fn -NewName $tn
} else {
"{0} exists is {1}, `n{2} not exists is {3}" -f $fn,(Test-Path $fn),$tn,(!(Test-Path $tn))
}
There is no output on a successful rename, on error the output is like:
D:\Users\user\Desktop\Working\xxx_20180606.txt exists is False,
D:\Users\user\Desktop\Working\yyy_20180606.txt not exists is False
Related
The script included below is now suddenly failing because of the following error. I have not made any changes to it and it's been working for months.
Rename-Item : Cannot bind argument to parameter 'Path' because it is null.
At C:\ImportScripts\FedEx Script\FedExScript.ps1:14 char:14
+ Rename-Item $file $newfilename
+ ~~~~~
+ CategoryInfo : InvalidData: (:) [Rename-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.RenameItemCommand
Add-Type -AssemblyName PresentationCore,PresentationFramework
$curdir=Get-Location
$unc=" " #redacted, but confirmed that working location is correct when running
Set-Location $unc
$dayofweek=([int](Get-date).DayOfWeek)
$fileday=-($dayofweek+3) #change if needed 4:Wednesday, 3:Thursday, etc
$ndate=get-date ((get-date).adddays($fileday)) -Format "yyyyMMdd"
$nyear=get-date ((get-date).adddays($fileday)) -Format "yyyy"
$filename="FedEx_ShipmentDetail_"+$ndate+"*.csv"
$newfilename="FedEx_ShipmentDetail_"+$ndate+".csv"
$fileexists=Test-Path "FedEx_ShipmentDetail_*.csv" -PathType Leaf
if ($fileexists) {
$file = gci ($filename)
Rename-Item $file $newfilename
Set-Location $curdir
$err=cscript "C:\ImportScripts\FedEx Script\FedExScript.vbs"
if ($err -eq 0) {
cscript "C:\ImportScripts\upscleanuptemp.vbs"
Set-Location $unc
mv $newfilename .\$nyear
Set-Location $curdir
[System.Windows.MessageBox]::Show("Import and cleanup completed with no errors.")
}
else {
[System.Windows.MessageBox]::Show("Error in FedExScript.vbs "+$err)
Set-Location $unc
Rename-Item $newfilename $file
Set-Location $curdir
}
}
else {
[System.Windows.MessageBox]::Show("File not found.")
Set-Location $curdir
}
Solved.
Needed to adjust $fileday modifying integer because filename was not matching, as noted in my comments.
I am trying to append string in the file name.
$cstzone = [System.TimeZoneInfo]::FindSystemTimeZoneById("India Standard Time")
$csttime = [System.TimeZoneInfo]::ConvertTimeFromUtc((Get-Date).ToUniversalTime(), $cstzone)
$d = Get-Date $csttime -f "dd-MM-yyyy"
$t = Get-Date $csttime -f "HH:mm"
Write-Host "Date : " $d
Write-Host "Time : " $t
gci C:\Result.jtl | % { rename-item –Path $_.FullName –Newname ( $_.basename + $t + $_.extension) }
Expected
Result_14:42.jtl
Error
rename-item : Cannot rename the specified target, because it represents a path or device name.
At line:10 char:25
+ ... t.jtl | % { rename-item –Path $_.FullName –Newname ( $_.basename + $t ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Rename-Item], PSArgumentException
+ FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.RenameItemCommand
You can't have colons in file names, they are reserved for drive letters. You can use a tostring to get date in different format:
(Get-Date).ToString("hh-mm")
I m fairly new to PowerShell and I apologize in advance if this is a dumb question.
I am trying to construct a new destination/filename where I take the old filename and increment its prefix with +1
$destination = Split-Path -Path 'C:\Users\tom\Desktop\test\0_InstalledPrograms.log'
$file = split-path "C:\Users\tom\Desktop\test\0_InstalledPrograms.log" -Leaf
$array = $file -split '_'
$prefix = $array[0] + 1
$suffix = $array[1]
$newFile = $prefix + '_' + $suffix
$newFile = Out-String -InputObject $newFile
$destination = $destination + '\' + $newFile
Test-Path $destination
Test-Path : Illegal characters in path.
At C:\Users\tom\Desktop\incrementFileName.ps1:18 char:1
+ Test-Path $destination
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (C:\Users\lgranc...dPrograms.log
:String) [Test-Path], ArgumentException
+ FullyQualifiedErrorId : ItemExistsArgumentError,Microsoft.PowerShell.Commands.TestPathCommand
False
This statement:
$newFile = Out-String -InputObject $newFile
adds a new line (CR+LF) to the string, and is completely unnecessary ($newFile is already a string).
Remove that line and it'll work :)
You can do it easily as follows:
$file = "C:\Users\tom\Desktop\test\0_InstalledPrograms.log"
$splittedName = (Split-Path $file -leaf).split('_')
$newFileName = [string]([int]$splittedName[0] + 1) +'_'+ $splittedName[1]
Move-Item -Path $file -Destination (Join-Path (Split-path $file) -ChildPath $newFileName)
I'm trying to move old files into folders based on creation date. The setup is that the script should check a folder for files older than 5 years and then put them in folders sorted by year with subfolders for each month.
$SourceDir = "C:\Test"
$DestinationDir = "C:\Archive\Test\"
$limit = (Get-Date).AddYears(-5)
$files = Get-ChildItem $SourceDir * | Where-Object {
!$_.PSIsContainer -and $_.CreationTime -lt $limit
}
foreach ($file in $files) {
$Directory = $DestinationDir + "" + $file.CreationTime.Date.ToString('yyyy') + "\" + $file.CreationTime.Date.ToString('MM-MMM')
if (!(Test-Path $Directory)) {
New-Item $directory -Type Directory
}
Move-Item $file.FullName $Directory
I get this error
PS C:\Scripts> .\SortIntoMonths5Year.ps1
You cannot call a method on a null-valued expression.
At C:\Scripts\SortIntoMonths5Year.ps1:11 char:69
+ $Directory = $DestinationDir + "" + $file.CreationTime.Date.ToString <<<< ('yyyy') + "\" + $file.CreationTime.Date.ToString('MM-MMM')
+ CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Test-Path : Cannot bind argument to parameter 'Path' because it is null.
At C:\Scripts\SortIntoMonths5Year.ps1:13 char:16
+ if (!(Test-Path <<<< $Directory))
+ CategoryInfo : InvalidData: (:) [Test-Path], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand
Move-Item : Cannot bind argument to parameter 'Path' because it is null.
At C:\Scripts\SortIntoMonths5Year.ps1:17 char:10
+ Move-Item <<<< $file.FullName $Directory
+ CategoryInfo : InvalidData: (:) [Move-Item], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.MoveItemCommand
Fixed it myself
$SourceDir = "C:\Test"
$DestinationDir = "C:\Archive\Test\"
$files = get-childitem $SourceDir * | Where-Object {$_.LastWriteTime -lt (Get-Date).AddYears(-5)}
#$files = get-childitem $SourceDir *
foreach ($file in $files)
{
$Directory = $DestinationDir + "" + $file.LastWriteTime.Date.ToString('yyyy') + "\" + $file.LastWriteTime.Date.ToString('MM-MMM')
if (!(Test-Path $Directory))
{
New-Item $directory -type directory
}
Move-Item $file.fullname $Directory
}
The Script:
Creates a list of folders based on the filenames in the scripts root directory, each folder breaks down the name by "Year/Month/Day"
Moves each file to the designated folder
Error Message:
CategoryInfo : ObjectNotFound:
(S:\Data\TECHNOL...59_20180108.txt:String)
[Move-Item], ItemNotFoundException FullyQualifiedErrorId :
PathNotFound,Microsoft.PowerShell.Commands.MoveItemCommand
My Issue
The files will not move to the correct endpath
#Create Directory
Set-StrictMode -Version 2
$rootPath = split-path -parent $MyInvocation.MyCommand.Definition
cd $rootPath
$FileNameArray = Get-ChildItem -Filter "*.txt"
$FileNameArray = $FileNameArray -replace "....$"
$FileNameArray = $FileNameArray -replace "^59_"
Foreach($f in $FileNameArray)
{
$Year = $f -replace "^\d{0}|\d{4}$" #"....$"
$Month = $f -replace "^\d{4}|\d{2}$"
$Month = $Month | sort -Unique
$Day = $f -replace "^\d{6}|\d{0}$"
#Loop 2a
Foreach($m1 in $Month){
#Loop 2a-a
Foreach($d1 in $Day){
Move-Item -Path ($rootPath + '\59_' + $file + '.txt')
-Destination ($rootPath + '\' + $Year + '\' + $m1 + '\' + $d1)
}
}
}
Apologies for the spaghetti code & simple question, I am new to both Computer Science and PowerShell.
The following script has two security features:
The MD command has a trailing -confirm you have to answer
The Move-Item has a -WhatIf which shows what would be done without the Parameter
If the script works OK, remove them both.
## Q:\Test\2018\05\03\SO_50158185.ps1
Set-StrictMode -Version 2
$rootPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
cd $rootPath
Get-ChildItem "59_20[0-9][0-9][0-1][0-9][0-3][0-9].txt" |
Where-Object {$_.BaseName -Match '59_(?<year>\d{4})(?<Month>\d{2})(?<Day>\d{2})'}|
ForEach-Object {
$DestDir = Join-Path $rootPath ("{0}\{1}\{2}" -f $Matches.Year,$Matches.Month,$Matches.Day)
If (!(Test-Path $DestDir)) {MD $DestDir -Confirm| Out-Null}
$_ | Move-Item -Destination $DestDir -WhatIf
}
Figured it out guys! Just needed to change $file to $f. Thanks for all the help.