Powershell:复制文件脚本

Powershell:复制文件脚本

尝试编写一个脚本,将文件复制到具有多个服务器名称的 servers.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:\ 上的任何文件夹,例如$FolderOnC="Program Files\Autodesk"

  1. 将此脚本放在 c: 驱动器上名为 copyfiles 的文件夹中,然后运行它
  2. 点击“获取文件”选择要复制的文件
  3. 如果要复制整个目录,请点击“Dir”复选框
  4. 按域中的名称搜索计算机
  5. 选择要复制到的计算机
  6. 如果您无法 ping 通 PC 但知道它处于开启状态,请取消选中“首先 ping PC”复选框
  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

相关内容