Powershell: 파일 스크립트 복사

Powershell: 파일 스크립트 복사

여러 서버 이름이 있는 server.txt를 사용하여 여러 컴퓨터에 파일을 복사하는 스크립트를 만들려고 합니다.

지금까지 사용한 코드는 다음과 같습니다.

# This file contains the list of servers you want to copy files/folders to
$a = Get-Content "C:\0000_scripts\servers.txt" 

# This is the file/folder(s) you want to copy to the servers in the $computer 
variable
$source = "C:\0000_scripts\a\*.*"

# The destination location you want the file/folder(s) to be copied to
$destination = "C$\Program Files\Autodesk\"

#The command below pulls all the variables above and performs the file copy
foreach ($computer in $a) {Copy-Item $source -Destination 
"\\$computer\$destination" -Recurse}

내가 얻는 오류는 다음과 같습니다.

Copy-Item : The network path was not found
At C:\0000_scripts\copy2.ps1:11 char:28
+ ... ter in $a) {Copy-Item $source -Destination "\\$computer\$destination" 
...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : NotSpecified: (:) [Copy-Item], IOException
+ FullyQualifiedErrorId : System.IO.IOException,Microsoft.PowerShell.Commands.CopyItemCommand

어떤 도움이라도 좋을 것입니다.

감사해요

답변1

ps 모듈을 사용하여 AD를 실행하고 있는지 확실하지 않지만 여기에 내가 작성한 멋진 작은 GUI가 포함된 파일 복사 스크립트가 있습니다. 약간의 개선을 사용할 수 있지만 설치를 c:\ like 의 폴더로 변경합니다 $FolderOnC="Program Files\Autodesk".

  1. 이 스크립트를 c: 드라이브의 copyfiles 폴더에 넣은 다음 실행하세요.
  2. "파일 가져오기"를 클릭하여 복사할 파일을 선택합니다.
  3. 전체 디렉터리를 복사하려면 "Dir" 확인란을 클릭하세요.
  4. 도메인에서 이름으로 컴퓨터 검색
  5. 복사할 컴퓨터를 선택하세요.
  6. PC를 핑할 수 없지만 PC가 켜져 있다는 것을 알고 있는 경우 "Ping PC First" 확인란을 선택 취소하세요.
  7. "파일 복사"를 클릭하세요.

Powershell: 파일 스크립트 복사

#Folder on C drive to copy to
$FolderOnC = "installs"

Add-Type -Name Window -Namespace Console -MemberDefinition '
[DllImport("Kernel32.dll")]
public static extern IntPtr GetConsoleWindow();

[DllImport("user32.dll")]
public static extern bool ShowWindow(IntPtr hWnd, Int32 nCmdShow);
'

Function Show-Console {
$consolePtr = [Console.Window]::GetConsoleWindow()
[Console.Window]::ShowWindow($consolePtr, 5)
}

Function Hide-Console {
$consolePtr = [Console.Window]::GetConsoleWindow()
[Console.Window]::ShowWindow($consolePtr, 0)
}

Function Get-FileName($initialDirectory)
{
    [System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null
    $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
    $OpenFileDialog.initialDirectory = $initialDirectory
    $OpenFileDialog.ShowDialog() | Out-Null
    $OpenFileDialog.filename
}

[xml]$xaml = @"
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:BlogPostIII"
    x:Name="Window" Title="Copy Files Tool" SizeToContent="WidthAndHeight" WindowStartupLocation="CenterScreen" WindowStyle="None" Topmost="True" ResizeMode="NoResize" AllowsTransparency="True" Background="Transparent" Opacity=".95" FocusManager.FocusedElement="{Binding ElementName=tb_CName}">
    <Border x:Name="MainBorder" Margin="10" CornerRadius="15" BorderThickness="10" Padding="0" Height="557" Width="706" Background="#FF4F5060">
        <Border.Effect>
            <DropShadowEffect x:Name="DSE" Color="Black" Direction="270" BlurRadius="15" ShadowDepth="3" Opacity="0.7" />
        </Border.Effect>

        <Grid x:Name="background" Width="665" Height="557" HorizontalAlignment="Left" VerticalAlignment="Top" Margin="0.4,0.4,0,-20.6">
            <Grid.RowDefinitions>
                <RowDefinition Height="455*"/>
                <RowDefinition Height="102*"/>
            </Grid.RowDefinitions>
            <CheckBox x:Name="cb_Directory" Content="Dir" Height="20" HorizontalAlignment="Left" Margin="17,10,0,0" VerticalAlignment="Top" Width="43" FontWeight="Bold" Background="{x:Null}" Foreground="#FFADBD37"/>
            <Label x:Name="lb_File" Content="File to Be Copied:" HorizontalAlignment="Left" Margin="143,3,0,0" VerticalAlignment="Top" Width="112" FontWeight="Bold" Background="{x:Null}" Foreground="#FFADBD37"/>
            <Button x:Name="btn_GetFile" Content="Get File" HorizontalAlignment="Left" Margin="75,6,0,0" Width="60" Height="20" VerticalAlignment="Top"/>
            <Label x:Name="lb_FileCopy" Content="none" HorizontalAlignment="Left" Margin="258,3,0,0" VerticalAlignment="Top" Width="447" FontWeight="Bold" Background="{x:Null}" Foreground="#FFADBD37"/>
            <Label x:Name="lb_CName" Content="Computer Name:" HorizontalAlignment="Left" Margin="10,29,0,0" VerticalAlignment="Top" Width="113" FontWeight="Bold" Foreground="#FFADBD37"/>
            <TextBox x:Name="tb_CName" HorizontalAlignment="Left" Height="23" Margin="121,32,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120"/>
            <Button x:Name="btn_FindComputers" IsDefault="True" Content="Find Computers" HorizontalAlignment="Left" Margin="251,34,0,0" Width="90" Height="20" VerticalAlignment="Top" RenderTransformOrigin="1.437,-0.191"/>

            <ListView x:Name="lv_ADComputers" HorizontalAlignment="Left" Height="249" Margin="17,64,-25,0" VerticalAlignment="Top" Width="655" AllowDrop="True" SelectionMode="Extended">
                <ListView.View>
                    <GridView>
                        <GridViewColumn Width="673" Header="Computers" DisplayMemberBinding="{Binding Computers}"/>
                    </GridView>
                </ListView.View>
            </ListView>

            <TextBox x:Name="tb_Updates" IsReadOnly = "True" AcceptsTab="True" AcceptsReturn="True" TextWrapping="Wrap" Background = "Black" Foreground = 'White' FontWeight = 'Bold' VerticalScrollBarVisibility = "Visible" Margin="17,320,-6,57.8" Grid.RowSpan="2"/>
            <Label x:Name="lb_Updates" Content="" HorizontalAlignment="Left" Margin="17,15,0,0" VerticalAlignment="Top" Width="673" FontWeight="Bold" Background="{x:Null}" Foreground="#FFADBD37" Height="85" Grid.Row="1"/>
            <CheckBox x:Name="cb_PingCheckbox" Content="Ping PC First" Height="20" HorizontalAlignment="Left" Margin="152,54.8,0,0" VerticalAlignment="Top" Width="121" FontWeight="Bold" Background="{x:Null}" Foreground="#FFADBD37" Grid.Row="1"/>
            <Button x:Name="btn_CopyFile" Content="Copy File" HorizontalAlignment="Left" Margin="293,51.8,0,0" Width="86" Height="20" VerticalAlignment="Top" Grid.Row="1"/>
            <Button x:Name="btn_Cancel" IsCancel="True" Content="Close" HorizontalAlignment="Left" Margin="391,51.8,0,0" VerticalAlignment="Top" Width="86" Grid.Row="1"/>
            <CheckBox x:Name="cb_PSCheckbox" Content="Show PS Window" Height="20" HorizontalAlignment="Left" Margin="491,51.8,0,0" VerticalAlignment="Top" Width="121" FontWeight="Bold" Background="{x:Null}" Foreground="#FFADBD37" Grid.Row="1"/>
        </Grid>
    </Border>
</Window>

"@
#<ListBox x:Name="tb_ADUsers" HorizontalAlignment="Left" Height="319" Margin="241,34,0,0" VerticalAlignment="Top" Width="308" Grid.RowSpan="2" AllowDrop="True" SelectionMode="Extended"/>

#Hide the Powershell Windows in background
    Hide-Console

Import-Module ActiveDirectory

#Global Variables
$LocalPath = $null
$RemotePath = $null
$Script:FileToCopy = $null
#$inputfile = Get-FileName "C:\powershell"
#End Global Declares

[string]$scriptPath = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent

# Initialize the Windows Presentation Framework
    Add-Type -AssemblyName PresentationFramework

# Create an object for the XML content
    $xamlReader = New-Object System.Xml.XmlNodeReader $xaml

# Load the content so we can start to work with it
    $mainform = [Windows.Markup.XamlReader]::Load($xamlReader)
# To see what options are avaliable
#   $mainform | Get-member Add* -MemberType Method -force > c:\powershell\get-member-main-form.txt

# Store Form Objects
    $xaml.SelectNodes("//*") | %{Set-Variable -Name ($_.Name) -Value $mainform.FindName($_.Name)}
    
# Make Window Draggable
    $mainform.Add_MouseDown({$this.DragMove()})

    
##################MAPS###################   

#Map: Output Textbox
    $tb_Updates = $mainform.FindName('tb_Updates')
#Action: Cancel Button
    $btn_Cancel.Add_Click({$mainform.Close()})
#Map: Ping/NoPing Checkbox
    $cb_PingCheckbox.IsChecked = $true
#Map: Show/Hide Powershell Windows Checkbox
    $cb_PSCheckbox.Add_Checked({Show-Console})
    $cb_PSCheckbox.Add_UnChecked({Hide-Console})

##################ACTIONS###################

#Action: Get Filename - Clicked##
    $btn_GetFile.Add_Click({
    $FileToCopy = Get-FileName("C:\copyfiles")
    If ($cb_Directory.IsChecked -eq $true){
    $FileToCopy = Split-Path $FileToCopy
    $lb_FileCopy.Content = $FileToCopy
    $tb_Updates.Text = "Directory: $FileToCopy `r"
    }
    Else{
    $lb_FileCopy.Content = $FileToCopy
    $tb_Updates.Text = "File: $FileToCopy `r"
    }
    })
#Action: Find Computers - Clicked##
    $btn_FindComputers.Add_Click({
    $CName = $tb_CName.Text
    $tb_Updates.AppendText(("{0}`r" -f "Finding Computers $CName"))
    #Clear the Users ListBox
        $lv_ADComputers.Items.Clear()
    if(!($CName -eq "")){Get-ADComputer -Filter "Name -like '$CName*'" | sort-object Name | ForEach {[void] $lv_ADComputers.Items.Add([PSCustomObject]@{Computers = $_.Name})}}
    })
#Action: Copy Files - Clicked##
    $btn_CopyFile.Add_Click({
    #Map: Computers Listbox to Variables
        $ADComputers = $lv_ADComputers.SelectedItems.Computers

    if(!($ADComputers -eq $null)){
        $tb_Updates.Clear
        
        #Start of Copying File
        ForEach ($Computer in $ADComputers){
            $script:DestPC = $Computer
            If ($cb_PingCheckbox.IsChecked -eq $true){
                If (-not (Test-Connection -quiet -count 1 -computer $Computer)) {
                $tb_Updates.AppendText(("{0}`r" -f "$Computer is Offline"))
                }
                Else{
                    $tb_Updates.AppendText(("{0}`r" -f "Copying File to $Computer"))
                    $FileToCopy = $lb_FileCopy.Content
                    Copy-Item "$FileToCopy" "\\$Computer\c$\$FolderOnC" -recurse -force
                    $tb_Updates.AppendText(("{0}`r" -f "File copied to $Computer"))
                    $tb_Updates.ScrollToEnd();

                }
            }
            Else{
                $FileToCopy = $lb_FileCopy.Content
                $tb_Updates.AppendText(("{0}`r" -f "Copying File to $Computer"))
                Copy-Item "$FileToCopy" "\\$DestPC\c$\$FolderOnC" -recurse -force
            }
        }
    }
    Else{$tb_Updates.Text = "No Computers Selected"}
    })#End of CopyFile Button Click

# Show the form
    $mainform.ShowDialog() | Out-Null

관련 정보