创建文件夹时的Powershell动态路径

时间:2017-07-25 10:13:35

标签: powershell

我想创建一个文件夹,但我不知道如何使用变量来定义路径。

原样:

New-Item -ItemType directory -Path "C:\Users\tizio.caio\Desktop\BACKUP_$((Get-Date).ToString('yyyyMMdd'))"

我想将C:\Users\tizio.caio\Desktop\替换为变量,以便日后重做更容易。

3 个答案:

答案 0 :(得分:0)

假设您始终希望当前用户使用桌面,您可以使用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
}

答案 1 :(得分:0)

我会拆分目录和文件名,然后使用environment variable USERPROFILE

$var    = $env:USERPROFILE + "\Desktop\"
$backup = "BACKUP_$((Get-Date).ToString('yyyyMMdd'))"

New-Item -ItemType directory -Path "$var$backup"

答案 2 :(得分:0)

根据您想要的简单程度:

$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