I'm trying to get what permissions files and folders have and export to a csv file. I can get the info to display on screen, but when I try to export it the resulting csv file is empty.
The code:
function Test-IsWritable(){
<#
.Synopsis
Command tests if a file is present and writable.
.Description
Command to test if a file is writeable. Returns true if file can be opened for write access.
.Example
Test-IsWritable -path $foo
Test if file $foo is accesible for write access.
.Example
$bar | Test-IsWriteable
Test if each file object in $bar is accesible for write access.
.Parameter Path
Psobject containing the path or object of the file to test for write access.
#>
[CmdletBinding()]
param([Parameter(Mandatory=$true,ValueFromPipeline=$true)][psobject]$path)
process{
Write-Host "Test if file $path is writeable"
if (Test-Path -Path $path -PathType Any){
$target = Get-Item $path -Force
try{
$writestream = $target.Openwrite()
$writestream.Close() | Out-Null
Remove-Variable -Name writestream
Write-Host "File is writable" -ForegroundColor DarkGreen
Write-Output $true
}
catch{
Write-Host "File is not writable" -ForegroundColor DarkRed
Write-Output $false
}
Remove-Variable -Name target
}
else{
Write-Host "File $path does not exist or is a directory" -ForegroundColor Red
Write-Output $false
}
}
}
write-host "WARNING: If checking deep folders (where the full path is longer than 248 characters) please " -foregroundcolor Yellow -NoNewline
Write-Host "MAP THE DRIVE " -ForegroundColor Red -NoNewline
Write-Host "in order to keep the names as short as possible" -ForegroundColor Yellow
$basefolder = Read-Host -Prompt 'What is the folder or files you want to get permissions of?'
write-host "WARNING: if permissions.csv already exists, it will be overwritten!" -foregroundcolor Yellow
Write-Host 'Export results to CSV? (y/n): ' -ForegroundColor Magenta -NoNewline
$export = Read-Host
if ($export -like "y")
{
Write-Host "Name the file (ex: permissions.csv): " -ForegroundColor Magenta -NoNewline
$FileName = Read-Host
$Outfile = “$PSScriptRoot\$FileName”
write-host "Will write results to $PSScriptRoot\$FileName" -ForegroundColor Green
}
else
{
write-host "User did not type 'y', continuing" -ForegroundColor DarkYellow
}
$files = get-childitem $basefolder -recurse -File
Write-Host $files
Write-Host "=========================" -ForegroundColor Black
#$subfiles = Get-ChildItem $folders -Recurse -File
#Write-Host $folders
#Write-Host "=========================" -ForegroundColor Black
#Write-Host $subfiles
$results = foreach($folder in $files) {
New-Object psobject -Property #{
File = $folder;
Access = "$basefolder\$folder" | Test-IsWritable
}
Write-Host $folder
}
#$subresults = foreach($subfile in $subfiles) {
# New-Object psobject -Property #{
# File = $subfiles;
# Access = $subfile | Test-IsWritable;
# }
#}
Write-Host $results
Write-Host "Finished combo loop, exporting..." -ForegroundColor Green
$results | Export-Csv $Outfile -NoTypeInformation -Delimiter ";"
Write-Host "Converting delimited CSV to Column Excel Spreadsheet"
$outputXLSX = $PSScriptRoot + "\$Filename.xlsx"
$excel = New-Object -ComObject excel.application
$workbook = $excel.Workbooks.Add(1)
$worksheet = $workbook.worksheets.Item(1)
$TxtConnector = ("TEXT;" + $Outfile)
$Connector = $worksheet.QueryTables.add($TxtConnector,$worksheet.Range("A1"))
$query = $worksheet.QueryTables.item($Connector.name)
$query.TextFileOtherDelimiter = ';'
$query.TextFileParseType = 1
$query.TextFileColumnDataTypes = ,2 * $worksheet.Cells.Columns.Count
$query.AdjustColumnWidth = 1
$query.Refresh()
$query.Delete()
$Workbook.SaveAs($outputXLSX,51)
$excel.Quit()
Remove-Item $Outfile
Write-Host "See $PSScriptRoot\$Filename.xlsx for results" -ForegroundColor Green
UPDATE: Mostly working, strange output though:
Z:\testfolder\file1.txt
Z:\testfolder\file1.txt
Z:\testfolder\file1.txt
Z:\testfolder\file1.txt
Z:\testfolder\file1.txt
Z:\testfolder\file1.txt
Z:\testfolder\file1.txt
Z:\testfolder\file2.txt
Z:\testfolder\file2.txt
Z:\testfolder\file2.txt
Z:\testfolder\file2.txt
Z:\testfolder\file2.txt
Z:\testfolder\file2.txt
Z:\testfolder\file2.txt
Z:\testfolder\file3.rar
Z:\testfolder\file3.rar
Z:\testfolder\file3.rar
Z:\testfolder\file3.rar
Z:\testfolder\file3.rar
Z:\testfolder\file3.rar
Z:\testfolder\file3.rar
The specified path, file name, or both are too
long. The fully qualified file name must be less than 260 characters,
and the directory name must be less than 248 characters.
In the next column:
FileAccess
FullControl
FullControl
FullControl
Modify, Synchronize
ReadAndExecute, Synchronize
Modify, Synchronize
Modify, Synchronize
FullControl
FullControl
FullControl
Modify, Synchronize
...
The specified path, file name, or both are too long. The fully
qualified file name must be less than 260 characters, and the
directory name must be less than 248 characters.
I'm not sure why it's showing multiple rows for the same file, I'd like to have 1 row per file with the true File Access.
Remove Write-Host before using Export-Csv. Write-Hostconsumes the data from the pipeline and only outputs it on screen.
#(...)
$i = 0
$results = foreach($acl in $acls) {
$folder = (Convert-Path $acl.pspath)
Write-Progress -Activity "Getting Security" -Status "checking $folder" -PercentComplete ($i / $folders.Count * 100)
foreach($access in $acl.GetAccessRules($true, $true, [System.Security.Principal.SecurityIdentifier])) {
New-Object psobject -Property #{
Folder = $folder;
User = $acl.Owner;
Group=$acl.Group;
Mode = $access.AccessControlType;
FileAcess = $access.FileSystemRights;
}
}
$i++
}
Write-Host "Reached End, exporting..." -ForegroundColor Green
$results | Export-Csv $Outfile -NoTypeInformation -Delimiter ";"
Related
I am trying to create a program that will copy files from our backup to archive directory using Powershell. I have two criteria in order for this program to run smoothly. One is that we have files from both current year and past years so only the files from this year must be copied over. Another is that we have to check to make sure that we are not copying over files of the same file name in case if the data in the file is accidentally modified. Whenever I have this program not in a function, it works. But in a function, it gives me errors that it "cannot find the path" of the folder that I am copying from and the folder that I'm pasting the files to. I am going to use this for more than sixty locations, so it would be better that I don't have to rewrite the code in the function sixty times. I thought about using Robocopy, but I am still getting the same issues regardless with files not being copied over.
Function Copy-Data {
param (
[system.object]$copyFolder,
[system.object]$pasteFolder,
[int]$currentYear,
[int]$lastYear,
[int]$nextYear)
$copyItem = Get-ChildItem -Path $copyFolder
$pasteItem = Get-ChildItem -Path $pasteFolder
$copyCount = $copyItem.count
for ($i = 0; $i -lt $copyCount; $i++)
{
$copyName = $copyItem.Name
$testPath = Test-Path "$pasteFolder$copyName"
if ($copyItem[$i].LastWriteTime -gt $firstDate -and $copyItem[$i].LastWriteTime -lt $lastDate)
{
if ($testPath -eq $false)
{
Copy-Item -Path $copyFolder$copyName -Destination $pasteFolder
#Robocopy "$copyFolder$copyItem[$i]" "$pasteFolder"
Write-Host $pasteFolder$copyName
}
}
}
}
$currentYear = Get-Date -Format "yyyy"
$lastYear = [int]$currentYear - 1
$nextYear = [int]$currentYear + 1
$firstDate = "12/31/$lastYear"
$lastDate = "01/01/$nextYear"
$copyFolder = "\\fileshare\test\copy\"
$pasteFolder = "\\fileshare\test\$currentYear\paste\"
Copy-Data ($copyFolder, $pasteFolder, $currentYear, $lastYear, $nextYear)
I feel like you are making this more complicated than it needs to be.
Core code can be something like:
Get-ChildItem -Path $copyFolder |
ForEach-Object{
If( !(Test-Path $pasteFolder -Name $_.Name ) )
{
Copy-Item $_.FullName -Destination $pasteFolder
}
}
You can use just the destination path you don't have to give the full path of the destination file.
As a function it may look something like:
Function CopyFoldercontents
{
Param(
[Parameter( Mandatory = $true, Position = 0)]
[String]$copyFolder,
[Parameter( Mandatory = $true, Position = 1)]
[String]$pasteFolder
) # End Parameter Block.
Get-ChildItem -Path $copyFolder |
ForEach-Object{
If( !(Test-Path $pasteFolder -Name $_.Name ) )
{
Copy-Item $_.FullName -Destination $pasteFolder
}
}
} # End Function CopyFolderContents
This could be more robust though, depends on what direction you want to take it.
Continuing from my comment.
You could just do this...
(validate what you are after on both sides, the construct the final function)
Function Start-FolderMirror
{
[CmdletBinding()]
[Alias('mir')]
Param
(
[string]$SourcePath = (Read-Host -Prompt 'Enter a source path'),
[string]$DestinationPath = (Read-Host -Prompt 'Enter a destination path')
)
$SourceFiles = (Get-ChildItem -Path $SourcePath -File).FullName
$DestinationFiles = (Get-ChildItem -Path $DestinationPath -File).FullName
Compare-Object -ReferenceObject $SourceFiles -DifferenceObject $DestinationFiles -IncludeEqual |
Select-Object -First 5
}
Start-FolderMirror -SourcePath 'd:\temp' -DestinationPath 'D:\temp\TestFiles'
# Results
<#
InputObject SideIndicator
----------- -------------
D:\temp\TestFiles\abc - Copy - Copy.bat =>
D:\temp\TestFiles\abc - Copy.bat =>
D:\temp\TestFiles\abc.bat =>
D:\temp\(MSINFO32) command-line tool switches.pdf <=
D:\temp\23694d1213305764-revision-number-in-excel-book1.xls <=
#>
Function Start-FolderMirror
{
[CmdletBinding(SupportsShouldProcess)]
[Alias('mir')]
Param
(
[string]$SourcePath = (Read-Host -Prompt 'Enter a source path'),
[string]$DestinationPath = (Read-Host -Prompt 'Enter a destination path')
)
$SourceFiles = (Get-ChildItem -Path $SourcePath -File).FullName
$DestinationFiles = (Get-ChildItem -Path $DestinationPath -File).FullName
Compare-Object -ReferenceObject $SourceFiles -DifferenceObject $DestinationFiles -IncludeEqual |
Select-Object -First 5 |
Where-Object -Property SideIndicator -Match '<='
}
Start-FolderMirror -SourcePath 'd:\temp' -DestinationPath 'D:\temp\TestFiles' -WhatIf
# Results
<#
InputObject SideIndicator
----------- -------------
D:\temp\(MSINFO32) command-line tool switches.pdf <=
D:\temp\23694d1213305764-revision-number-in-excel-book1.xls <=
#>
Function Start-FolderMirror
{
[CmdletBinding(SupportsShouldProcess)]
[Alias('mir')]
Param
(
[string]$SourcePath = (Read-Host -Prompt 'Enter a source path'),
[string]$DestinationPath = (Read-Host -Prompt 'Enter a destination path')
)
$SourceFiles = (Get-ChildItem -Path $SourcePath -File).FullName
$DestinationFiles = (Get-ChildItem -Path $DestinationPath -File).FullName
Compare-Object -ReferenceObject $SourceFiles -DifferenceObject $DestinationFiles -IncludeEqual |
Select-Object -First 5 |
Where-Object -Property SideIndicator -Match '<=' |
ForEach {Copy-Item -Path $PSItem.InputObject -Destination $DestinationPath}
}
Start-FolderMirror -SourcePath 'd:\temp' -DestinationPath 'D:\temp\TestFiles' -WhatIf
# Results
<#
What if: Performing the operation "Copy File" on target "Item: D:\temp\(MSINFO32) command-line tool switches.pdf Destination: D:\temp\TestFiles\(MSINFO32) command-line tool switches.pdf".
What if: Performing the operation "Copy File" on target "Item: D:\temp\23694d1213305764-revision-number-in-excel-book1.xls Destination: D:\temp\TestFiles\23694d1213305764-revision-number-in-excel-book1.xls".
#>
I have a rather complex script, which follows the following steps;
-->Login (Ask user to enter admin details)
--->Start (Queries Ad for user creditals)
--->Progress (Creates a progress bar)
--->Search (Carries out the search for the data)
--->Question1 -(Yes - Select-Folder No - Create)
--->Select-Folder (Asks the user to create a file path for the document to be stored)
--->Go (Creates a csv from the results of the search)
--->Question2 (CSV - Result XLSX - Excel) (Asks the user if they wish to create a Xlsx file from the Csv)
--->Create (Checks to see if file path exists C:\temp\Server_shares if not creates it)
--->Done (creates csv at default location C:\temp\Server_shares)
--->Question2 (Asks the user if they wish to create a Xlsx file from the Csv)
--->Question2 -(CSV - Result XLSX - Excel) (Asks the user if they wish to create a Xlsx file from the Csv)
--->Result (User has chosen not to create a Xlsx notifys the user of the file path)
--->End (Closes script)
--->Excel (creates Xlsx from csv and stores it in either default or user defined location)
--->Delete (Deletes all remaingin Csv's from file path)
--->End (Closes script)
it seems that I keep get unhandelled exception errors everytime that I run the code.
I have found out that it runs then loads the functions, I need to run them all in memory so that when called each one will run without error.
I have tried creating varibles for each function, but this exactly the same as what I have already.
[void][System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[void][System.Reflection.Assembly]::LoadWithPartialName ("Microsoft.VisualBasic")
$Script:ErrorActionPreference = "Stop"
$Script:Ma3 = "C:\Temp\Server_Shares\"
Function Get-Event{
Function Get-Login {
Clear-Host
#Write-Host "Please provide admin credentials (for example DOMAIN\admin.user and your password)"
$Global:Credential = Get-Credential
}
Function Get-Start{
#Get user credentials
$Cred = Get-Credential -Message "Enter Your Credentials (Domain\Username)"
if ($Cred -eq $Null)
{
Write-Host "Please enter your username in the form of Domain\UserName and try again" -BackgroundColor Black -ForegroundColor Yellow
Rerun
Break
}
#Parse provided user credentials
$DomainNetBIOS = $Cred.username.Split("{\}")[0]
$UserName = $Cred.username.Split("{\}")[1]
$Password = $Cred.GetNetworkCredential().password
Write-Host "`n"
Write-Host "Checking Credentials for $DomainNetBIOS\$UserName" -BackgroundColor Black -ForegroundColor White
Write-Host "***************************************"
If ($DomainNetBIOS -eq $Null -or $UserName -eq $Null)
{
Write-Host "Missing domain please type in the following format: Domain\Username" -BackgroundColor Black -ForegroundColor Yellow
Rerun
Break
}
# Checks if the domain in question is reachable, and get the domain FQDN.
Try
{
$DomainFQDN = (Get-ADDomain $DomainNetBIOS).DNSRoot
}
Catch
{
Write-Host "Error: Domain was not found: " $_.Exception.Message -BackgroundColor Black -ForegroundColor Red
Write-Host "Please make sure the domain NetBios name is correct, and is reachable from this computer" -BackgroundColor Black -ForegroundColor Red
Rerun
Break
}
#Checks user credentials against the domain
$DomainObj = "LDAP://" + $DomainFQDN
$DomainBind = New-Object System.DirectoryServices.DirectoryEntry($DomainObj,$UserName,$Password)
$DomainName = $DomainBind.distinguishedName
If ($DomainName -eq $Null)
{
Write-Host "Domain $DomainFQDN was found: True" -BackgroundColor Black -ForegroundColor Green
$UserExist = Get-ADUser -Server $DomainFQDN -Properties LockedOut -Filter {sAMAccountName -eq $UserName}
If ($UserExist -eq $Null)
{
Write-Host "Error: Username $Username does not exist in $DomainFQDN Domain." -BackgroundColor Black -ForegroundColor Red
Rerun
Break
}
Else
{
Write-Host "User exists in the domain: True" -BackgroundColor Black -ForegroundColor Green
If ($UserExist.Enabled -eq "True")
{
Write-Host "User Enabled: "$UserExist.Enabled -BackgroundColor Black -ForegroundColor Green
}
Else
{
Write-Host "User Enabled: "$UserExist.Enabled -BackgroundColor Black -ForegroundColor RED
Write-Host "Enable the user account in Active Directory, Then check again" -BackgroundColor Black -ForegroundColor RED
Rerun
Break
}
If ($UserExist.LockedOut -eq "True")
{
Write-Host "User Locked: " $UserExist.LockedOut -BackgroundColor Black -ForegroundColor Red
Write-Host "Unlock the User Account in Active Directory, Then check again..." -BackgroundColor Black -ForegroundColor RED
Rerun
Break
}
Else
{
Write-Host "User Locked: " $UserExist.LockedOut -BackgroundColor Black -ForegroundColor Green
}
}
Write-Host "Authentication failed for $DomainNetBIOS\$UserName with the provided password." -BackgroundColor Black -ForegroundColor Red
Write-Host "Please confirm the password, and try again..." -BackgroundColor Black -ForegroundColor Red
Rerun
Break
}
Else
{
Write-Host "SUCCESS: The account $Username successfully authenticated against the domain: $DomainFQDN" -BackgroundColor Black -ForegroundColor Green
}
Search
}
Function Rerun {
$Title = "Enter another set of Credentials?"
$Message = "Do you want to try another set of credentials?"
$Yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes", "Try Again?"
$No = New-Object System.Management.Automation.Host.ChoiceDescription "&No", "End Script."
$Options = [System.Management.Automation.Host.ChoiceDescription[]]($Yes, $No)
$Result = $host.ui.PromptForChoice($Title, $Message, $Options, 0)
Switch ($Result)
{
0 {Get-Start}
1 {"End Script."}
}
}
Function Get-Progress{
Try{
{If (Test-Path $PC -ErrorAction Stop) {
Add-Type -assembly System.Windows.Forms
## -- Create The Progress-Bar
$ObjForm = New-Object System.Windows.Forms.Form
$ObjForm.Text = "Progress-Bar of searched folders"
$ObjForm.Height = 100
$ObjForm.Width = 500
$ObjForm.BackColor = "White"
$ObjForm.FormBorderStyle = [System.Windows.Forms.FormBorderStyle]::FixedSingle
$ObjForm.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen
## -- Create The Label
$ObjLabel = New-Object System.Windows.Forms.Label
$ObjLabel.Text = "Starting. Please wait ... "
$ObjLabel.Left = 5
$ObjLabel.Top = 10
$ObjLabel.Width = 500 - 20
$ObjLabel.Height = 15
$ObjLabel.Font = "Tahoma"
## -- Add the label to the Form
$ObjForm.Controls.Add($ObjLabel)
$PB = New-Object System.Windows.Forms.ProgressBar
$PB.Name = "PowerShellProgressBar"
$PB.Value = 0
$PB.Style="Continuous"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Width = 500 - 40
$System_Drawing_Size.Height = 20
$PB.Size = $System_Drawing_Size
$PB.Left = 5
$PB.Top = 40
$ObjForm.Controls.Add($PB)
## -- Show the Progress-Bar and Start The PowerShell Script
$ObjForm.Show() | Out-Null
$ObjForm.Focus() | Out-NUll
$ObjLabel.Text = "Starting. Please wait ... "
$ObjForm.Refresh()
Start-Sleep -Seconds 1
Out-Null
## -- Execute The PowerShell Code and Update the Status of the Progress-Bar
$result = (get-acl $pc).Access
$Counter = 0
ForEach ($Item In $Result) {
## -- Calculate The Percentage Completed
$Counter++
[Int]$Percentage = ($Counter/$Result.Count)*100
$PB.Value = $Percentage
$ObjLabel.Text = "Scanning $Folders For $criteria in $PC"
#$ObjLabel.Text = "Found $counter Pst's in $Search"
$ObjForm.Refresh()
Start-Sleep -Milliseconds 150
# -- $Item.Name
#"`t" + $Item.Path
$ObjForm.Close()
#Write-Host "`n"
Else {
#Write-Host
#Write-Host "`t Cannot Execute The Script." -ForegroundColor "Yellow"
#Write-Host "`t $Search Does Not Exist in the System." -ForegroundColor "Yellow"
#Write-Host
}
}
}
}
}
Catch{
Write-Host "Please enter a vaild path" -ForegroundColor Cyan
Search
}
}
Function Script:Get-Question {
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form1 = New-Object System.Windows.Forms.Form
$Form1.ClientSize = New-Object System.Drawing.Size(200, 100)
$form1.topmost = $true
$Text = New-Object System.Windows.Forms.Label
$Text.Location = New-Object System.Drawing.Point(15, 15)
$Text.Size = New-Object System.Drawing.Size(200, 40)
$Text.Text = "Would you like to save the file to a custom location?"
$Form1.Controls.Add($Text)
#$ErrorActionPreference = "SilentlyContinue"
Function Button1
{
$Button1 = New-Object System.Windows.Forms.Button
$Button1.Location = New-Object System.Drawing.Point(20, 55)
$Button1.Size = New-Object System.Drawing.Size(55, 20)
$Button1.Text = "Yes"
$Button1.add_Click({Get-Go -ErrorAction SilentlyContinue
$Form1.Close()})
$Form1.Controls.Add($Button1)
}
Function Button2
{
$Button2 = New-Object System.Windows.Forms.Button
$Button2.Location = New-Object System.Drawing.Point(80, 55)
$Button2.Size = New-Object System.Drawing.Size(55, 20)
$Button2.Text = "No"
$Button2.add_Click({Get-Create -ErrorAction SilentlyContinue
$Form1.Close()})
$Form1.Controls.Add($Button2)
}
Button1
Button2
[void]$form1.showdialog()
}
Function Select-FolderDialog{
param([string]$Description="Select Folder",[string] $RootFolder="Desktop")
[System.Reflection.Assembly]::LoadWithPartialName ("System.windows.forms") | Out-Null
Write-host "Please minimize the console to select a folder in which to save the results"
$objForm = New-Object System.Windows.Forms.FolderBrowserDialog
$objForm.Rootfolder = $RootFolder
$objForm.Description = $Description
$objForm.ShowNewFolderButton = $false
$Show = $objForm.ShowDialog()
If ($Show -eq "OK")
{
Return $objForm.SelectedPath
}
Else
{
Write-Error "Operation cancelled by user."
Exit
}
}
Function Get-Search{
Write-host "Please Minimize the console and enter the full folder path that you require permissions for" -ForegroundColor Green
$Script:PC = [Microsoft.VisualBasic.Interaction]::InputBox("Please enter the full path of the folder you wish to search", "Folder choice")
If ($PC -eq "")
{
Exit
}
Get-Progress
$Res = (get-acl $pc).Access
$Script:Gold = $Res| Select-object #{label = "User Groups";Expression = {$_.IdentityReference}},
#{label = "Rights";Expression = {$_.FileSystemRights}},
#{label = "Access";Expression = {$_.AccessControlType}}
Get-Question
}
Function Script:Get-Go{
$Form1.Close()
$FPath = Select-FolderDialog
$Folder = $FPath + "\" + [Microsoft.VisualBasic.Interaction]::InputBox ("Please select a folder to save the data to", "Path Choice") + "\"
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
"Please minimize the console to select a folder in which to save the results"
$Name = [Microsoft.VisualBasic.Interaction]::InputBox("Please choose a filename", "File Name Choice")
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null
$cfgOutpath = $Folder + "$Name"
if( -Not (Test-Path -Path $Folder ) )
{
New-Item -ItemType directory -Path $Folder |out-null
}
Else{
[System.Windows.MessageBox]::Show('The directory already exists','Error','Ok','Error')
}
$Gold | Export-Csv "$cfgOutpath.csv" -NoClobber -NoTypeInformation
Write-Host "File has been saved to $cfgOutpath.csv" -ForegroundColor Yellow
Get-Q2
}
##############################################
## Testing Phases ##
## Get-Start ##
## ##
##############################################
Search
Function Script:Get-Create {
$Form1.Close()
if( -Not (Test-Path -Path $Ma3 ) )
{
New-Item -ItemType directory -Path $Ma3 |out-null
}
Done
}
Function Script:Get-Done{
$PC2 = ($PC -split '\\')[-1]
$CSV = "C:\Temp\Server_Shares\User access for $PC2"
$cfgOutpath = $CSV
$Gold | Export-Csv "$cfgOutpath.csv" -NoClobber -NoTypeInformation
Get-Q2
}
Function Script:Get-Q2 {
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void][System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
$Form2 = New-Object System.Windows.Forms.Form
$Form2.ClientSize = New-Object System.Drawing.Size(200, 100)
$form2.topmost = $true
$Text = New-Object System.Windows.Forms.Label
$Text.Location = New-Object System.Drawing.Point(15, 15)
$Text.Size = New-Object System.Drawing.Size(200, 40)
$Text.Text = "Would you like to create an Xlsx document or leave it as csv?"
$Form2.Controls.Add($Text)
$ErrorActionPreference = "SilentlyContinue"
Function Button1
{
$Button1 = New-Object System.Windows.Forms.Button
$Button1.Location = New-Object System.Drawing.Point(20, 55)
$Button1.Size = New-Object System.Drawing.Size(55, 20)
$Button1.Text = "CSV"
$Button1.add_Click({Get-Result
$Form2.Close()})
$Form2.Controls.Add($Button1)}
Function Button2
{
$Button2 = New-Object System.Windows.Forms.Button
$Button2.Location = New-Object System.Drawing.Point(80, 55)
$Button2.Size = New-Object System.Drawing.Size(55, 20)
$Button2.Text = "XLSX"
$Button2.add_Click({Get-Excel
$Form2.Close()})
$Form2.Controls.Add($Button2)
}
Button1
Button2
[void]$form2.showdialog()
}
Function Script:Get-Ans{
$Form2.Close()
Try{
Get-Excel
}
Catch{
Write-Host "Unable to create XSLX please check full path." -ForegroundColor Red
}
}
Function Script:Get-Result{
$Form2.Close()
Write-Host "File has been saved to $CSV.csv" -ForegroundColor Yellow
}
Function Script:Get-Excel{
$RD = $Ma3 + "*.csv"
$CsvDir = $RD
$csvs = dir -path $CsvDir # Collects all the .csv's from the driectory
$outputxls = "$Ma4.Xlsx"
$Excel = New-Object -ComObject excel.application
$Excel.displayAlerts = $false
$workbook = $excel.Workbooks.add()
# Loops through each CVS, pulling all the data from each one
foreach($iCsv in $csvs){
$iCsv
$WN = ($iCsv -Split "\\")[5]
$wn = ($WN -Split " ")[3]
$WN = $WN -replace ".{5}$"
$Excel = New-Object -ComObject excel.application
$Excel.displayAlerts = $false
$Worksheet = $workbook.worksheets.add()
$Worksheet.name = $WN
$TxtConnector = ("TEXT;" + $iCsv)
$Connector = $worksheet.Querytables.add($txtconnector,$worksheet.Range("A1"))
$query = $Worksheet.QueryTables.item($Connector.name)
$query.TextfileOtherDelimiter = $Excel.Application.International(5)
$Query.TextfileParseType =1
$Query.TextFileColumnDataTypes = ,2 * $worksheet.cells.column.count
$query.AdjustColumnWidth =1
$Query.Refresh()
$Query.Delete()
$Worksheet.Cells.EntireColumn.AutoFit()
$Worksheet.Rows.Item(1).Font.Bold = $true
$Worksheet.Rows.Item(1).HorizontalAlignment = -4108
$Worksheet.Rows.Item(1).Font.Underline = $true
$Workbook.save()
}
$Empty = $workbook.worksheets.item("Sheet1")
$Empty.Delete()
$Workbook.SaveAs($outputxls,51)
$Workbook.close()
$Excel.quit()
Write-Host "File has been saved to $outputxls" -ForegroundColor Yellow
Delete
}
Function Script:Delete{
get-childitem $MA3 -recurse -force -include *.txt | remove-item -force #Removes all txt files from final directory
get-childitem $MA3 -recurse -force -include *.csv | remove-item -force #Removes all CSV files from final directory
}
Write-Host "Finished"
}
Get-Event
#Excel-Write'
I know it's a lot of code, but in-order for anyone to replicate the probelm, you will need it all.
I want it to run, first time, everytime, at the moment it take 3-4 tries before its loaded each function into memory.
Put all of your functions into a PowerShell module file.
C:\Module.psm1
And then import that module before anything else in the script:
Import-Module C:\Module.psm1
For larger scripts this makes things more manageable as you can keep your long list of functions separate from the script that calls them.
I am using PowerShell to compare the file count and size (per file extension) in 2 separate directories.
$User = $env:username
$pwd = pwd
clear
write-host "`n"
write-host "`n"
write-host "`n"
write "The current user is: $User"
write-host "`n"
write "The current path is: $pwd"
write-host "`n"
write-host "`n"
write-host "`n"
write "We need to know the following information:"
write "`n"
write "`n"
$UserDesktopPath = Read-Host "New PC User Desktop Path" # This should be the new PC Desktop Path
$UserDocumentPath = Read-Host "New PC User Document Path" # This should be the new PC Document Path
$USBDesktopPathServer = Read-Host "USB User Desktop Path" # This should be the USB User Desktop Path
$USBDocumentPathServer = Read-Host "USB User Document Path" # This should be the USB User Document Path
clear
write-host "`n"
write-host "`n"
write-host "`n"
write "This is the results for your Desktop Folder Paths:"
write-host "`n"
$folder_new = Get-ChildItem -Recurse -path "$USBDesktopPathServer" # Recurses the New PC Desktop
$folder_old = Get-ChildItem -Recurse -path "$UserDesktopPath" # Recurses the USB Backup Desktop
Compare-Object -ReferenceObject "$folder_new" -DifferenceObject "$folder_old" # Compares the two folders for the path to identify discrepancies
write-host "`n"
write "This is the results for your Documents Folder Paths:"
write-host "`n"
write-host "`n"
write-host "`n"
$folder_new1 = Get-ChildItem -Recurse -path "$UserDocumentPath" # Recurses the New PC Documents
$folder_old1 = Get-ChildItem -Recurse -path "$USBDocumentPathServer" # Recurses the USB Backup Documents
Compare-Object -ReferenceObject "$folder_new1" -DifferenceObject "$folder_old1" # Compares the two folders for the path to identify discrepancies
write-host "`n"
write-host "`n"
write-host "`n"
write "Now we shall compare file sizes of your Documents:"
write-host "`n"
write-host "`n"
write-host "`n"
write-host "`n"
function doc{
$DirectoryDocuments = "$USBDocumentPathServer", "$UserDocumentPath"
foreach ($Directory in $DirectoryDocuments) {
Get-ChildItem -Path $Directory -Recurse |
Where-Object {-not $_.PSIsContainer} |
Tee-Object -Variable Files |
Group-Object -Property Extension |
Select-Object -Property #{
n = "Directory"
e = {$Directory}
},
#{
n = "Extension"
e = { $_.Name -replace '^\.' }
},
#{
n = "Size (MB)"
e={ [math]::Round( ( ( $_.Group | Measure-Object Length -Sum ).Sum / 1MB ), 2 ) }
},
Count
$Files |
Measure-Object -Sum -Property Length |
Select-Object -Property #{
n = 'Extension'
e = { 'Total' }
},
#{
n = 'Size (MB)'
e = { [math]::Round( ( $_.Sum / 1MB ), 2 ) }
},
Count
}
}
When using the ISE and calling dtop I get the correct return:
PS C:\Users\Michael Nancarrow> dtop
Directory Extension Size (MB) Count
--------- --------- --------- -----
D:\Deployment Kit\Test\Desktop2 txt 0 1
Total 0 1
D:\Deployment Kit\Test\Desktop1 txt 0 11
Total 0 11
Yet when run in the script, it does not return any value. I have attempted to call a function write $tst which runs dtop and that does the same (writes null).
Furthermore, I have removed the { so it does not run as a function, and it operates without an issue. My concern is perhaps the -Path file cannot be parsed at the same time as the input - meaning: when I call dtop from ISE it already has the $Directory variable stored in memory.
Are there any obvious errors here? I am rather new to PowerShell and am unsure where the mistake lies.
I have a long winded script that gets a user from an CSV file, matches user against a CSV filename from a specific directory.
The user is matched against this CSV file in this format <data><samaccountname><text>.csv
The aim here is to get an AD User from a list, then scan a folder with CSV Files in it and match against the user. From there restore the user AD attributes.
The issue here is that the output is always of the last user twice, I have REM out the export at the end so I can see what is on screen first.
Clear-Host
#Get username from users list and match against CSV file name.
$FDate = (get-date).ToString("yyyMMdd")
$Project = "<FolderPath>" #Project name used to setup folders and for reports etc
$ProjectRoot = "<path>\" # Backup folder
$RestorePath = $ProjectRoot + $Project #combined path for restoring
$UsersListFile = $ProjectRoot + '\Userlist.csv' #Userlist
$Results = #{} # Storage for all csv files
$PSObject = New-Object psobject
$Report = #() #For Export-CSV
$Results = gci $RestorePath -Filter '*.csv'
$i = 0
foreach ($File in $Results) {
$i += 1
Write-Host 'Number of passes - '$i
Write-Host 'Current file processing - '$file.Name -for Green
foreach ($User in (import-csv $UsersListFile)) {
$SAM = $User.SamAccountName
Write-Host 'Current User processing - '$SAM -ForegroundColor Magenta
if ($file.Name -match $SAM) {
Write-host "Filename and user $SAM match " -for Yellow
$Row= New-Object psobject
$ROW | Add-Member -type NoteProperty -name Name -value $SAM -force
$Report += $Row
foreach ($Attrib in (import-csv $restorepath\$file)) {
#Write-host 'Attributes in file - ' $attrib.samaccountname $Attrib.mail -for Yellow
#Use this to restore AD User data
}
} else {
Write-Host "No match" -ForegroundColor Red
}
}
}
#$Report | Export-Csv $RestorePath'\Test.csv' -NoTypeInformation -Force
$Report | Sort-Object Name
Updated script to move New-Object psobject to above $Row, so this creates a new object each time, rather then overwriting previous entry.
I've written the following PS script to delete log files from specific server paths. I'm a novice to PS but I'm getting some errors with a few of the functions that I have written in this script:
#* FileName: FileCleaner.ps1
#Clear the screen
Clear
#Read XML Config File to get settings
[xml]$configfile = Get-Content "C:\Users\pmcma\Documents\Projects\Replace FileCleaner with PowerShell Script\FileCleaner.config.xml"
#Declare and set variables from Config values
$hostServer = $configfile.Settings.HostServer
$dirs = #($configfile.Settings.DirectoryName.Split(",").Trim())
$scanSubDirectories = $configfile.Settings.ScanSubDirectories
$deleteAllFiles = $configfile.Settings.deleteAllFiles
$fileTypesToDelete = #($configfile.Settings.FileTypesToDelete.Split(";").Trim())
$liveSiteLogs = $configfile.Settings.LiveSiteLogs
$fileExclusions = #($configfile.Settings.FileExclusions.Split(";").Trim())
$retentionPeriod = $configfile.Settings.RetentionPeriod
$AICLogs = $configfile.Settings.AICLogs
$AICLogsRententionPeriod = $configfile.Settings.AICLogsRententionPeriod
$fileCleanerLogs = $configfile.Settings.FileCleanerLogs
$fileCleanerLogsRententionPeriod = $configfile.Settings.FileCleanerLogsRententionPeriod
#Setup FileCleaner output success logfiles
$successLogfile = $configfile.Settings.SuccessOutputLogfile
$dirName = [io.path]::GetDirectoryName($successLogfile)
$filename = [io.path]::GetFileNameWithoutExtension($successLogfile)
$ext = [io.path]::GetExtension($successLogfile)
$successLogfile = "$dirName\$filename$(get-date -Format yyyy-MM-dd)$ext"
#Setup FileCleaner output error logfiles
$errorLogfile = $configfile.Settings.ErrorOutputLogfile
$dirName = [io.path]::GetDirectoryName($errorLogfile)
$filename = [io.path]::GetFileNameWithoutExtension($errorLogfile)
$ext = [io.path]::GetExtension($errorLogfile)
$errorLogfile = "$dirName\$filename$(get-date -Format yyyy-MM-dd)$ext"
#Setup Retention Period
$LastWrite = (Get-Date).AddDays(-$retentionPeriod)#.ToString("d")
$AICLastWrite = (Get-Date).AddDays(-$AICLogsRententionPeriod)#.ToString("d")
$fileCleanerLastWrite = (Get-Date).AddDays(-$fileCleanerLogsRententionPeriod)
#EMAIL SETTINGS
$smtpServer = $configfile.Settings.SMTPServer
$emailFrom = $configfile.Settings.EmailFrom
$emailTo = $configfile.Settings.EmailTo
$emailSubject = $configfile.Settings.EmailSubject
#Update the email subject to display the Host Server value
$emailSubject -replace "HostServer", $hostServer
$countUnaccessibleUNCPaths = 0
#Check Logfiles exists, if not create them
if(!(Test-Path -Path $successLogfile))
{
New-Item -Path $successLogfile –itemtype file
}
if(!(Test-Path -Path $errorLogfile))
{
New-Item -Path $errorLogfile –itemtype file
}
foreach ($dir in $dirs)
{
#needs a check to determine if server/the UNC Path is accessible. If it fails to connect, it needs to move on to the next UNC share but a flag needs to
#be generate to alert us to investigate why the UNC share was not accessible during the job run.
If(Test-Path -Path $dir)
{
#write to output logfile Directory info
$Msg = Write-Output "$(Get-Date -UFormat "%D / %T") - Accessing: $dir"
$Msg | out-file $successLogfile
If ($scanSubDirectories -eq "True")
{
If ($deleteAllFiles -eq "True")
{
#ScanSubDirectories and delete all files older than the $retentionPeriod, include Sub-Directories / also forces the deletion of any hidden files
$logFiles = Get-ChildItem -Path $dir -Force -Recurse -Exclude $fileExclusions[0],$fileExclusions[1] | Where { $_.LastWriteTime -le "$LastWrite" }
DeleteLogFiles($logFiles)
#foreach($logFile in $logFiles)
#{
# if($logFile -ne $null)
# {
# $Msg = Write-Output "$("Deleting File $logFile")"
# $Msg | out-file $successLogfile -append
# Remove-Item $logFile.FullName -Force
# }
#}
}
Else
{
#"ScanSubDirectories but only delete specified file types."
$logFiles = Get-Childitem $dir -Include $fileTypesToDelete[0],$fileTypesToDelete[1],$fileTypesToDelete[2], $liveSiteLogs -Recurse -Exclude $fileExclusions[0],$fileExclusions[1] | Where {$_.LastWriteTime -le "$LastWrite"}
DeleteLogFiles($logFiles)
#foreach($logFile in $logFiles)
#{
# if($logFile -ne $null)
# {
# $Msg = Write-Output "$("Deleting File $logFile")"
# $Msg | out-file $successLogfile -append
# Remove-Item $logFile.FullName -Force
# }
#}
}
}
Else
{
#Only delete files in top level Directory
If ($deleteAllFiles -eq "True")
{
$logFiles = Get-ChildItem -Path $dir -Force -Exclude $fileExclusions[0],$fileExclusions[1] | Where { $_.LastWriteTime -le "$LastWrite" }
DeleteLogFiles($logFiles)
#foreach($logFile in $logFiles)
#{
# if($logFile -ne $null)
# {
# $Msg = Write-Output "$("Deleting File $logFile")"
# $Msg | out-file $successLogfile -append
# Remove-Item $logFile.FullName -Force
# }
#}
}
Else
{
$logFiles = Get-Childitem $dir -Include $fileTypesToDelete[0],$fileTypesToDelete[1],$fileTypesToDelete[2], $liveSiteLogs -Exclude $fileExclusions[0],$fileExclusions[1] | Where {$_.LastWriteTime -le "$LastWrite"}
DeleteLogFiles($logFiles)
#foreach($logFile in $logFiles)
#{
# if($logFile -ne $null)
# {
# $Msg = Write-Output "$("Deleting File $logFile")"
# $Msg | out-file $successLogfile -append
# Remove-Item $logFile.FullName -Force
# }
#}
}
}
}
Else
{
$countUnaccessibleUNCPaths++
#server/the UNC Path is unaccessible
$Msg = Write-Output "$(Get-Date -UFormat "%D / %T") Unable to access $dir."
$Msg | out-file $errorLogfile -append
}
# Call the function to Delete the AIC XML Logfiles
DeleteAICXMLLogs $dir
}
#If any of the directories were unaccessible send an email to alert the team
if($countUnaccessibleUNCPaths.count -gt 0)
{
# Call the function to send the email
SendEmail $emailSubject $emailFrom $emailTo
}
#Only keep 2 weeks worth of the FileCleaner App logs for reference purposes
If(Test-Path -Path $fileCleanerLogs)
{
#write to output logfile Directory info
$Msg = Write-Output "$(Get-Date -UFormat "%D / %T") - Accessing: $fileCleanerLogs"
$Msg | out-file $successLogfile
$fileCleanerLogs = Get-Childitem $fileCleanerLogs -Recurse | Where {$_.LastWriteTime -le "$fileCleanerLastWrite"}
DeleteLogFiles($fileCleanerLogs)
#foreach($fileCleanerLog in $fileCleanerLogs)
#{
# if($fileCleanerLog -ne $null)
# {
# $Msg = Write-Output "$("Deleting File $fileCleanerLog")"
# $Msg | out-file $successLogfile -append
# Remove-Item $fileCleanerLog.FullName -Force
# }
#}
}
Function DeleteLogFiles($logFiles)
{
foreach($logFile in $logFiles)
{
if($logFile -ne $null)
{
$Msg = Write-Output "$("Deleting File $logFile")"
$Msg | out-file $successLogfile -append
Remove-Item $logFile.FullName -Force
}
}
}
Function DeleteAICXMLLogs($dir)
{
#Split the UNC path $dir to retrieve the server value
$parentpath = "\\" + [string]::join("\",$dir.Split("\")[2])
#test access to the \\server\D$\DebugXML path
If(Test-Path -Path $parentpath$AICLogs)
{
$Msg = Write-Output "$(Get-Date -UFormat "%D / %T") - Accessing: $parentpath$AICLogs"
$Msg | out-file $successLogfile
#Concantenate server value to $AICLogs to delete all xml logs in \\server\D$\DebugXML with a retention period of 30Days
$XMLlogFiles = Get-ChildItem -Path $parentpath$AICLogs -Force -Include $fileTypesToDelete[3]-Recurse -Exclude $fileExclusions[0],$fileExclusions[1] | Where { $_.LastWriteTime -le "$AICLastWrite" }
#get each file and add the filename to be deleted to the successLogfile before deleting the file
DeleteLogFiles($XMLlogFiles)
#foreach($XMLlogFile in $XMLlogFiles)
#{
# if($XMLlogFile -ne $null)
# {
# $Msg = Write-Output "$("Deleting File $XMLlogFile")"
# $Msg | out-file $successLogfile -append
# Remove-Item $XMLlogFile.FullName -Force
# }
#}
}
Else
{
$Msg = Write-Output "$("$parentpath$AICLogs does not exist.")"
$Msg | out-file $successLogfile -append
}
}
Function SendEmail($emailSubject, $emailFrom, $emailTo)
{
$MailMessage = New-Object System.Net.Mail.MailMessage
$SMTPClient = New-Object System.Net.Mail.smtpClient
$SMTPClient.host = $smtpServer
$Recipient = New-Object System.Net.Mail.MailAddress($emailTo, "Recipient")
$Sender = New-Object System.Net.Mail.MailAddress($emailFrom, "Sender")
$MailMessage.Sender = $Sender
$MailMessage.From = $Sender
$MailMessage.Subject = $emailSubject
$MailMessage.Body = #"
This email was generated because the FileCleaner script was unable to access some UNC Paths, please refer to $errorLogfile for more information.
Please inform the Team if you plan to resolve this.
This is an automated email please do not respond.
"#
$SMTPClient.Send($MailMessage)
}
when debugging I'm getting these errors:
DeleteAICXMLLogs : The term 'DeleteAICXMLLogs' is not recognized as
the name of a cmdlet, function, script file, or operable program.
Check the spelling of the name, or if a path was included, verify
that the path is correct and try again. At
C:\Users\pmcma\Documents\Projects\Replace FileCleaner with PowerShell
Script\FileCleaner.ps1:158 char:5
+ DeleteAICXMLLogs $dir
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (DeleteAICXMLLogs:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
SendEmail : The term 'SendEmail' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling
of the name, or if a path was included, verify that the path is
correct and try again. At C:\Users\pmcma\Documents\Projects\Replace
FileCleaner with PowerShell Script\FileCleaner.ps1:164 char:5
+ SendEmail $emailSubject $emailFrom $emailTo
+ ~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (SendEmail:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
DeleteLogFiles : The term 'DeleteLogFiles' is not recognized as the
name of a cmdlet, function, script file, or operable program. Check
the spelling of the name, or if a path was included, verify that the
path is correct and try again. At
C:\Users\pmcma\Documents\Projects\Replace FileCleaner with PowerShell
Script\FileCleaner.ps1:175 char:5
+ DeleteLogFiles($fileCleanerLogs)
+ ~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (DeleteLogFiles:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
I don't see anything wrong with how I'm declaring the functions or calling them. Any ideas why this script is failing?
PowerShell Scripts are read from the top to the bottom, so you can't use any references before they are defined, most probably that is why you are receiving errors.
Try adding your function definition blocks above the point where you call them.
Alternatively you can make a function having global scope. Just preface the function name with the keyword global: like,
function global:test ($x, $y)
{
$x * $y
}
I've had this happen as well. Try placing the functions before the business logic. This is a script, not compiled code. So the functions are yet to be declared before you are calling them.