【问题标题】:PowerShell Move Script - Dynamic DirectoryPowerShell 移动脚本 - 动态目录
【发布时间】:2018-05-01 18:46:10
【问题描述】:

我正在创建一个 PowerShell 移动脚本,它将根据文件名动态创建目录,然后根据文件名移动文件。除了默认目录路径外,此脚本的每个方面都有效。知道如何自动将其更改为脚本位置的目录。我试过了: cd $PSScriptroot 没有运气

这是我的帮助文件,用于创建文件。在我们的真实环境中,文件已经生成: cd $PSScriptroot New-Item -Path ($PSScriptroot + '\59_' + '20180101' + '.txt') -ItemType file New-Item -Path ($PSScriptroot + '\59_' + '20180102' + '.txt') -ItemType file New-Item -Path ($PSScriptroot + '\59_' + '20180103' + '.txt') -ItemType file New-Item -Path ($PSScriptroot + '\59_' + '20180104' + '.txt') -ItemType file ... New-Item -Path ($PSScriptroot + '\59_' + '20181231' + '.txt') -ItemType file

这是脚本:

`cd $PSScriptroot
$FileNameArray = Get-ChildItem -Filter "*.txt"
$FileNameArray = $FileNameArray -replace "....$"
$FileNameArray = $FileNameArray.Substring(3)
Foreach ($f in $FileNameArray)
{
    #Year
    $Year = $f -replace "....$"
    $FilePathY = "$PSScriptroot\$Year" 
    if (Test-Path $FilePathYM ){
    }
    else {New-Item -ItemType Directory -Path ($FilePathY)}
    #Month
    $Month = $f.Substring(4) -replace "..$"
    $FilePathYM = "$PSScriptroot\$Year\$Month"
     if (Test-Path $FilePathYM ){
    }
    else {New-Item -ItemType Directory -Path ($FilePathYM)}
    #Days
    $Day = $f.Substring(6)
    $FilePathYMD = $PSScriptroot +'\'+ $Year +'\'+ $Month +'\'+ $Day
     if (Test-Path $FilePathYMD){
    }
    else {New-Item -ItemType Directory -Path ($FilePathYMD)}
}
Foreach($file in $FileNameArray)
{
        $Year = $file -replace "....$"
        $Month = $file.Substring(4) -replace "..$"
        $Day = $file.Substring(6)`

        Move-Item ($PSScriptroot + '\59_' + $file + '.txt' ) ($PSScriptroot + '\' + $Year + '\' + $Month + '\' + $Day)
}`

【问题讨论】:

  • “除默认目录路径外,此脚本的所有方面都有效”是什么意思?怎么了? (记住:没有人能看到你的屏幕!)
  • 文件路径设置为用户默认目录。因此文件通常会移动到 C:\ 驱动器或用户设置为默认目录的任何位置。
  • 但文件已按计划移动到正确的文件夹,并且文件夹创建时没有错误。
  • “文件路径设置为用户默认目录”是什么意思?什么用户?什么目录?您的问题似乎缺少大量信息。抱歉,我无法提供帮助。
  • 如果您想要脚本在Get-Location 中运行的当前位置,可能就是您要查找的位置

标签: powershell


【解决方案1】:

根据我对 cme​​ts 的了解,我了解到脚本运行良好且没有错误,并且您想要指向脚本位置的路径

知道如何自动将其更改为脚本位置的目录。我试过了: cd $PSScriptroot 没有运气

试试这个:(已测试:它指向脚本所在的目录)

$rootPath = split-path -parent $MyInvocation.MyCommand.Definition
echo "Path is: $rootPath"

$PSScriptRoot 在 PowerShell 版本 3

中引入

提示:尝试$PSVersionTable.PSVersion 了解版本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-08-09
    • 1970-01-01
    • 1970-01-01
    • 2020-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    相关资源
    最近更新 更多