Powershell: Copiar script de arquivo

Powershell: Copiar script de arquivo

Tentando fazer um script para copiar arquivos para várias máquinas com servidores.txt tendo vários nomes de servidores

Aqui está o código que usei até agora

# 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}

O erro que recebo é

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

Qualquer ajuda seria ótimo

Obrigado

Responder1

Não tenho certeza se você está executando o AD com o módulo ps, mas aqui está um script de cópia de arquivos que escrevi que contém uma pequena interface gráfica. Pode ser necessário um pouco de refinamento, mas altere as instalações para qualquer pasta em c:\ like $FolderOnC="Program Files\Autodesk".

  1. Coloque este script em uma pasta chamada copyfiles na unidade c: e execute-o
  2. Selecione o arquivo a ser copiado clicando em "Obter Arquivo"
  3. Clique na caixa de seleção "Dir" se quiser copiar o diretório inteiro
  4. Pesquise computadores pelo nome do domínio
  5. Selecione os computadores para os quais copiar
  6. Desmarque a caixa de seleção "Ping PC First" se você não consegue executar ping no PC, mas sabe que ele está ligado
  7. Clique em "Copiar arquivo"

Powershell: Copiar script de arquivo

#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

informação relacionada