简体   繁体   中英

passing variables to ren command in powershell

Can someone show me what is wrong with this syntax? I simply cannot get this to work:

#there is file called MyLog.log inside'logoutput'
$file='myimage'
$LogsDestFolder='logoutput'
Write-Host "Renaming log for $file.bmp"
ren $LogsDestFolder\MyLog.log $LogsDestFolder\$file.log

keeps complaining I cannot pass variables inside the 'ren' command. I tried put single or double quotes, nothing worked.

Keep getting this:

ren : Cannot rename the specified target, because it represents a path or device name.

thx!

The issue here is most likely that you are passing a path into the parameter -NewName . Your command translates to this currently:

Rename-Item -Path $LogsDestFolder\MyLog.log -NewName $LogsDestFolder\$file.log

ren = Rename-Item which you can see from Get-Alias ren . The actual error I get when I run this is:

ren : Cannot rename because the target specified represents a path or device name.

If you look at TechNet for Rename-Item you will see under the description for -NewName

Specifies the new name of the item. Enter only a name, not a path and name. If you enter a path that is different from the path that is specified in the Path parameter, Rename-Item generates an error.

There is no need to set the path for the NewName since you already did that with -Path . Remove the path component and leave the file name like Ryan suggested.

Rename-Item -Path "$LogsDestFolder\MyLog.log" -NewName "$file.log"
#or
Ren "$LogsDestFolder\MyLog.log" "$file.log"

Always a good idea to put paths in quotes. You need to in this case anyway to prevent a parsing error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM