我想创建一个文件夹,但我不知道如何使用变量来定义路径。Powershell创建文件夹时的动态路径
由于是:
New-Item -ItemType directory -Path "C:\Users\tizio.caio\Desktop\BACKUP_$((Get-Date).ToString('yyyyMMdd'))"
我想,以使未来的返修率更容易变量来代替C:\Users\tizio.caio\Desktop\
。
我想创建一个文件夹,但我不知道如何使用变量来定义路径。Powershell创建文件夹时的动态路径
由于是:
New-Item -ItemType directory -Path "C:\Users\tizio.caio\Desktop\BACKUP_$((Get-Date).ToString('yyyyMMdd'))"
我想,以使未来的返修率更容易变量来代替C:\Users\tizio.caio\Desktop\
。
假设你总是希望当前用户的桌面,你可以使用Environment.GetFolderPath()
method检索路径,然后使用Join-Path
cmdlet将其与目录名称相结合:
$DesktopPath = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::Desktop)
$DirectoryName = "BACKUP_$((Get-Date).ToString('yyyyMMdd'))"
$DirectoryPath = Join-Path $DesktopPath $DirectoryName
你可以打包成一个功能需要-Path
参数,如果你希望能够覆盖它:
function New-BackupDirectory
{
param(
[ValidateScript({Test-Path $_ -PathType Container})]
$Path = [System.Environment]::GetFolderPath([System.Environment+SpecialFolder]::Desktop)
)
$DirectoryName = "BACKUP_$((Get-Date).ToString('yyyyMMdd'))"
$DirectoryPath = Join-Path $Path $DirectoryName
mkdir $DirectoryPath
}
我会分裂的目录和文件名,并使用environment variableUSERPROFILE
$var = $env:USERPROFILE + "\Desktop\"
$backup = "BACKUP_$((Get-Date).ToString('yyyyMMdd'))"
New-Item -ItemType directory -Path "$var$backup"
取决于你想如何简单去:
$folderpath = "C:\Users\tizio.caio\Desktop"
New-Item -ItemType directory -Path "$folderpath\BACKUP_$((Get-Date).ToString('yyyyMMdd'))"
或者你也可以将多个变量:
$folderpath = "C:\Users\tizio.caio\Desktop"
$backuppath = "$folderpath\BACKUP_$((Get-Date).ToString('yyyyMMdd'))"
New-Item -ItemType directory -Path $backuppath
感谢马蒂亚斯,没有,用户的桌面是不是最后的位置..我尝试了类似于你的东西,但创建字符串时一直失败:New-Item -ItemType directory -Path“C:\ Users \ tizio.caio \ Desktop \ BACKUP_ $((Get-Date).ToString('yyyyMMdd'))” – Alex
你是什么意思“失败”?请更具体地说明你想达到什么目的,以及你试图做什么失败 –
我的意思是文件夹没有被创建.. 我尝试设置一个变量并在路径中使用它,但没有任何结果。 – Alex