0

I am trying to append date and time to a folder using powershell. Let's say the folder name is always same, so I can store it in a variable in my power shell script. Ex: $myfolder = "default_folder"

I use get-date and get-time to find current date/time and store it in $file_date and $file_time

Using Rename-Item doesn't seem to work.

Rename-Item "$myfolder" "$myfolder"_"$file_date"_"$file_time"

I get the following error:

Rename-Item : A positional parameter cannot be found that accepts argument '_20210722_1157'.
At line:1 char:1
+ Rename-Item "$myfolder" "$myfolder"_"$file_date"_"$file_time"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Rename-Item], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Com

1 Answer 1

1

The way you concatenated the strings resulted in a space after default_folder:

❯ $myfolder = "default_folder"
❯ $file_date = "20210722"
❯ $file_time = "1157"
❯ write-host "$myfolder"_"$file_date"_"$file_time"
default_folder _20210722_1157

Try this for your rename argument instead ${myfolder}_${file_date}_${file_time}

❯ write-host ${myfolder}_${file_date}_${file_time}
default_folder_20210722_1157

Rename-Item -Path ${myfolder} -NewName ${myfolder}_${file_date}_${file_time}

4
  • woohoo! That worked like a charm. Thanks, Josh.
    – hithesh
    Jul 23, 2021 at 3:13
  • @hithesh no problem! Could you mark my answer as correct? I also see you had a follow up question that you might have accidentally put in as an edit to the answer, you can just add it as a comment here.
    – Josh Zhang
    Jul 23, 2021 at 13:15
  • Related question: While doing this, I also tried to use Select-Object to get date and time of folder creation. When I use select-object, instead of 1 time stamp, I get a bunch like below. Why do I get so many and how do I limit to 1? Get-ChildItem "$myfolder" | Select-Object -ExpandProperty CreationTime | Get-Date -f "yyyyMMdd_hhmm" 20210722_1104 20210722_1104 20210722_1104 20210722_1104 20210722_1104 20210722_1104 20210722_1104 20210722_1104 20210722_1104 20210722_1104
    – hithesh
    Jul 23, 2021 at 22:05
  • @hithesh you are getting multiple timestamps because you used Get-ChildItem which is including all the subfolders instead of Get-Item which would only return the folder or file you chose.
    – Josh Zhang
    Jul 24, 2021 at 12:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.