powershell script on entire directory

E

Evan Platt

So I'm looking to rename all the files in a directory appending the
date / time.

I found the powershell script at
http://ss64.com/ps/syntax-stampme.html :

#StampMe.ps1
param( [string] $fileName)

# Check the file exists
if (-not(Test-Path $fileName)) {break}

# Display the original name
"Original filename: $fileName"

$fileObj = get-item $fileName

# Get the date
$DateStamp = get-date -uformat "%Y-%m-%d@%H-%M-%S"

$extOnly = $fileObj.extension

if ($extOnly.length -eq 0) {
$nameOnly = $fileObj.Name
rename-item "$fileObj" "$nameOnly-$DateStamp"
}
else {
$nameOnly = $fileObj.Name.Replace( $fileObj.Extension,'')
rename-item "$fileName" "$nameOnly-$DateStamp$extOnly"
}

# Display the new name
"New filename: $nameOnly-$DateStamp$extOnly"

But this doesn't appear to work on a batch basis, ie

powershell ./stampme.ps1 G:\test\*.*
(or G:\test ).

Am I missing something obvious? This is Windows 8 if it matters.
(Yes, I realize this is a Win7 group but I beleve the PS is the same)
Thanks.
 
B

Bob I

yes, from what I can see, you are going to need a "for" command in
there. you can't pass a "wildcard' like that
 
P

Paul

Bob said:
yes, from what I can see, you are going to need a "for" command in
there. you can't pass a "wildcard' like that
Example of a "for" loop here.

http://stackoverflow.com/questions/...alues-to-a-single-powershell-script-parameter

Paul
So I'm looking to rename all the files in a directory appending the
date / time.

I found the powershell script at
http://ss64.com/ps/syntax-stampme.html :

#StampMe.ps1
param( [string] $fileName)

<SNIP>

But this doesn't appear to work on a batch basis, ie

powershell ./stampme.ps1 G:\test\*.*
(or G:\test ).

Am I missing something obvious? This is Windows 8 if it matters.
(Yes, I realize this is a Win7 group but I beleve the PS is the same)
Thanks.
 
A

Andy Burns

Andy said:
Surely simpler to pass one argument (the name of the folder) and let
powershell enumerate all files within it and rename them to incorporate
the timestamp?
something like this ...

# StampAll.ps1

param( [string] $folderName)


function stampOne($fileObj) {
# Display the original name
"Original filename: $($fileObj.Name)"

# Get the date
$DateStamp = get-date -uformat "%Y-%m-%d@%H-%M-%S"

$extOnly = $fileObj.extension

if ($extOnly.length -eq 0) {
$nameOnly = $fileObj.Name
rename-item "$fileObj" "$nameOnly-$DateStamp"
}
else {
$nameOnly = $fileObj.Name.Replace( $fileObj.Extension,'')
rename-item "$($fileObj.Name)" "$nameOnly-$DateStamp$extOnly"
}
}


# Check the folder exists
if (-not(Test-Path $folderName)) {break}


# rename all files within folder
Set-Location $folderName
Get-childItem | ForEach-Object { stampOne $_ }
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top