Powershell - Trouble passing Validateset parameters into ForEach-Object, getting prompt - powershell

So I'm new to PowerShell, and I'm trying to get this function to work.
I have 2 ValidateSet arrays with 3 parameters. These parameters are supposed to change the file path and copy them over from one server to another. For some reason, I keep getting the command prompt for the parameters instead of them passing through. I'm guessing it's an issue with the ForEach-Object, but I'm at a loss. It IS, however, working for the $ArchivePath. I'm new, so please be gentle... TIA
param(
[Parameter(Mandatory = $true)]
[ValidateSet("One", "Two", "Three")]
[string[]]$Channel
,[Parameter(Mandatory = $true)]
[Alias('Phase')]
[ValidateSet("Devl", "Test", "Prod")]
[string[]]$Phase
,[Parameter(Mandatory = $false)]
[string]$FilenameFilter = '.csv'
,[Parameter(Mandatory = $false)]
[switch]$CreateTrigger
)
function ExitWithCode { param($exitcode) $host.SetShouldExit($exitcode); exit $exitcode }
$exitcode = 0
try {
# Get a list of files on the host server.
#
$files = Get-ChildItem -File -Path "\\ServerName\d\Extract\$Phase\FileTransfer\$Channel\Outbound"
# Destination directory.
#
$LocalPath = "\\ServerName\d\Extract\$Phase\FileTransfer\$Channel\Outbound" #for testing
# Set up folder name for Archive server. Formated as YYYYMMDDTHHMMSS YYYYMMDD --> Var_Date, 'T' --> Var_Constant & HHMMSS --> Var_Time
#
$Var_Date = get-date -UFormat "%Y-%m-%d"
$Var_Constant = 'T'
$Var_Time = get-date -UFormat "%H-%M-%S"
$Var_Fulldate = $Var_Date + $Var_Constant + $Var_Time
$ArchivePath = $env:USERPROFILE + "\Desktop\$Channel\$Var_Fulldate" #For testing
New-Item -Type Directory -Path $ArchivePath
if (-not (Test-Path -Path $ArchivePath -ErrorAction SilentlyContinue)) { $ArchivePath = $Env:TEMP }
#Look for files in Outbound directory and remove
Get-ChildItem -File -Path $LocalPath | ForEach-Object { Copy-Item $_.FullName } #Using copy instead of remove for test
$FileCount = 0
Write-Output Try2 #for testing
pause #for testing
foreach ($file in $files) {
if ((-not $file.IsDirectory) -and ($File.FullName -match $FilenameFilter)) {
$localfilename = $LocalPath + $file.Name
if (Test-Path $localfilename) { Copy-Item $localfilename }
try {
Copy-Item -Path $(Join-Path -Path $LocalPath -ChildPath $file.Name) -Destination $ArchivePath
#Remove files from outbound since they've been archived
#
#Remove-Item -Path $file.FullName
"Retrieved file $file"
$FileCount++
}
catch {
Write-Output Try13 #for testing
$exitcode = 13
"failed to retrieve $file"
}
finally {
$error.Clear()
}
}
}
}
catch {
Write-Output Try3
$exitcode = 14
}
finally {
Write-Output Try4
$error.Clear()
}
if ($CreateTrigger -and ($exitcode -eq 0) -and ($FileCount -gt 0)) {
New-Item -Path "$LocalPath\Trigger_File.trg" -ItemType File | Out-Null
}
#ExitWithCode $exitcode # take out for testing
The output:
PS C:\Users\me> \\Server\blah\USERS\me\My Documents\Folder\Get-FileName_t4.ps1
cmdlet Get-FileName_t4.ps1 at command pipeline position 1
Supply values for the following parameters:
Channel[0]: Three
Channel[1]:
Phase[0]: Devl
Phase[1]:
Directory: C:\Users\me\Desktop\Three
Mode LastWriteTime Length Name
---- ------------- ------ ----
d----- 11/22/2019 12:17 PM 2019-11-22T12-17-23
Try2
Press Enter to continue...:
Retrieved file File1_20191122080912.csv
Retrieved file File2_20191122080922.csv
Retrieved file File3_20191122080925.csv
Retrieved file File4_20191122080932.csv
Retrieved file File5_20191122080933.csv
Retrieved file File6_20191122080933.csv
Try4

You are getting prompted because you're not passing in those parameters but Mandatory=$true is set on the arguments you are getting prompted for. Since your session is interactive, it asks you to input the correct values. If you don't want to get prompted, provide the mandatory arguments:
"\\Server\blah\USERS\me\My Documents\Folder\Get-FileName_t4.ps1" -Channel Three -Phase Dev1
A couple of other things I noticed:
You don't need to provide Mandatory=$false, as Mandatory is $false by default
Setting an alias of Phase for the -Phase argument is also redundant

Related

PowerShell: Creating a set amount of files based on a parameter, with a running number to differentiate the files

So I have an assignment where I have to create an PowerShell script that takes three parameters, "$foldername", "$filename" and "$number".
The script checks if the folder "$foldername" exists and if not, creates it. After that it creates as many new files named "$filename" as "$number" specifies. After that it reports how many files have been created and lists them.
What I have so far.
Param (
[string]$foldername,
[string]$filename,
$number=1
)
if ((Test-Path -Path $foldername) -ne $true) {
new-item -path $foldername -ItemType directory #if the folder doesn't exist, create it.
}
$new_file= $foldername+"\$_"+$filename #save the path and name of the new file to an variable
if ((Test-Path -Path $new_file* -PathType leaf) -eq $true) {
Write-Host "$filename already exists in $foldername"
break #if a file with a name that contains $filename in it exists in $foldername, break and do not create any new files.
}
$null=1..$number | foreach { new-item -path $foldername -name $_$filename } #create new files using foreach.
write-host ("Created $number new files") #tell the user how many files were created
Get-ChildItem -path $foldername | where-object Name -like *$filename* | format-table Name #show the created files in a table format, formatted by name
There are a few problems and scuffed solutions in this script, but the main problem is the creation of the new files. Since the name of the new files come from $filename, simply running the script like so:
./script.ps1 -foldername C:\users\example\testing -filename "test.txt" -number 5
Would not work since it tries to create 5 files named "test.txt" and will just return errors.
I sort of solved it by using "foreach" and naming the files $_$filename which creates
1test.txt
2test.txt
...
5test.txt
But I found out that the correct way would be:
test1.txt
test2.txt
...
test5.txt
The number should be running in the filename somehow, but I am not sure how to do that.
Bonus points if you figure out how to check if the $filename files already exist in the target folder.
It's good to use Test-Path however I don't see a need for it here, you can use $ErrorAction = 'Stop' so that if the folder exists the script would instantly stop with a warning message. On the other hand, if the folder is a new folder there is no way the files already exist.
Param (
[parameter(Mandatory)]
[string]$FolderName,
[parameter(Mandatory)]
[string]$FileName,
[int]$Number = 1
)
$ErrorActionPreference = 'Stop'
try {
$newFolder = New-Item -Path $FolderName -ItemType Directory
}
catch {
# If the folder exists, show this exception and stop here
Write-Warning $_.Exception.Message
break
}
$files = 1..$Number | ForEach-Object {
# If this is a new Folder, there is no way the files already exist :)
$path = Join-Path $newFolder.FullName -ChildPath "$FileName $_.txt"
New-Item -Path $path -ItemType File
}
Write-Host 'Script finished successfully.'
$newFolder, $files | Format-Table -AutoSize
EDIT: I might have missed the point where you want to create the files in the folder even if the folder already exists, in that case you could use the following:
Param (
[parameter(Mandatory)]
[string]$FolderName,
[parameter(Mandatory)]
[string]$FileName,
[int]$Number = 1
)
$ErrorActionPreference = 'Stop'
$folder = try {
# If the Folder exists get it
Get-Item $FolderName
}
catch {
# If it does not, create it
New-Item -Path $FolderName -ItemType Directory
}
$files = 1..$Number | ForEach-Object {
$path = Join-Path $folder.FullName -ChildPath "$FileName $_.txt"
try {
# Try to create the new file
New-Item -Path $path -ItemType File
}
catch {
# If the file exists, display the Exception and continue
Write-Warning $_.Exception.Message
}
}
Write-Host "Script finished successfully."
Write-Host "Files created: $($files.Count) out of $Number"
$files | Format-Table -AutoSize

Why is powershell switching directories mid code on copy-item when the variable is already defined?

I have some code that checks a target file, waits for a change, and I want it to only move the most recent files based on their LastWriteTime Value. However, every time I change a file within the target directory nothing is copying over and I am having the copy-item directory change to "C:\Users\run". I
it recognizes that there are files to copy and even states their filename when throwing the error. What can I do in this situation to make sure my copy-item command is copying from my target directory?
Code for Reference:
$File = "C:\Users\run\Desktop\Target"
$destinationFolder = "c:\users\run\desktop\dest"
$maxDays = "-1"
$maxMins = "20"
$date = Get-Date
Write-Host "Waiting For File To Change in Job Cloud..."
$Action = '
dateChecker
Write-Host "Moving Files From Job Cloud To Server Shares... Please Do Not Disrupt This Service"
write-host "files copied to job cloud..."
exit
'
$global:FileChanged = $false
function dateChecker {
Foreach($File in (Get-ChildItem -Path $File)){
if($File.LastWriteTime -lt ($date).AddMinutes($maxMins)){
Write-Host "Moving Files From Job Cloud To Server Shares... Please Do Not Disrupt This Service"
Copy-Item -Path $File -Destination $destinationFolder -recurs #-ErrorAction #silentlyContinue
}
}
}
while($true) {
function Wait-FileChange {
param(
[string]$File,
[string]$Action
)
$FilePath = Split-Path $File -Parent
$FileName = Split-Path $File -Leaf
$ScriptBlock = [scriptblock]::Create($Action)
$Watcher = New-Object IO.FileSystemWatcher $FilePath, $FileName -Property #{
IncludeSubdirectories = $false
EnableRaisingEvents = $true
}
$onChange = Register-ObjectEvent $Watcher Changed -Action {$global:FileChanged = $true}
while ($global:FileChanged -eq $false){
Start-Sleep -Milliseconds 100
}
& $ScriptBlock
Unregister-Event -SubscriptionId $onChange.Id
}
Wait-FileChange -File $File -Action $Action
}
PowerShell is not switching directories - although I can certainly see why you'd think that based on the behavior. The explanation is closer than you might think though:
The -Path parameter takes a [string] argument.
$File is not a string - it's a [FileInfo] object - and PowerShell therefore converts it to a string before passing it to Copy-Item -Path. Unfortunately, this results in the name of the file (not the full path) being passed as the argument, and Copy-Item therefore has to resolve the full path, and does so relative to the current working directory.
You can fix this by passing the full path explicitly to Copy-Item -LiteralPath:
Copy-Item -LiteralPath $File.FullName ... |...
or you can let the pipeline parameter binder do it for you by piping the $File object to Copy-Item:
$File |Copy-Item ... |...
Why -LiteralPath instead of -Path? -Path accepts wildcard patterns like filenameprefix[0-9] and tries to resolve it to a file on disk, meaning if you have to operate on files with [ or ] in the name, it'll result in some unexpected behavior :)

Execute app install if test-path equals false

I'm working on a script to test if a file exists in a target directory, and if false, execute an application installation.
The goal is to test if the file exists and if it does, abort with a log as to why. If the file does not exist, then the application installer should be executed.
I first tried creating a dummy file using New-Item to create both the directory and the dummy file.
New-Item -ItemType Directory -Force -Path "C:\temp"
New-Item -Path "C:\temp\vistaupdated.txt" -ItemType "file" -Value "Updated"
# Test if computer is updated
$file = Get-Content "C:\temp\vistaupdated.txt"
$containsWord = $file | %{$_ -match "Updated"}
if ($containsWord -contains $false) { ###start running the install stuff
However, this errors out if the file does not exist with an Object-NotFound. I then decided to switch tactics and use Test-Path:
$file = Test-Path -Path "C:\temp\vistaupdated.txt"
if ($file -eq $false) { ###start running the install stuff
In this case, I believe $file would evaluate to False and as a result execute the installation. On execution all I get is a return of the script's path:
PS C:\users\me\desktop> $filetest = Test-Path -Path "C:\temp\vistaupdated.txt"
PS C:\users\me\desktop> $filetest
False
PS C:\users\me\desktop> C:\Users\me\Desktop\vistaupdate.ps1
The above reference to the PS1 file doesn't execute. It's only what's returned if I run the script through ISE as administrator. If I do the same with the console, then the output is blank without any action taken.
# Test if computer is updated
$file = Test-Path -Path "C:\temp\vistaupdated.txt"
if ($file -eq $False) {
#package repository
$VistaInsPath = "\\apps\shared\me\vista\6.16.0"
#package installation command
$VistaInsEXE = "VistaClient.6.16.0.896"
#package installation parameters
$VistaInsParam = "/s /v/qn"
#logging
$logFile = "\\apps\shared\me\vista\6.16.0\log\vista_install.log"
#timestamp for logging
function Get-TimeStamp {
return "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date)
}
#main function
function Vista-Install {
$errFlag = $false
try {
$cmdLine = "$VistaInsPath$VistaInsEXE"
Start-Process -FilePath $cmdLine -ArgumentList $VistaInsParam -Wait
} catch {
$(Get-TimeStamp) + "[" + $env:COMPUTERNAME +"]" + "[" + $env:USERNAME +"]" + "Error has occurred: " + $_.Exception.Message | Out-File $logFile -Append
$error.Clear()
$errFlag = $true
}
#if no error, notify success
if (-not $errFlag) {
$(Get-TimeStamp) + "[" + $env:COMPUTERNAME +"]" + "[" + $env:USERNAME +"]" + "Completed Successfully" | Out-File $logFile -Append
}
# Place dummy file to tag computer as updated
New-Item -ItemType Directory -Force -Path "C:\temp"
New-Item -Path "C:\temp\vistaupdated.txt" -ItemType "file" -Value "Updated"
}
} else {
$(Get-TimeStamp) + "[" + $env:COMPUTERNAME +"]" + "[" + $env:USERNAME +"]" + "Computer Already Updated. Aborting" | Out-File $logFile -Append
}
If Test-Path is False, then the installer should kick off in the first if statement. Instead the script spits back the path of the script itself and exits.
As #lit already pointed out in the comments to your question, you never invoke the function Vista-Install, so it's rather unsurprising that your code doesn't actually do anything. And you shouldn't define functions (or your $Vista* and $LogFile variables) in a nested scope anyway. The code in the else branch won't be able to find Get-TimeStamp or $LogFile with what you currently have.
Allow me to suggest some improvements:
Your logging code has a lot of redundant information. Instead of defining a function just for generating the timestamp, make a function that takes the log message as a parameter and otherwise completely encapsulates the logging.
$cmdLine = "$VistaInsPath$VistaInsEXE" will combine directory path and filename without a path separator, resulting in an incorrect path. Either put a backslash between the variables:
$cmdLine = "$VistaInsPath\$VistaInsEXE
or (better) use the Join-Path cmdlet, as #Theo suggested:
$cmdLine = Join-Path $VistaInsPath $VistaInsEXE
Put Test-Path directly in the if condition. There's no need to assign the result to a variable first.
The variable $errFlag is pointless. Just put the log statement after Start-Process. If an exception is thrown the code will go to the catch block without reaching that statement.
I assume you want the file vistaupdated.txt created only if the installation didn't throw an error, so that code should go in the try block too.
New-Item outputs an object for the item. You may want to suppress that.
The function Vista-Install doesn't make much sense either, as it would only install one specific program. Since it has very little code to begin with I would just drop it and put the code directly in the "then" branch. But if you wanted it to be a function you should name and parametrize it properly: pass program and arguments as parameters (preferably named after the parameters of Start-Process, so you can simply splat the $PSBoundParameters variable) and use a name conforming to the naming conventions:
function Install-Program {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true, Position=0)]
[string]$FilePath,
[Parameter(Mandatory=$false, Position=1)]
[string]$ArgumentList = #()
)
try {
Start-Process #PSBoundParameters
...
} catch {
...
}
}
Install-Program -FilePath (Join-Path $VistaInsPath $VistaInsEXE) -ArgumentList $VistaInsParam
Simplified code:
$VistaInsPath = '\\apps\shared\me\vista\6.16.0'
$VistaInsEXE = 'VistaClient.6.16.0.896'
$VistaInsParam = '/s', '/v', '/qn'
$logFile = '\\apps\shared\me\vista\6.16.0\log\vista_install.log'
function Write-Log {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$false)]
[string]$Message = ''
)
"[{0:MM/dd/yy HH:mm:ss}]`t[{1}\{2}]`t{3}" -f (Get-Date), $env:COMPUTERNAME, $env:USERNAME, $Message |
Out-File $script:LogFile -Append
}
if (-not (Test-Path -Path 'C:\temp\vistaupdated.txt')) {
$cmdLine = Join-Path $VistaInsPath $VistaInsEXE
try {
Start-Process -FilePath $cmdLine -ArgumentList $VistaInsParam -Wait
New-Item -Path 'C:\temp' -Type Directory -Force | Out-Null
New-Item -Path 'C:\temp\vistaupdated.txt' -Type File -Value 'Updated' | Out-Null
Write-Log 'Completed successfully.'
} catch {
Write-Log ('Error has occurred: {0}' -f $_.Exception.Message)
}
} else {
Write-Log 'Computer already updated. Aborting.'
}
Arguments could be made for flipping "then" and "else" branch to avoid a negated condition:
if (Test-Path -Path 'C:\temp\vistaupdated.txt') {
Write-Log 'Computer already updated. Aborting.'
} else {
$cmdLine = ...
...
}
or exiting from the script directly if the file exists in order to avoid an else branch entirely:
if (Test-Path -Path 'C:\temp\vistaupdated.txt') {
Write-Log 'Computer already updated. Aborting.'
exit
}
$cmdLine = ...
...

Powershell script executed on each file in a folder?

I currently have a powershell script, which print out some information regarding the files which passed in as argument..
The command for executing the script, it done as such:
.\myscript.ps1 -accessitem C:\folder
I want to apply the script on all files and folder on the drive C:, is it possible i for loop to list all files, and pass the path as argument for the script?
The script:
[CmdletBinding()]
Param (
[Parameter(Mandatory=$True,Position=0)]
[String]$AccessItem
)
$ErrorActionPreference = "SilentlyContinue"
If ($Error) {
$Error.Clear()
}
$RepPath = Split-Path -Parent $MyInvocation.MyCommand.Definition
$RepPath = $RepPath.Trim()
$str = $AccessItem -replace ':',''
$str = $AccessItem -replace '/','.'
$FinalReport = "$RepPath\"+$str+".csv"
$ReportFile1 = "$RepPath\NTFSPermission_Report.txt"
If (!(Test-Path $AccessItem)) {
Write-Host
Write-Host "`t Item $AccessItem Not Found." -ForegroundColor "Yellow"
Write-Host
}
Else {
If (Test-Path $FinalReport) {
Remove-Item $FinalReport
}
If (Test-Path $ReportFile1) {
Remove-Item $ReportFile1
}
Write-Host
Write-Host "`t Working. Please wait ... " -ForegroundColor "Yellow"
Write-Host
## -- Create The Report File
$ObjFSO = New-Object -ComObject Scripting.FileSystemObject
$ObjFile = $ObjFSO.CreateTextFile($ReportFile1, $True)
$ObjFile.Write("NTFS Permission Set On -- $AccessItem `r`n")
$ObjFile.Close()
$ObjFile = $ObjFSO.CreateTextFile($FinalReport, $True)
$ObjFile.Close()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($ObjFSO) | Out-Null
Remove-Variable ObjFile
Remove-Variable ObjFSO
If((Get-Item $AccessItem).PSIsContainer -EQ $True) {
$Result = "ItemType -- Folder"
}
Else {
$Result = "ItemType -- File"
}
$DT = Get-Date -Format F
Add-Content $ReportFile1 -Value ("Report Created As On $DT")
Add-Content $ReportFile1 "=================================================================="
$Owner = (Get-Item -LiteralPath $AccessItem).GetAccessControl() | Select Owner
$Owner = $($Owner.Owner)
$Result = "$Result `t Owner -- $Owner"
Add-Content $ReportFile1 "$Result `n"
(Get-Item -LiteralPath $AccessItem).GetAccessControl() | Select * -Expand Access | Select IdentityReference, FileSystemRights, AccessControlType, IsInherited, InheritanceFlags, PropagationFlags | Export-CSV -Path "$RepPath\NTFSPermission_Report2.csv" -NoTypeInformation
Add-Content $FinalReport -Value (Get-Content $ReportFile1)
Add-Content $FinalReport -Value (Get-Content "$RepPath\NTFSPermission_Report2.csv")
Remove-Item $ReportFile1
Remove-Item "$RepPath\NTFSPermission_Report2.csv"
Invoke-Item $FinalReport
}
If ($Error) {
$Error.Clear()
}
I would prefer a outside command doing this, as workings of the script should not be altered, it it used for single file testing..
There are two ways to do this:
Add -Recurse Flag to the script
Run the script on each directory
I'm going with option two since the script looks complicated enough that I don't want to touch it.
$path_to_script = "C:\path\to\myscript.ps1"
$start_directory = "C:\folder"
# Call Script on Parent Directory
& "$path_to_script" -AccessItem "$start_directory"
# Call Script on any Child Directories within the "$start_directory"
foreach($child in (ls "$start_directory" -Recurse -Directory))
{
$path = $child.FullName
& "$path_to_script" -AccessItem "$path"
}
Basically, I'm calling the script on the parent directory and any sub-directories within the parent directory.

Loop in powershell

Hello Guys need some help, tips with script:
$path = ".\" # path do txt
$server = "server" # server.txt
$paczki = ".\paczki\"
$missingi = "$path\$server.txt"
$plik = get-content $missingi
foreach ($j in $plik) {
Write-Output "1"
$wynik = Get-ChildItem "$paczki" | ? {$_.name -match "$j"}
if ($wynik -eq $null) {
# Write-Host $i
}
else {
Write-Output "2"
Write-Host $wynik "znaleziono"
Copy-Item $paczki\$wynik -Destination \\$server\c$\temp\ -force
}
}
#### BAT GENERATOR #####
Write-Output "3"
# & .\bat_generator.ps1
$zapis = "$path\test.bat"
"pushd %~dp0" > $zapis
$nazwa = Get-ChildItem "\\$server\c$\temp\" | select name
foreach ($i in $nazwa) {
$text = $i.name + " /norestart /quiet"
$text >> $zapis
}
"ppd0" >> $zapis # dodaj ppd0
move-item -path .\test.bat -destination \\$server\c$\temp\ -Force # skopiuj .bat na server
At first I create file with name of server, for example server.txt in this server we have list of KBs. Scripts searching in folder paczki that KB exist if yes copying this in server and create .bat
I would like do add automatically searching all .txt files eg server.txt, & server1.txt and use it in loop, I thought about something like that:
$pliki_txt= Get-ChildItem $path -Filter "*.txt" | % {$_.BaseName}
and put it in loop but its not really working, I try to add loop in this place:
for ($i in pliki_txt)
$path = ".\" # path do txt
$server="server" # server.txt
$pliki_txt= Get-ChildItem $path -Filter "*.txt" | % {$_.BaseName}
(....)
What am I doing wrong? Is there any easier way? Script is only working when I put manually set $server like $server="serwer"
You can try this:
$path = ".\"
Get-ChildItem $path -Filter *.txt | %{
$content = Get-content $_.FullName
Foreach($server in $content){
write-host $server
}
}
If I got that right, the issue here is that you're not putting the lines in the right order.
From your original code I would change the following
$path = ".\" # path do txt
$server = "server" # server.txt
$paczki = ".\paczki\"
# $missingi = "$path\$server.txt"
$missingi = Get-ChildItem -Path $path -Filter server*.txt | Select -ExpandProperty Name
foreach ($m in $missingi) {
$plik = get-content $m
( ... )
}
That way you'll check every server*.txt file in that path and process it accordingly.
Or you could even turn it into a parameterized script like this
Param(
[Parameter(Mandatory = $true)]
[String]$path,
[Parameter(Mandatory = $true)]
[String]$pattern,
[Parameter(Mandatory = $true)]
[String]$packzi
)
$missingi = Get-ChildItem -Path $path -Filter *.txt | Select -ExpandProperty | Select-String "$pattern"
foreach ($m in $missingi) {
$plik = get-content $m
foreach ($j in $plik) {
Write-Output "1"
$wynik = Get-ChildItem "$paczki" | ? {$_.name -match "$j"}
if ($wynik -eq $null) {
# Write-Host $i
}
else {
Write-Output "2"
Write-Host $wynik "znaleziono"
Copy-Item $paczki\$wynik -Destination \\$server\c$\temp\ -force
}
}
#### BAT GENERATOR #####
Write-Output "3"
# & .\bat_generator.ps1
$zapis = "$path\test.bat"
"pushd %~dp0" > $zapis
$nazwa = Get-ChildItem "\\$server\c$\temp\" | select name
foreach ($i in $nazwa) {
$text = $i.name + " /norestart /quiet"
$text >> $zapis
}
"ppd0" >> $zapis # dodaj ppd0
move-item -path .\test.bat -destination \\$server\c$\temp\ -Force # skopiuj .bat na server
}
Then you would run it like this:
.\YourScript.ps1 -path ".\" -pattern "server" -packzi ".\packzi\"
That will give you more flexibility if you want to change the source path, the name pattern or the search patch.
I hope this helps.