是否可以在脚本运行之前加载其所有功能?

时间:2019-01-23 14:46:17

标签: function powershell

我有一个相当复杂的脚本,该脚本遵循以下步骤;

-> 登录(要求用户输入管理员详细信息) ---> 开始(用于查询用户信用的广告)

---> 进度(创建进度栏)

---> 搜索(进行数据搜索) ---> 问题1 -(是-选择文件夹否-创建)

---> 选择文件夹(要求用户为要存储的文档创建文件路径)   ---> 开始(根据搜索结果创建一个csv)

---> 问题2 (CSV-结果XLSX-Excel)(询问用户是否希望从Csv创建Xlsx文件)

---> 创建(检查文件路径是否存在C:\ temp \ Server_shares(如果未创建))   ---> 完成(在默认位置C:\ temp \ Server_shares创建CSV)

---> 问题2 (向用户询问是否要从Csv创建Xlsx文件)

---> 问题2 -(CSV-结果XLSX-Excel)(询问用户是否希望从Csv创建Xlsx文件)

---> 结果(用户选择不创建Xlsx来通知用户文件路径)   ---> 结束(关闭脚本)

---> Excel (从csv创建Xlsx并将其存储在默认位置或用户定义的位置)   ---> 删除(从文件路径中删除所有剩余的Csv)    ---> 结束(关闭脚本)

每次运行代码时,似乎总是出现未经处理的异常错误。

我发现它先运行然后加载函数,我需要在内存中全部运行它们,以便在调用每个函数时都不会出错。

我尝试为每个函数创建变量,但这与我已经拥有的完全相同。

[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'

我知道这是很多代码,但是为了使任何人都能复制探针,您将需要全部。

我希望它每次都运行3-4次,然后才能将其加载到内存中。

1 个答案:

答案 0 :(得分:0)

将所有功能放入PowerShell模块文件中。

C:\Module.psm1

然后在脚本中的其他任何内容之前导入该模块:

Import-Module C:\Module.psm1

对于较大的脚本,这可以使事情变得更易于管理,因为您可以将一长串函数与调用它们的脚本分开。