[英]Powershell Script to copy file to new folder
I am fairly new to Powershell scripting and I have to write a script that copies a file from a certain path and pastes it in a new folder that is created with the current date.我对 Powershell 脚本相当陌生,我必须编写一个脚本来从某个路径复制文件并将其粘贴到使用当前日期创建的新文件夹中。 This is what I got so far.这是我到目前为止所得到的。
New-Item -Path "c:\users\random\desktop\((Get-Date).ToString('yyyy-MM-dd'))" -ItemType Directory
copy-item c:\users\random\desktop\rand.txt 'c:\users\random\desktop\((Get-Date).ToString('yyyy-MM-dd'))
When I run this script, it creates a directory called ((Get-Date).ToString('yyyy-MM-dd'))
instead of today's date.当我运行此脚本时,它会创建一个名为((Get-Date).ToString('yyyy-MM-dd'))
而不是今天的日期。
When this script runs, it has to create a directory with the current date and paste that file in it.当此脚本运行时,它必须创建一个包含当前日期的目录并将该文件粘贴到其中。 So if I were to run it once a day for 5 days, it should create 5 different folders with the file in each of them.因此,如果我每天运行一次,持续 5 天,它应该创建 5 个不同的文件夹,每个文件夹中都有该文件。 Any help is much appreciated.任何帮助深表感谢。
If you are looking to keep with those 2 lines of code you need to wrap the Get-Date
portion in $()
.如果您希望保留这两行代码,则需要将Get-Date
部分包装在$()
。 This tells PS to resolve that code before using the string inside the double quotes.这告诉 PS 在使用双引号内的字符串之前解析该代码。
So your code would look like this:所以你的代码看起来像这样:
New-Item -Path "c:\users\random\desktop\$((Get-Date).ToString('yyyy-MM-dd'))" -ItemType Directory
copy-item c:\users\random\desktop\rand.txt "c:\users\random\desktop\$((Get-Date).ToString('yyyy-MM-dd'))"
However, you could have one flaw if your script is ever executed within microseconds of midnight: Each command would get a separate date.但是,如果您的脚本在午夜的几微秒内执行,您可能会遇到一个缺陷:每个命令都会获得一个单独的日期。
A better method to use is to simply grab the date in a variable and use that in both of your commands.更好的使用方法是简单地获取变量中的日期并在您的两个命令中使用它。 It will also make it more readable:它还将使其更具可读性:
$cDate = Get-Date -format yyyy-MM-dd
$NewPath = "C:\Users\random\desktop\$cDate"
New-Item -Path $NewPath -ItemType Directory
Copy-Item c:\users\random\desktop\rand.txt $NewPath
This would ensure you get the same date value if you happen to pass midnight when it runs.如果您在运行时碰巧过了午夜,这将确保您获得相同的日期值。 Although, that is probably not going to be an issue it doesn't hurt to be safe.虽然,这可能不会成为问题,但安全无害。
you miss a dollar sign before the bracket你错过了括号前的美元符号
"c:\\users\\random\\desktop**$**((Get-Date).ToString('yyyy-MM-dd'))" "c:\\users\\random\\desktop**$**((Get-Date).ToString('yyyy-MM-dd'))"
Create a variable to store your GetDate, then convert it in to a string.创建一个变量来存储您的 GetDate,然后将其转换为字符串。
$currentdate = date $currentdate2 = $currentdate.ToString("yyyy-MM-dd")
Hence your code folder path will be 'c:\\users\\random\\desktop\\$currentdate2'因此您的代码文件夹路径将是 'c:\\users\\random\\desktop\\$currentdate2'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.