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")
Related
I am no expert with Powershell; however, I am trying to simply run an Invoke-Sqlcmd and save the results as a .csv file. I am looping through multiple *.sql files as the queries. When I run the following Powershell from a Windows10 desktop, everything runs fine but when I run this from our SQL Server, I am receiving errors on the export-csv command.
Here is my Powershell:
#Prompt for date
$DatePrompt = Read-Host -Prompt 'Enter the database date. (YYYY-MM-DD)'
#Convert to date
$DatabaseDate = [DateTime]::Parse($DatePrompt)
#Create FileDate string
$FileDate = $DatabaseDate.ToString("yyyyMMdd")
#Create SQLDate string
$SQLDate = $DatabaseDate.ToString("yyyy-MM-dd")
#--------------------------------------------------------------------------------------------------------------------------------
#Provide SQLServerName
$SQLServer ="SQLSERVER\MISDATA"
#Provide Database Name
$DatabaseName ="StagingDB"
#Set MonthStart and MonthEnd (YYYY-MM-DD)
$Variables = "FileDate = $SQLDate"
#Scripts Folder Path
$FolderPath ="\\SQLSERVER\MISDATA\Queries"
#Output Folder Path
$OutputFolderPath ="\\SQLSERVER\MISDATA\Results"
#--------------------------------------------------------------------------------------------------------------------------------
#Loop through the .sql files and run them
foreach ($filename in get-childitem -path $FolderPath -filter "*.sql")
{ #Run SQL Query
Invoke-Sqlcmd -ServerInstance $SQLServer -Database $DatabaseName -InputFile $filename.fullname -Variable $Variables -Querytimeout 0|
#Export to CSV
Export-Csv -NoTypeInformation -Path ($OutputFolderPath + "\" + $FileDate + "-" + $filename.basename + ".csv") -Encoding UTF8
#Write to ConsoleHost
Write-Host $filename.name "completed"
}
Here is the error:
Export-Csv : Cannot open file because the current provider (Microsoft.SqlServer.Management.PSProvider\SqlServer) cannot open a file.
At C:\MISDATA\Queries\Run Scripts.ps1:26 char:5
+ Export-Csv -NoTypeInformation -Path ($OutputFolderPath + "\" + $FileDate + " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], PSInvalidOperationException
+ FullyQualifiedErrorId : ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportCsvCommand
sqlquery1.sql completed
Export-Csv : Cannot open file because the current provider (Microsoft.SqlServer.Management.PSProvider\SqlServer) cannot open a file.
At C:\MISDATA\Queries\Run Scripts.ps1:26 char:5
+ Export-Csv -NoTypeInformation -Path ($OutputFolderPath + "\" + $FileDate + " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], PSInvalidOperationException
+ FullyQualifiedErrorId : ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportCsvCommand
sqlquery2.sql completed
Export-Csv : Cannot open file because the current provider (Microsoft.SqlServer.Management.PSProvider\SqlServer) cannot open a file.
At C:\MISDATA\Queries\Run Scripts.ps1:26 char:5
+ Export-Csv -NoTypeInformation -Path ($OutputFolderPath + "\" + $FileDate + " ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Export-Csv], PSInvalidOperationException
+ FullyQualifiedErrorId : ReadWriteFileNotFileSystemProvider,Microsoft.PowerShell.Commands.ExportCsvCommand
sqlquery3.sql completed
You need to specify powershell ruled UNC format.
$OutputFolderPath ="Filesystem::\\SQLSERVER\MISDATA\Results"
or
$OutputFolderPath ="Microsoft.PowerShell.Core\FileSystem::\\SQLSERVER\MISDATA\Results"
I am working on azure CD pipeline, i want to change content of multiple files which exist in following folder structure.
MainFolder => SubFolder1 => myFile1.txt
SubFolder2 => myFile2.txt
SubFolder3 => myFile3.txt
I want to achieve my above requirement using powershell, and i have tried the following code.
$filepath = 'C:\Users\ashishjain06\Desktop\MainFolder'
$mydata = Get-ChildItem $filepath -include *.txt -recurse | Select-Object fullName
$totalRecords = $mydata.Count
for($x = 0; $x -lt $totalRecords; $x++)
{
((Get-Content -path $mydata[$x] -Force) -replace 'oldText','newText') | Set-Content -Path $mydata[$x]
}
When i run above code it's give me following output.
Get-Content : Cannot find drive. A drive with the name '#{FullName=C' does not exist.
At line:6 char:7
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (#{FullName=C:String) [Get-Content], DriveNotFoundException
+ FullyQualifiedErrorId : DriveNotFound,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:6 char:25
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:6 char:25
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:6 char:25
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
Get-Content : Cannot bind argument to parameter 'Path' because it is null.
At line:6 char:25
+ ((Get-Content -path $mydata[$x] -Force) -replace 'oldText ...
+ ~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Get-Content], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.GetContentCommand
I am newbie on powershell, Please help me out to resolve this issue.
Get-ChildIItem returns (an array of) FileInfoObjects with a bunch of properties,
Select-Object drops all but the selected one, but it is still an object with one property FullName.
See $mydata | Get-Member
One method is Select-Object -ExpandProperty FullName,
another one is the property dereference operator . used in the following script.
To have the script work on any user don't include a fixed path, either use $Env:USERPROFILE or better yet, let the system evaluate current users Desktop folder (which might be relocated).
Instead of iterating the arrray $mydata by index let powershell do that with a foreach:
$filepath = Join-Path ([environment]::GetFolderPath('Desktop')) 'MainFolder'
$files = (Get-ChildItem $filepath -Filter *.txt -Recurse).FullName
foreach($file in $files){
(Get-Content -path $file -Force) -replace 'oldText','newText' | Set-Content -Path $file
}
It's still an object with a property unless you do this:
select-object -expandproperty fullname
Replace Select-Object with ForEach-Object, i.e.:
$filepath = 'C:\Users\ashishjain06\Desktop\MainFolder'
#$mydata = Get-ChildItem $filepath -include *.txt -recurse | Select-Object fullName
$mydata = Get-ChildItem $filepath -include *.txt -recurse | ForEach-Object fullName
$totalRecords = $mydata.Count
for($x = 0; $x -lt $totalRecords; $x++)
{
((Get-Content -path $mydata[$x] -Force) -replace 'oldText','newText') | Set-Content -Path $mydata[$x]
}
Trying to search a folder for files not already ending in *.txt which have not been modified in 1 day and rename the extension to .txt
$app_files = get-childitem "C:\Users\adm.aross\Desktop\Rename DHL files - TKT0087521\Test" -recurse -exclude *.txt | where-object {$_.LastWriteTime -lt (Get-Date).AddDays(-1)}
foreach ( $file in $app_files ) {
$newfile = $file.Name + ".txt"
Rename-Item -Literalpath "C:\Users\adm.aross\Desktop\Rename DHL files - TKT0087521\Test\$file" $newfile
}
Rename-Item : Cannot rename because item at
'C:\Users\adm.aross\Desktop\Rename DHL files -
TKT0087521\Test\C:\Users\adm.aross\Desktop\Rename DHL files -
TKT0087521\Test\01-06-2019.log' does not exist. At line:5 char:9
+ Rename-Item -Literalpath "C:\Users\adm.aross\Desktop\Rename D ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
Rename-Item : Cannot rename because item at
'C:\Users\adm.aross\Desktop\Rename DHL files -
TKT0087521\Test\C:\Users\adm.aross\Desktop\Rename DHL files -
TKT0087521\Test\01-07-2019.log' does not exist. At line:5 char:9
+ Rename-Item -Literalpath "C:\Users\adm.aross\Desktop\Rename D ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
Rename-Item : Cannot rename because item at
'C:\Users\adm.aross\Desktop\Rename DHL files -
TKT0087521\Test\C:\Users\adm.aross\Desktop\Rename DHL files -
TKT0087521\Test\08-05-2019.log.log' does not exist. At line:5 char:9
+ Rename-Item -Literalpath "C:\Users\adm.aross\Desktop\Rename D ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Rename-Item], PSInvalidOperationException
+ FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.RenameItemCommand
$RootFolder = 'C:\Users\adm.aross\Desktop\Rename DHL files - TKT0087521\Test'
$CheckDate = [DateTime]::UtcNow.AddDays(-1)
Get-ChildItem -LiteralPath $RootFolder -Exclude #('*.txt') -Recurse:$true |
Where-Object { $_.psIsContainer -eq $false } | # Check is file, not a directory
Where-Object { $_.LastWriteTimeUtc -lt $CheckDate } |
Where-Object { $_.CreationTimeUtc -lt $CheckDate } |
Where-Object { ( Test-Path -LiteralPath "$($_.FullName).txt" -PathType Any ) -ne $true } | # Check if there is no .txt file already
ForEach-Object { Rename-Item -LiteralPath $_.FullName -NewName "$($_.Name).txt" }
Check WriteTime and CreationTime. There can be situations when file
is created AFTER written ( when file is copied from another source,
WriteTime is copied, and CreationTime is not )
Check you can rename the file (the target name not exist )
Check it is a file
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
}
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