使用 PowerShell 将文件复制到随机命名的目录

Copy file to randomly named directory with PowerShell

#copies program directory

copy-item .\iphone -Recurse c:\Users$env:username -force

#sets file I want to copy to unknown directory name as $file1

C:\Users$env:username\iphone\.filename = $file1

#sets unknown folder location to $location1 which is a randomly named directory 
#under this subfolder in appdata\Roaming\parentfolder761253721536721(random //number) , 
#name is just a string of numbers

Get-ChildItem  C:\Users$env:username\AppData\Roaming\parentfolder = $location1

//attempts to copy file to location

copy-item $file1 $location1

Powershell 的新手。我确信我正在使这比它需要的更难。这就像我尝试执行此操作的第 10 个脚本,我觉得我离答案越来越远。一直在 technet 上查看示例,只是没有找到任何用于设置我试图将文件复制到的未知目录路径的东西。

如果您的回答不介意解释代码的作用以便我学习,我将不胜感激。

给变量赋值时,变量引用需要放在=的左边:

$file1 = Get-Item C:\Users$env:username\iphone\.filename
$location1 = Get-ChildItem C:\Users$env:username\AppData\Roaming\parentfolder 

$file1 |Copy-Item -Destination $location1.FullName

假设你只有一个"random folder":

## Translates to C:\Users\%USERNAME%\AppData\Roaming
$Parent = "$env:AppData\ParentFolder"

$Destination = Get-ChildItem -Path $Parent | Where-Object { $_.PSIsContainer }
$File = "$env:UserProfile\iphone\.filename"

Copy-Item -Path $File -Destination $Destination