【问题标题】:match file with folder directory and insert each file found to its folder directory将文件与文件夹目录匹配并将找到的每个文件插入其文件夹目录
【发布时间】:2021-03-28 11:03:15
【问题描述】:

代码:

c:\Users\H107371a\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
c:\Users\m763671\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
c:\Users\W575288\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

csv 文件包含:

Full Name Name
c:\      H107371a
c:\      m763671
c:\      W575288 
$source = Read-Host -Prompt 'Insert SOURCE computer'
$destination = Read-Host -Prompt 'Insert DESTINATION computer'
$InvoiceList = Import-CSV -Path C:\$source-PREP.csv
 for each($list in $InvoiceList){
$Name=$($list.name)
Get-Child Item -Path 'C:\' -Filter *.cmd | where {$_.Name -like "*$name*" } |
 Set-Content -Path ('C:\{0}-Config.cmd' -f $_) -Force}
 Copy-Item -Destination |  where {$_.Name -like "*$name*" } "\\$destination\c$\Users\{0}\App Data\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\" -Force 

【问题讨论】:

    标签: powershell object foreach merge


    【解决方案1】:

    虽然不太确定,但我想你想:

    • 读取 csv,其中 Name 列必须对应于 C:\ 驱动器中 .cmd 文件的名称
    • 如果找到此类文件,请在远程计算机上以其他名称复制该文件

    为此,您可以使用以下代码:

    $source      = Read-Host -Prompt 'Insert SOURCE computer'
    $destination = Read-Host -Prompt 'Insert DESTINATION computer'
    
    $InvoiceList = Import-CSV -Path "C:\$source-PREP.csv"
    
    # loop through the Names column from the CSV
    foreach($userName in $InvoiceList.Name) {
        # try and get a .cmd file with a basename like the name from the CSV
        $file = Get-ChildItem -Path 'C:\' -Filter '*.cmd' | Where-Object {$_.BaseName -like "*$userName*" } | Select-Object -First 1
        if ($file) {
            # create a new file name for the copy
            $newName = '{0}-Config.cmd' -f $userName
            $target  = '\\{0}\c$\Users\{1}\App Data\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\{2}' -f $destination, $userName, $newName
            Write-Host "Copying file '$($file.FullName)' to '$target'"
            $file | Copy-Item -Destination $target -WhatIf
        }
    }
    

    如您所见,Copy-Item 可以直接复制一个新名称的文件。

    -WhatIf 开关是为了您自己的安全。 有了,没有什么是复制品,控制台只会向您展示会发生什么。如果您觉得一切正常,请移除 -WhatIf 开关并再次运行代码。

    【讨论】:

    • @EnriqueTellez 这就是你想要的吗?请让我们知道这是否适合您(如果不适合,您有什么问题)
    猜你喜欢
    • 1970-01-01
    • 2022-12-03
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    • 2011-07-07
    • 2016-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多