Anlage des Repos
This commit is contained in:
42
test/.NET FileSystemWatcher.ps1
Normal file
42
test/.NET FileSystemWatcher.ps1
Normal file
@@ -0,0 +1,42 @@
|
||||
#By BigTeddy 05 September 2011
|
||||
|
||||
#This script uses the .NET FileSystemWatcher class to monitor file events in folder(s).
|
||||
#The advantage of this method over using WMI eventing is that this can monitor sub-folders.
|
||||
#The -Action parameter can contain any valid Powershell commands. I have just included two for example.
|
||||
#The script can be set to a wildcard filter, and IncludeSubdirectories can be changed to $true.
|
||||
#You need not subscribe to all three types of event. All three are shown for example.
|
||||
# Version 1.1
|
||||
|
||||
$folder = 'd:\Programme\DFUE' # Enter the root path you want to monitor.
|
||||
$filter = '*.*' # You can enter a wildcard filter here.
|
||||
|
||||
# In the following line, you can change 'IncludeSubdirectories to $true if required.
|
||||
$fsw = New-Object IO.FileSystemWatcher $folder, $filter -Property @{IncludeSubdirectories = $true;NotifyFilter = [IO.NotifyFilters]'FileName, LastWrite'}
|
||||
|
||||
# Here, all three events are registerd. You need only subscribe to events that you need:
|
||||
|
||||
Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
|
||||
$name = $Event.SourceEventArgs.Name
|
||||
$changeType = $Event.SourceEventArgs.ChangeType
|
||||
$timeStamp = $Event.TimeGenerated
|
||||
Write-Host "The file '$name' was $changeType at $timeStamp" -fore green
|
||||
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"}
|
||||
|
||||
Register-ObjectEvent $fsw Deleted -SourceIdentifier FileDeleted -Action {
|
||||
$name = $Event.SourceEventArgs.Name
|
||||
$changeType = $Event.SourceEventArgs.ChangeType
|
||||
$timeStamp = $Event.TimeGenerated
|
||||
Write-Host "The file '$name' was $changeType at $timeStamp" -fore red
|
||||
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"}
|
||||
|
||||
Register-ObjectEvent $fsw Changed -SourceIdentifier FileChanged -Action {
|
||||
$name = $Event.SourceEventArgs.Name
|
||||
$changeType = $Event.SourceEventArgs.ChangeType
|
||||
$timeStamp = $Event.TimeGenerated
|
||||
Write-Host "The file '$name' was $changeType at $timeStamp" -fore white
|
||||
Out-File -FilePath c:\scripts\filechange\outlog.txt -Append -InputObject "The file '$name' was $changeType at $timeStamp"}
|
||||
|
||||
# To stop the monitoring, run the following commands:
|
||||
# Unregister-Event FileDeleted
|
||||
# Unregister-Event FileCreated
|
||||
# Unregister-Event FileChanged
|
||||
8
test/123.ps1
Normal file
8
test/123.ps1
Normal file
@@ -0,0 +1,8 @@
|
||||
Get-PSDrive -PSProvider FileSystemName -Scope local -ErrorAction SilentlyContinue | select root
|
||||
#", "Registry" oder "Certificate".
|
||||
|
||||
#-Scope <string>
|
||||
|
||||
foreach "(Get-PSDrive -PSProvider FileSystemName -Scope local -ErrorAction SilentlyContinue | select root)" {
|
||||
Echo
|
||||
}
|
||||
36
test/Backup-XWiki.ps1
Normal file
36
test/Backup-XWiki.ps1
Normal file
@@ -0,0 +1,36 @@
|
||||
# https://www.xwiki.org/xwiki/bin/view/Documentation/AdminGuide/Authentication/
|
||||
# Authenticate like: username:password@url and add &basicauth=1 at the end
|
||||
|
||||
# Setup Credentials and Encode them
|
||||
$Username = "DigitalData"
|
||||
$Password = "35452dd!"
|
||||
$CredentialsPair = "$($Username):$($Password)"
|
||||
$EncodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($CredentialsPair))
|
||||
|
||||
# Create Request Header for Basic Authenticastion
|
||||
$Headers = @{ Authorization = "Basic $EncodedCredentials" }
|
||||
|
||||
# Set the url
|
||||
$Url = "http://wiki.dd/xwiki11/bin/export/XWiki/XWikiPreferences?editor=globaladmin§ion=Export"
|
||||
$Path = "E:\backup.xar"
|
||||
|
||||
Write-Host "Downloading Backup from [$($url)].."
|
||||
|
||||
# Make the request
|
||||
$Response = Invoke-WebRequest -Method Get -Uri $Url -Headers $Headers
|
||||
|
||||
Write-Host "Download finished!"
|
||||
|
||||
# Write the reponse to disk
|
||||
Write-Host "Streaming file to [$($Path)].."
|
||||
|
||||
try {
|
||||
[System.IO.File]::WriteAllBytes($Path, $Response.Content)
|
||||
} catch {
|
||||
Write-Host "An error occurred:"
|
||||
Write-Host $_
|
||||
} finally {
|
||||
$Stream.Dispose()
|
||||
}
|
||||
|
||||
Write-Host "Done!"
|
||||
12
test/Beispielfenster.ps1
Normal file
12
test/Beispielfenster.ps1
Normal file
@@ -0,0 +1,12 @@
|
||||
[void][reflection.assembly]::LoadWithPartialName(„System.Windows.Forms“)
|
||||
$form = new-object Windows.Forms.Form
|
||||
$form.Text = „Beispielfenster“
|
||||
$button = new-object Windows.Forms.Button
|
||||
$button.Text = „OK“
|
||||
$button.Left = 100
|
||||
$button.Top = 100
|
||||
$button.Width = 50
|
||||
$button.Height = 25
|
||||
$button.Add_Click({$form.close()})
|
||||
$form.Controls.Add($button)
|
||||
$form.ShowDialog()
|
||||
22
test/Change_ADUser_Password_randomized.ps1
Normal file
22
test/Change_ADUser_Password_randomized.ps1
Normal file
@@ -0,0 +1,22 @@
|
||||
# Password Settings
|
||||
$PasswordLength = 8
|
||||
$password = ""
|
||||
# Set Password Character Strings
|
||||
$Set0 = "abcdefghijklmnpqrstuvwxyz".ToCharArray()
|
||||
$Set1 ="123456789".ToCharArray()
|
||||
$Set2 = "ABCDEFGHIJKLMNPQRSTUVWXYZ".ToCharArray()
|
||||
$Set3 = "!£$%^&()_ @#".ToCharArray()
|
||||
|
||||
# Build Password on Length Variable
|
||||
do{
|
||||
|
||||
$password += $set0 | Get-Random;
|
||||
$password += $set1 | Get-Random;
|
||||
$password += $set2 | Get-Random;
|
||||
$password += $set3 | Get-Random;
|
||||
}
|
||||
until ($password.Length -eq $passwordlength)
|
||||
# Convert to Secure String
|
||||
$pwd = convertto-securestring $password -asplaintext -force
|
||||
# Display Password
|
||||
$password
|
||||
22
test/Change_Service.ps1
Normal file
22
test/Change_Service.ps1
Normal file
@@ -0,0 +1,22 @@
|
||||
#
|
||||
# Change service user name and password
|
||||
# www.sivarajan.com
|
||||
#
|
||||
clear
|
||||
$UserName = "Infralab\santhosh"
|
||||
$Password = "Password"
|
||||
$Service = "MpsSvc" #Change service name with your service name
|
||||
$Cred = Get-Credential #Prompt you for user name and password
|
||||
Import-CSV C:\Scripts\input.csv | % {
|
||||
$ServerN = $_.ServerName
|
||||
$svcD=gwmi win32_service -computername $ServerN -filter "name='$service'" -Credential $cred
|
||||
$StopStatus = $svcD.StopService()
|
||||
If ($StopStatus.ReturnValue -eq "0") # validating status - http://msdn.microsoft.com/en-us/library/aa393673(v=vs.85).aspx
|
||||
{write-host "$ServerN -> Service Stopped Successfully"}
|
||||
$ChangeStatus = $svcD.change($null,$null,$null,$null,$null,$null,$UserName,$Password,$null,$null,$null)
|
||||
If ($ChangeStatus.ReturnValue -eq "0")
|
||||
{write-host "$ServerN -> Sucessfully Changed User Name"}
|
||||
$StartStatus = $svcD.StartService()
|
||||
If ($ChangeStatus.ReturnValue -eq "0")
|
||||
{write-host "$ServerN -> Service Started Successfully"}
|
||||
}
|
||||
146
test/Checkboxen.ps1
Normal file
146
test/Checkboxen.ps1
Normal file
@@ -0,0 +1,146 @@
|
||||
function GenerateForm {
|
||||
|
||||
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
|
||||
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
|
||||
|
||||
$form1 = New-Object System.Windows.Forms.Form
|
||||
$button1 = New-Object System.Windows.Forms.Button
|
||||
$listBox1 = New-Object System.Windows.Forms.ListBox
|
||||
$checkBox3 = New-Object System.Windows.Forms.CheckBox
|
||||
$checkBox2 = New-Object System.Windows.Forms.CheckBox
|
||||
$checkBox1 = New-Object System.Windows.Forms.CheckBox
|
||||
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
|
||||
|
||||
$b1= $false
|
||||
$b2= $false
|
||||
$b3= $false
|
||||
|
||||
#----------------------------------------------
|
||||
#Generated Event Script Blocks
|
||||
#----------------------------------------------
|
||||
|
||||
$handler_button1_Click=
|
||||
{
|
||||
$listBox1.Items.Clear();
|
||||
|
||||
if ($checkBox1.Checked) { $listBox1.Items.Add( "Checkbox 1 is checked" ) }
|
||||
|
||||
if ($checkBox2.Checked) { $listBox1.Items.Add( "Checkbox 2 is checked" ) }
|
||||
|
||||
if ($checkBox3.Checked) { $listBox1.Items.Add( "Checkbox 3 is checked" ) }
|
||||
|
||||
if ( !$checkBox1.Checked -and !$checkBox2.Checked -and !$checkBox3.Checked ) { $listBox1.Items.Add("No CheckBox selected....")}
|
||||
}
|
||||
|
||||
$OnLoadForm_StateCorrection=
|
||||
{#Correct the initial state of the form to prevent the .Net maximized form issue
|
||||
$form1.WindowState = $InitialFormWindowState
|
||||
}
|
||||
|
||||
#----------------------------------------------
|
||||
#region Generated Form Code
|
||||
$form1.Text = "Primal Form"
|
||||
$form1.Name = "form1"
|
||||
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
|
||||
$System_Drawing_Size = New-Object System.Drawing.Size
|
||||
$System_Drawing_Size.Width = 450
|
||||
$System_Drawing_Size.Height = 236
|
||||
$form1.ClientSize = $System_Drawing_Size
|
||||
|
||||
$button1.TabIndex = 4
|
||||
$button1.Name = "button1"
|
||||
$System_Drawing_Size = New-Object System.Drawing.Size
|
||||
$System_Drawing_Size.Width = 75
|
||||
$System_Drawing_Size.Height = 23
|
||||
$button1.Size = $System_Drawing_Size
|
||||
$button1.UseVisualStyleBackColor = $True
|
||||
|
||||
$button1.Text = "Run Script"
|
||||
|
||||
$System_Drawing_Point = New-Object System.Drawing.Point
|
||||
$System_Drawing_Point.X = 27
|
||||
$System_Drawing_Point.Y = 156
|
||||
$button1.Location = $System_Drawing_Point
|
||||
$button1.DataBindings.DefaultDataSourceUpdateMode = 0
|
||||
$button1.add_Click($handler_button1_Click)
|
||||
|
||||
$form1.Controls.Add($button1)
|
||||
|
||||
$listBox1.FormattingEnabled = $True
|
||||
$System_Drawing_Size = New-Object System.Drawing.Size
|
||||
$System_Drawing_Size.Width = 301
|
||||
$System_Drawing_Size.Height = 212
|
||||
$listBox1.Size = $System_Drawing_Size
|
||||
$listBox1.DataBindings.DefaultDataSourceUpdateMode = 0
|
||||
$listBox1.Name = "listBox1"
|
||||
$System_Drawing_Point = New-Object System.Drawing.Point
|
||||
$System_Drawing_Point.X = 137
|
||||
$System_Drawing_Point.Y = 13
|
||||
$listBox1.Location = $System_Drawing_Point
|
||||
$listBox1.TabIndex = 3
|
||||
|
||||
$form1.Controls.Add($listBox1)
|
||||
|
||||
|
||||
$checkBox3.UseVisualStyleBackColor = $True
|
||||
$System_Drawing_Size = New-Object System.Drawing.Size
|
||||
$System_Drawing_Size.Width = 104
|
||||
$System_Drawing_Size.Height = 24
|
||||
$checkBox3.Size = $System_Drawing_Size
|
||||
$checkBox3.TabIndex = 2
|
||||
$checkBox3.Text = "CheckBox 3"
|
||||
$System_Drawing_Point = New-Object System.Drawing.Point
|
||||
$System_Drawing_Point.X = 27
|
||||
$System_Drawing_Point.Y = 75
|
||||
$checkBox3.Location = $System_Drawing_Point
|
||||
$checkBox3.DataBindings.DefaultDataSourceUpdateMode = 0
|
||||
$checkBox3.Name = "checkBox3"
|
||||
|
||||
$form1.Controls.Add($checkBox3)
|
||||
|
||||
$checkBox2.UseVisualStyleBackColor = $True
|
||||
$System_Drawing_Size = New-Object System.Drawing.Size
|
||||
$System_Drawing_Size.Width = 104
|
||||
$System_Drawing_Size.Height = 24
|
||||
$checkBox2.Size = $System_Drawing_Size
|
||||
$checkBox2.TabIndex = 1
|
||||
$checkBox2.Text = "CheckBox 2"
|
||||
$System_Drawing_Point = New-Object System.Drawing.Point
|
||||
$System_Drawing_Point.X = 27
|
||||
$System_Drawing_Point.Y = 44
|
||||
$checkBox2.Location = $System_Drawing_Point
|
||||
$checkBox2.DataBindings.DefaultDataSourceUpdateMode = 0
|
||||
$checkBox2.Name = "checkBox2"
|
||||
|
||||
$form1.Controls.Add($checkBox2)
|
||||
|
||||
|
||||
|
||||
$checkBox1.UseVisualStyleBackColor = $True
|
||||
$System_Drawing_Size = New-Object System.Drawing.Size
|
||||
$System_Drawing_Size.Width = 104
|
||||
$System_Drawing_Size.Height = 24
|
||||
$checkBox1.Size = $System_Drawing_Size
|
||||
$checkBox1.TabIndex = 0
|
||||
$checkBox1.Text = "CheckBox 1"
|
||||
$System_Drawing_Point = New-Object System.Drawing.Point
|
||||
$System_Drawing_Point.X = 27
|
||||
$System_Drawing_Point.Y = 13
|
||||
$checkBox1.Location = $System_Drawing_Point
|
||||
$checkBox1.DataBindings.DefaultDataSourceUpdateMode = 0
|
||||
$checkBox1.Name = "checkBox1"
|
||||
|
||||
$form1.Controls.Add($checkBox1)
|
||||
|
||||
|
||||
#Save the initial state of the form
|
||||
$InitialFormWindowState = $form1.WindowState
|
||||
#Init the OnLoad event to correct the initial state of the form
|
||||
$form1.add_Load($OnLoadForm_StateCorrection)
|
||||
#Show the Form
|
||||
$form1.ShowDialog()| Out-Null
|
||||
|
||||
} #End Function
|
||||
|
||||
#Call the Function
|
||||
GenerateForm
|
||||
94
test/Close-FileHandles_and_Copy-FilesAndFolders.ps1
Normal file
94
test/Close-FileHandles_and_Copy-FilesAndFolders.ps1
Normal file
@@ -0,0 +1,94 @@
|
||||
function Close-FileHandles
|
||||
{
|
||||
param(
|
||||
[parameter(mandatory=$True, HelpMessage='Full or partial file path')]
|
||||
[string]$FilePath
|
||||
)
|
||||
|
||||
Write-Host "Searching for locks on path: $FilePath"
|
||||
|
||||
gps | Where-Object { $_.Path -match $FilePath.Replace("\", "\\") } |% `
|
||||
{
|
||||
Write-Host "Closing process $_.Name with path: $_.Path"
|
||||
Stop-Process -Id $_.Id -Force
|
||||
}
|
||||
}
|
||||
|
||||
function Copy-FilesAndFolders
|
||||
{
|
||||
param(
|
||||
[parameter(mandatory=$True, HelpMessage='Source directory from which to copy')]
|
||||
[string]$SourceDir,
|
||||
|
||||
[parameter(mandatory=$True, HelpMessage='Destination directory to which to copy')]
|
||||
[string]$DestinationDir,
|
||||
|
||||
[parameter(mandatory=$True, HelpMessage='Clean destination directory before copying')]
|
||||
[bool]$CleanDestinationDir=$False,
|
||||
|
||||
[parameter(mandatory=$False, HelpMessage='Timeout')]
|
||||
[int]$Timeout=20
|
||||
)
|
||||
|
||||
# Ensure script fails on any errors
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
if ($CleanDestinationDir -eq $True)
|
||||
{
|
||||
# First, try to remove the folder without explicitly dropping any locks; leave a
|
||||
|
||||
reasonable
|
||||
# time for services to stop and threads to end
|
||||
for ($j = 0; $j -le 2; $j ++)
|
||||
{
|
||||
Write-Host "Attempting to delete $DestinationDir, since CleanDestinationDir was specified"
|
||||
|
||||
for ($i = 1; $i -le $Timeout -and (Test-Path -Path $DestinationDir -ErrorAction SilentlyContinue); $i ++)
|
||||
{
|
||||
Write-Host "Attempting to remove folder $DestinationDir ($i of $Timeout)"
|
||||
Remove-Item -Path $DestinationDir -Recurse -Force -ErrorAction SilentlyContinue
|
||||
Start-Sleep -Milliseconds 1000
|
||||
}
|
||||
|
||||
if (Test-Path -Path $DestinationDir -ErrorAction SilentlyContinue)
|
||||
{
|
||||
if ($j -eq 0)
|
||||
{
|
||||
Write-Host "Folder is still locked; dropping locks and retrying"
|
||||
Close-FileHandles -FilePath $DestinationDir
|
||||
}
|
||||
else
|
||||
{
|
||||
throw "Unable to clean $DestinationDir; aborting"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "Checking whether $DestinationDir directory exists"
|
||||
|
||||
if (!(Test-Path $DestinationDir -ErrorAction SilentlyContinue))
|
||||
{
|
||||
# Create the destination folder
|
||||
Write-Host "$DestinationDir does not exist; creating"
|
||||
New-Item -ItemType directory -Path $DestinationDir
|
||||
}
|
||||
|
||||
# Copy the folder
|
||||
Write-Host "Copying $SourceDir to $DestinationDir"
|
||||
Get-ChildItem -Path $SourceDir |% `
|
||||
{
|
||||
try
|
||||
{
|
||||
Write-Host "Copying: $_"
|
||||
Copy-Item $_.fullname "$DestinationDir" -Recurse -Force
|
||||
}
|
||||
catch
|
||||
{
|
||||
Write-Host "Destination file appears to be locked; attempting to drop locks on
|
||||
|
||||
folder"
|
||||
Close-FileHandles -FilePath $DestinationDir
|
||||
}
|
||||
}
|
||||
}
|
||||
110
test/ConsoleTest.ps1
Normal file
110
test/ConsoleTest.ps1
Normal file
@@ -0,0 +1,110 @@
|
||||
<# ConsoleTest.ps1 (c) infoSpectrum Inc. 2011-2012 #>
|
||||
|
||||
# Examples of Console commands
|
||||
# Run "PShellExec ConsoleTest.ps1 /s" to see console interactions and output
|
||||
|
||||
$testWrites = `
|
||||
{
|
||||
Write-Verbose "More Console Output Examples:"
|
||||
|
||||
Write-Error "Error 1"
|
||||
Write-Error "Error 2"
|
||||
|
||||
Write-Warning "Warning 2"
|
||||
|
||||
Write-Debug "Debug test 2"
|
||||
|
||||
Write-Output "Output 1"
|
||||
"Output 2"
|
||||
}
|
||||
|
||||
$ErrorActionPreference = "Continue"
|
||||
$verbosePreference = "Continue"
|
||||
$WarningPreference = "Continue"
|
||||
$DebugPreference = "Continue"
|
||||
Write-Host $verbosePreference
|
||||
|
||||
Write-Warning ("Running from "+$pwd)
|
||||
|
||||
Write-Verbose "Checking for any script arguments..."
|
||||
if ($($args.count) -lt 1)
|
||||
{Write-Verbose "No arguments"}
|
||||
else
|
||||
{
|
||||
# Script arguments are enclosed in quotes and comma separated:
|
||||
# PShellExec ConsoleTest.ps1 /a:"?one,two,?3rdArg"
|
||||
for ( $j=0; $j -lt $($args.count); $j++)
|
||||
{
|
||||
Write-Verbose ("Argument"+($j+1).ToString()+"="+$args[$j])
|
||||
}
|
||||
}
|
||||
|
||||
Write-Debug "Debug test 1"
|
||||
|
||||
$ins = Read-Host "Input a line:" # reads input with a default value
|
||||
$ins
|
||||
|
||||
Write-Verbose "Enter a Password?"
|
||||
$ins = Read-Host -AsSecureString # reads in a secure string password
|
||||
if ($ins -and $ins -ne "")
|
||||
{
|
||||
$ins = (New-Object System.Management.Automation.PSCredential('dummy',$ins)).GetNetworkCredential().Password
|
||||
Write-Host $ins # outputs password in plain text
|
||||
}
|
||||
$ins = Read-Host -Prompt 'Age 21 or older?:Yes' # prompts for input with a default value
|
||||
$ins
|
||||
Write-Verbose "Results for Console Output:"
|
||||
$testThis = Start-Job -Name "ConsoleTest" -ScriptBlock $testWrites
|
||||
Wait-Job -Job $testThis -TimeOut -1
|
||||
|
||||
foreach ($jobResult in $testThis.ChildJobs)
|
||||
{
|
||||
$jobResult.Output | Out-Host | Write-Host
|
||||
$jobResult.Verbose | ForEach-Object -Process {$_.Message | Out-Host | Write-Host}
|
||||
$jobResult.Warning | ForEach-Object -Process {$_.Message | Out-Host | Write-Host}
|
||||
$jobResult.Debug | ForEach-Object -Process {$_.Message | Out-Host | Write-Host}
|
||||
$jobResult.Error | ForEach-Object -Process {$_ | Out-Host | Write-Host}
|
||||
}
|
||||
|
||||
|
||||
$dOpt = new-object System.Management.Automation.Host.ChoiceDescription 'Demo', "Example of Get-Credential"
|
||||
$sOpt = new-object System.Management.Automation.Host.ChoiceDescription 'Skip', "Skip Get-Credential"
|
||||
$choices = [System.Management.Automation.Host.ChoiceDescription[]] ($dOpt,$sOpt)
|
||||
$sel=0
|
||||
$sel = $host.ui.PromptForChoice("Get-Credential Demo",'Your choice:',$choices,$sel)
|
||||
if ($sel -eq 0)
|
||||
{
|
||||
Write-Verbose "Example of Get-Credential"
|
||||
try
|
||||
{ $logon = Get-Credential -Verbose
|
||||
"Logon user: {0}" -f $logon.Username
|
||||
if (test-path variable:\PSExecOut)
|
||||
{$variable:PSExecOut="Logon user: "+ $logon.Username}
|
||||
}
|
||||
catch
|
||||
{
|
||||
$err = $_.Exception.ToString()
|
||||
Write-Warning $err
|
||||
}
|
||||
}
|
||||
|
||||
Write-Verbose "PShellExec Info:"
|
||||
Get-Process PShellExec
|
||||
|
||||
<#
|
||||
NOTES
|
||||
|
||||
$myInvocation use within PShellExec:
|
||||
|
||||
The following return empty or null (when outside a function):
|
||||
|
||||
$myInvocation.ScriptName, $myInvocation.InvocationName,
|
||||
$myInvocation.MyCommand.Name, $myInvocation.MyCommand.Path
|
||||
|
||||
$PSExecName is a variable provided to PShellExec users and contains a string with the full script path and filename.
|
||||
#>
|
||||
|
||||
if (test-path variable:\PSExecName)
|
||||
{echo "`$PSExecName: $($PSExecName)"}
|
||||
|
||||
Read-Host "Press [Enter] to exit ConsoleTest...:Goodbye"
|
||||
19
test/ConvertWord2PDF.ps1
Normal file
19
test/ConvertWord2PDF.ps1
Normal file
@@ -0,0 +1,19 @@
|
||||
$documents_path = 'e:\doc2pdf'
|
||||
|
||||
$word_app = New-Object -ComObject Word.Application
|
||||
|
||||
# This filter will find .doc as well as .docx documents
|
||||
Get-ChildItem -Path $documents_path -Filter *.doc? | ForEach-Object {
|
||||
|
||||
$document = $word_app.Documents.Open($_.FullName)
|
||||
|
||||
$pdf_filename = "$($_.DirectoryName)\$($_.BaseName).pdf"
|
||||
|
||||
$document.SaveAs([ref] $pdf_filename, [ref] 17)
|
||||
|
||||
$document.Close()
|
||||
}
|
||||
|
||||
$word_app.Quit()
|
||||
|
||||
#$documents_path = Split-Path -parent $MyInvocation.MyCommand.Path
|
||||
BIN
test/Custom_GUI.ps1
Normal file
BIN
test/Custom_GUI.ps1
Normal file
Binary file not shown.
BIN
test/Custom_Inputbox.ps1
Normal file
BIN
test/Custom_Inputbox.ps1
Normal file
Binary file not shown.
BIN
test/Custom_Messagebox.ps1
Normal file
BIN
test/Custom_Messagebox.ps1
Normal file
Binary file not shown.
10
test/Dateien_Verschieben.ps1
Normal file
10
test/Dateien_Verschieben.ps1
Normal file
@@ -0,0 +1,10 @@
|
||||
Set-Variable -Name QuellPfad -Value "\\192.168.10.53\ftp\WebFrontEndVCL\WinSped_Export" -Scope Script
|
||||
Set-Variable -Name ZielPfad -Value "\\dd-sto01\dd-sto01-a2\FTP\DD - Kunden\Vetra\WinSped_Export" -Scope Script
|
||||
|
||||
$Dateien = Get-ChildItem –Path "$QuellPfad" -Include *.xml | where-object {$_.lastwritetime -lt (get-date).addminutes(-3)}
|
||||
|
||||
FOREACH ($Datei in $Dateien)
|
||||
{
|
||||
Write-Host "Verschiebe Datei $Datei"
|
||||
$Datei | Move-Item -Destination $ZielPfad -Force
|
||||
}
|
||||
BIN
test/Dateifindenundausführen.ps1
Normal file
BIN
test/Dateifindenundausführen.ps1
Normal file
Binary file not shown.
37
test/EDMIAPI-Test.ps1
Normal file
37
test/EDMIAPI-Test.ps1
Normal file
@@ -0,0 +1,37 @@
|
||||
Set-Variable -Scope Global -Name ScriptName -Value (($MyInvocation.MyCommand.Name) -split "\.")[0].ToString()
|
||||
Set-Variable -Scope Global -Name ScriptPath -Value (Split-Path ($MyInvocation.MyCommand.Path))
|
||||
Set-Variable -Scope Global -Name EDMIServerURL -Value "net.tcp://172.24.12.67:9000/DigitalData/Services/Main"
|
||||
|
||||
Import-Module "S:\Schrank\DigitalData.Modules.EDMIAPI.dll" -Force
|
||||
Import-Module "S:\Schrank\DigitalData.Modules.Logging.dll" -Force
|
||||
Import-Module "S:\Schrank\NLog.dll" -Force
|
||||
|
||||
Remove-Item -Path "E:\EDMILog\" -Filter *.log -Force -Recurse -ErrorAction SilentlyContinue
|
||||
|
||||
cls
|
||||
|
||||
#Logger initialisieren
|
||||
$log = [DigitalData.Modules.Logging.LogConfig]::New([DigitalData.Modules.Logging.LogConfig+PathType]::CustomPath, "E:\EDMILog", $NULL)
|
||||
$log.Debug = $True
|
||||
$logger = $log.GetLogger()
|
||||
$logger.Info("Logger ist initialisiert!")
|
||||
$logger.debug("debug-Logger ist initialisiert!")
|
||||
|
||||
$document = [DigitalData.Modules.EDMIAPI.Document]::New($log, $EDMIServerURL)
|
||||
$ImportFile = $document.ImportFile("E:\JenneJ\ghost.sql")
|
||||
|
||||
If ($ImportFile.OK -eq "false") {
|
||||
|
||||
Write-Host "War erfolgreich!"
|
||||
|
||||
} #end if
|
||||
ELSE {
|
||||
|
||||
Write-Host $ImportFile.ErrorMessage
|
||||
|
||||
} #end else
|
||||
|
||||
#$ExportFile = $document.GetDocumentByDocumentId($ImportFile.Document.DocumentId)
|
||||
$ExportFile = $document.GetDocumentByContainerId($ImportFile.Document.ContainerId)
|
||||
|
||||
[System.IO.File]::WriteAllBytes("E:\" + $ExportFile.Document.FileName, $ExportFile.Contents)
|
||||
BIN
test/FileSystemWatcher.ps1
Normal file
BIN
test/FileSystemWatcher.ps1
Normal file
Binary file not shown.
BIN
test/Find-PInvoke.ps1
Normal file
BIN
test/Find-PInvoke.ps1
Normal file
Binary file not shown.
579
test/Func-File-copy-or-move.ps1
Normal file
579
test/Func-File-copy-or-move.ps1
Normal file
@@ -0,0 +1,579 @@
|
||||
# PowerShell 4.0 Script
|
||||
# Einfaches kopieren oder verschieben von Dateien.
|
||||
|
||||
# Digital Data
|
||||
# Ludwig-Rinn-Strasse 16
|
||||
# 35452 Heuchelheim
|
||||
# Tel.: 0641 / 202360
|
||||
# E-Mail: info@didalog.de
|
||||
|
||||
# Version 1.0
|
||||
# Letzte Aktualisierung: 08.12.2014
|
||||
|
||||
# Mindestanforderung für dieses Skript:
|
||||
# Microsoft Windows XP SP3 / Server 2008 R2 SP1 -> siehe KB976932
|
||||
# Microsoft .NET Framework 4.5 -> siehe KB2858728
|
||||
# Microsoft PowerShell 4.0 -> siehe KB2819745
|
||||
|
||||
# WICHTIG: Falls sich dieses Skript nicht ausführen lässt,
|
||||
# muss dieser PS-Befehl noch mit administrativen Rechten ausgeführt werden:
|
||||
# set-executionpolicy unrestricted
|
||||
|
||||
#Requires –Version 4.0
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------
|
||||
############################ Zusätzliche Assemblys hinzufügen bzw. laden. ############################
|
||||
#-----------------------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------
|
||||
######################################## Variablen definieren. #######################################
|
||||
#-----------------------------------------------------------------------------------------------------
|
||||
|
||||
Set-Variable -Name ScriptName -Value (($MyInvocation.MyCommand.Name) -split "\.")[0].ToString() -Scope script
|
||||
Set-Variable -Name ScriptPath -Value (Split-Path ($MyInvocation.MyCommand.Path)) -Scope script
|
||||
Set-Variable -Name ConfigFile -Value "$ScriptPath\$ScriptName`_Settings.ini" -Scope script
|
||||
Set-Variable -Name KonfigWerte -Value $NULL -Scope script
|
||||
|
||||
Set-Variable -Name ZeitStempel1 -Value $(Get-Date -Format 'ddMMyyyy_HHmmss') -Scope script
|
||||
Set-Variable -Name Timestamp1 -Value $(Get-Date -Format 'ddMMyyyy') -Scope script
|
||||
Set-Variable -Name Timestamp2 -Value $(Get-Date -Format 'ddMMyyyy_HHmmss') -Scope script
|
||||
Set-Variable -Name Timestamp3 -Value $(Get-Date -Format 'ddMMyyyy_HHmmssffff') -Scope script
|
||||
Set-Variable -Name Fehler -Value $NULL -Scope local
|
||||
Set-Variable -Name LogDatei -Value "$ScriptName`_$ZeitStempel1.log" -Scope script
|
||||
Set-Variable -Name LogEintrag -Value $NULL -Scope local
|
||||
Set-Variable -Name LogPathListe -Value $NULL -Scope script
|
||||
Set-Variable -Name LogPath -Value $NULL -Scope script
|
||||
Set-Variable -Name LogPathEintrag -Value $NULL -Scope script
|
||||
Set-Variable -Name LogKeepTime -Value 60 -Scope script
|
||||
Set-Variable -Name FileDelayAge -Value 5 -Scope script
|
||||
Set-Variable -Name Item -Value $NULL -Scope local
|
||||
Set-Variable -Name Items -Value $NULL -Scope local
|
||||
Set-Variable -Name Path -Value $NULL -Scope local
|
||||
Set-Variable -Name PathTest -Value $NULL -Scope local
|
||||
Set-Variable -Name ProzessTest -Value $NULL -Scope local
|
||||
Set-Variable -Name VersionSeperator -Value '~' -Scope local
|
||||
Set-Variable -Name FileSeperator -Value ''
|
||||
|
||||
Set-Variable -Name Sourcepath -Value $NULL -Scope local
|
||||
Set-Variable -Name Destinationpath -Value $NULL -Scope local
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------
|
||||
####################################### Funktionen definieren. #######################################
|
||||
#-----------------------------------------------------------------------------------------------------
|
||||
|
||||
$test1 = Select-String -Path $MyInvocation.InvocationName -Pattern Func-*| select Matches
|
||||
|
||||
write-host $test1
|
||||
|
||||
pause
|
||||
|
||||
Function Func-Path-Check {
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Function will check the given Path for existence.
|
||||
.DESCRIPTION
|
||||
Function will check the given Path for existence. If Path doesn´t exist, Function will try to create it.
|
||||
.REQUIREMENT General
|
||||
PowerShell V2 and Function "Func-Write-Logfile".
|
||||
.REQUIREMENT Variables
|
||||
Path, PathTest
|
||||
.VERSION
|
||||
1.0 / 06.11.2014
|
||||
.EXAMPLE
|
||||
Func-Path-Check -Path "E:\Path\to\check"
|
||||
.EXAMPLE
|
||||
Func-Path-Check -Path "E:\Path\to\create"
|
||||
.PARAMETER Path
|
||||
Give the full Path you want to check or create.
|
||||
#>
|
||||
|
||||
Param
|
||||
(
|
||||
[String]$Path
|
||||
)
|
||||
|
||||
$PathTest = Test-Path -PathType Container $Path
|
||||
Func-Write-Logfile -LogEintrag "Checking Path $Path for existence."
|
||||
IF ($PathTest -eq "True")
|
||||
{
|
||||
Func-Write-Logfile -LogEintrag "Path $Path is already existence and can be used."
|
||||
}
|
||||
ELSE
|
||||
{
|
||||
Try
|
||||
{
|
||||
Func-Write-Logfile -LogEintrag "Path $Path has to been created."
|
||||
New-Item -Path $Path -ItemType directory -force -ErrorAction Stop
|
||||
}
|
||||
|
||||
Catch
|
||||
{
|
||||
Func-Write-Logfile -LogEintrag "ERROR: Unable to create Path."
|
||||
Func-Write-Logfile -LogEintrag "INFO: Maybe there is an access or rights Problem."
|
||||
Func-Write-Logfile -LogEintrag "Application was unplannd terminated."
|
||||
EXIT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Function Func-Write-Logfile {
|
||||
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Function will write a given String to a Logfile.
|
||||
.DESCRIPTION
|
||||
Function will write a given String to a Logfile. It will even log Error Messages.
|
||||
.REQUIREMENT General
|
||||
PowerShell V2
|
||||
.REQUIREMENT Variables
|
||||
LogPathListe, LogPathEintrag, LogPath, Fehler, Pfad-Test
|
||||
.VERSION
|
||||
1.0 / 06.11.2014
|
||||
.EXAMPLE
|
||||
Func-Path-Check -Log "Write this in my Log, please."
|
||||
.EXAMPLE
|
||||
Func-Path-Check -Log "Write this Variabel $Variable in my Log, please."
|
||||
.PARAMETER Log
|
||||
Give the Sting you want to be written in the Logfile.
|
||||
#>
|
||||
|
||||
Param
|
||||
(
|
||||
[string]$LogEintrag
|
||||
)
|
||||
|
||||
# Der Fehlerindikator ($?) muss bereits zu Anfang abgefragt werden,
|
||||
# da er von JEDEM funktionierenden Befehl wieder auf True gesetzt wird.
|
||||
IF ($? -ne 'True')
|
||||
{
|
||||
Set-Variable -Name Fehler -Value 1
|
||||
}
|
||||
|
||||
IF ($LogPath -eq $NULL)
|
||||
{
|
||||
|
||||
Set-Variable -Name LogPathListe -Value @($LogPathListe)
|
||||
Set-Variable -Name LogPathListe -Value ($LogPathListe += "$ScriptPath\Logs","$env:temp")
|
||||
|
||||
FOREACH ($LogPathEintrag in $LogPathListe)
|
||||
{
|
||||
$PfadTest = Test-Path -PathType Container "$LogPathEintrag"
|
||||
Write-Host "Pfadüberprüfung: Prüfe ob LogPath bereits angelegt ist: $LogPathEintrag"
|
||||
IF ($PfadTest -eq "True")
|
||||
{
|
||||
Write-Host "Pfadüberprüfung: LogPath $LogPathEintrag ist bereits angelegt!"
|
||||
Set-Variable -Name LogPath -Value $LogPathEintrag
|
||||
break
|
||||
}
|
||||
ELSE
|
||||
{
|
||||
Write-Host "Pfadüberprüfung: LogPath $LogPathEintrag muss angelegt werden."
|
||||
New-Item -Path $LogPathEintrag -ItemType directory -force -ErrorAction SilentlyContinue | Out-Null
|
||||
$PfadTest = Test-Path -PathType Container $LogPathEintrag
|
||||
Write-Host "Pfadüberprüfung: Prüfe ob Pfad erfolgreich angelegt werden konnte."
|
||||
IF ($PfadTest -eq "True")
|
||||
{
|
||||
Write-Host "Pfadüberprüfung: Pfad $LogPathEintrag wurde erfolgreich angelegt."
|
||||
Set-Variable -Name LogPath -Value $LogPathEintrag
|
||||
break
|
||||
}
|
||||
ELSE
|
||||
{
|
||||
Write-Host "Pfadüberprüfung: Pfad $LogPathEintrag konnte nicht angelegt werden."
|
||||
Set-Variable -Name LogPath -Value $LogPathEintrag
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ELSEIF ($LogPath -eq $env:temp)
|
||||
{
|
||||
Write-Warning "FEHLER: LogPath nicht zugreifbar oder nicht korrekt konfiguriert!"
|
||||
Write-Warning "INFO: $LogPath - wird nun verwendet!"
|
||||
Write-Warning "Programm wird trotzdem fortgesetzt."
|
||||
}
|
||||
|
||||
Set-Variable -Name LogPath -Value $LogPath -scope script
|
||||
|
||||
Write-Host $LogEintrag
|
||||
Add-content $LogPath\$LogDatei -value "$(Get-Date -Format 'dd.MM.yyyy')-$(Get-Date -Format 'HH:mm:ss'): $LogEintrag"
|
||||
|
||||
IF ($Fehler -eq 1)
|
||||
{
|
||||
Write-Host "Fehlermeldung: $error"
|
||||
Add-content $LogPath\$LogDatei -value "$(Get-Date -Format 'dd.MM.yyyy')-$(Get-Date -Format 'HH:mm:ss'): Fehlermeldung: $error"
|
||||
# Setze Fehlerspeicher zurück
|
||||
$error.clear()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
# Funktion um eine Textdatei (ASCII), komplett einzulesen.
|
||||
Function Func-ReadConfigFile
|
||||
{
|
||||
Param
|
||||
(
|
||||
[String]$ConfigFile
|
||||
)
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Prüfe ob Konfigurationsdatei: $ConfigFile vorhanden ist."
|
||||
$DateiTest = Test-Path -PathType Leaf $ConfigFile
|
||||
IF ($DateiTest -eq "True")
|
||||
{
|
||||
Write-Host "Konfigurationsdatei ist vorhanden, fahre fort."
|
||||
}
|
||||
ELSE
|
||||
{
|
||||
Func-Write-Logfile -LogEintrag "FEHLER: Konfigurationsdatei ist nicht vorhanden!"
|
||||
Func-Write-Logfile -LogEintrag "Programm wird ungeplant beendet."
|
||||
EXIT
|
||||
}
|
||||
|
||||
Write-Host "Konfigurationsdatei wird nun eingelesen."
|
||||
Set-Variable -Name KonfigWerte -Value (Select-String -path $ConfigFile -pattern "=" | where {-not($_-match "#")})
|
||||
IF ($KonfigWerte -eq $Null)
|
||||
{
|
||||
Write-Host "Keine gültigen Werte in Konfigurationsdatei erkannt!"
|
||||
}
|
||||
ELSE
|
||||
{
|
||||
Write-Host "Es wurden"$KonfigWerte.count"Zeilen aus der Konfigurationsdatei eingelesen."
|
||||
#Write-Host "Folgende Werte wurden eingelesen:"
|
||||
#Write-Host "$KonfigWerte"
|
||||
}
|
||||
|
||||
Set-Variable -Name KonfigWerte -Value $KonfigWerte -Scope script
|
||||
}
|
||||
|
||||
# Funktion um eine Textdatei (ASCII), komplett einzulesen.
|
||||
# Gibt immer nur einen Wert zurück!
|
||||
Function Func-ReadConfigValue
|
||||
{
|
||||
Param
|
||||
(
|
||||
[String]$KonfigBezeichner
|
||||
)
|
||||
|
||||
$Items = ($KonfigWerte.line | select-string -pattern "$KonfigBezeichner")
|
||||
IF ($Items -eq $NULL)
|
||||
{
|
||||
Write-Host "Der gesuchte Bezeichner ($KonfigBezeichner) konnte nicht gefunden werden!"
|
||||
Write-Host "Standardwert wird verwendet!"
|
||||
$KonfigBezeichner = (Get-Variable -Name $KonfigBezeichner -ValueOnly)
|
||||
return $KonfigBezeichner
|
||||
}
|
||||
|
||||
ELSEIF ($Items.GetType() -like "*Microsoft.PowerShell.Commands.MatchInfo*" -or $Funde.GetType() -like "*String*")
|
||||
{
|
||||
$Items = ($Items -split "=")
|
||||
$Items = @($Items)
|
||||
$Items = $Items[1]
|
||||
$Items = ($Items.TrimStart())
|
||||
$Items = ($Items.TrimEnd())
|
||||
return $Items
|
||||
}
|
||||
|
||||
ELSEIF ($Items -is [Array])
|
||||
{
|
||||
return $Items
|
||||
}
|
||||
}
|
||||
|
||||
Function Func-Dateien-zusammensuchen
|
||||
{
|
||||
Param
|
||||
(
|
||||
[String]$SuchPath,
|
||||
[Array]$SuchWhiteList,
|
||||
[Array]$SuchBlackList
|
||||
)
|
||||
|
||||
Set-Variable -Name SuchWhiteList -Value ($SuchWhiteList -Replace " ","")
|
||||
Set-Variable -Name SuchWhiteList -Value ($SuchWhiteList -Split ",")
|
||||
Set-Variable -Name SuchWhiteList -Value ($SuchWhiteList -Split ";")
|
||||
|
||||
Set-Variable -Name SuchBlackList -Value ($SuchBlackList -Replace " ","")
|
||||
Set-Variable -Name SuchBlackList -Value ($SuchBlackList -Split ",")
|
||||
Set-Variable -Name SuchBlackList -Value ($SuchBlackList -Split ";")
|
||||
|
||||
$Items = Get-ChildItem -Path "$SuchPath" -include $SuchWhiteList -exclude $SuchBlackList -Recurse
|
||||
IF ($Items -eq $NULL)
|
||||
{
|
||||
Func-Write-Logfile -LogEintrag "Could not find any File(s) in Path: $SuchPath (regard on White and Black Lists)."
|
||||
}
|
||||
ELSE
|
||||
{
|
||||
Func-Write-Logfile -LogEintrag "Could find some File(s) in Path: $SuchPath (regard on White and Black Lists) ..."
|
||||
FOREACH ($Item in $Items)
|
||||
{
|
||||
Func-Write-Logfile -LogEintrag "...one Found is: $Item"
|
||||
}
|
||||
return $Items
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Function Func-File-copy-or-move {
|
||||
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Function will copy or move File(s).
|
||||
.DESCRIPTION
|
||||
Function will copy or move File(s). If File already exists in target Path new File will get a Version ~2.
|
||||
.REQUIREMENT General
|
||||
PowerShell V2
|
||||
.REQUIREMENT Variables
|
||||
Datei, Datei1, DateiName, DateiEndung, DateiTest, DateiVersion,ZielPath, MoveorCopy, SourcePath
|
||||
.VERSION
|
||||
1.2 / 15.09.2015
|
||||
.EXAMPLE
|
||||
Func-Dateien-Versionieren -Datei "E:\Quellpfad\Test.txt" -ZielPath "E:\Zielpfad" -MoveorCopy move
|
||||
.EXAMPLE
|
||||
Func-Dateien-Versionieren -Datei "E:\Quellpfad\Test.txt" -ZielPath "E:\Zielpfad" -MoveorCopy copy
|
||||
.PARAMETER $Datei
|
||||
Give the full Path and Filename to one File.
|
||||
.PARAMETER $ZielPath
|
||||
Give the Target path you want to move or copy the specified File.
|
||||
.PARAMETER $MoveOrCopy
|
||||
Give this Parameter to determ a copy or a move Order.
|
||||
#>
|
||||
|
||||
Param
|
||||
(
|
||||
[String]$filename_and_path,
|
||||
[String]$file_targetpath,
|
||||
[String]$move_or_copy,
|
||||
[String]$newfilename,
|
||||
[String]$newfilename_prefix,
|
||||
[String]$newfilename_suffix
|
||||
)
|
||||
|
||||
|
||||
Set-Variable -Name SourcePath -Value (split-path "$filename_and_path")
|
||||
Set-Variable -Name Filename -Value (split-path "$filename_and_path" -Leaf)
|
||||
|
||||
IF (($MoveorCopy -ne 'move') -and ($MoveorCopy -ne 'copy')) {
|
||||
|
||||
Func-Write-Logfile -LogEintrag "ERROR: Wrong Function call."
|
||||
Func-Write-Logfile -LogEintrag "INFO: Parameter move_or_copy accepts only 'move' or 'copy'."
|
||||
Func-Write-Logfile -LogEintrag "Application will use the copy Order by default."
|
||||
Set-Variable -Name move_Or_copy -Value copy -Scope local
|
||||
}
|
||||
|
||||
IF (($VersionSeperator -eq $null) -or ($VersionSeperator -eq '')) {
|
||||
|
||||
Func-Write-Logfile -LogEintrag "ERROR: Wrong Function call."
|
||||
Func-Write-Logfile -LogEintrag "INFO: Variable VersionSeperator is not valid."
|
||||
Func-Write-Logfile -LogEintrag "Application was unplannd terminated."
|
||||
EXIT
|
||||
}
|
||||
|
||||
IF ($newfilename -gt "") {
|
||||
|
||||
Func-Write-Logfile -LogEintrag "New Filename will replace the old one."
|
||||
Set-Variable -Name Filename -Value $newfilename -Scope local
|
||||
}
|
||||
|
||||
IF ($newfilename_prefix -gt "") {
|
||||
|
||||
Func-Write-Logfile -LogEintrag "New prefix has been set for file."
|
||||
}
|
||||
|
||||
IF ($newfilename_suffix -gt "") {
|
||||
|
||||
Func-Write-Logfile -LogEintrag "New suffix has been set for file."
|
||||
}
|
||||
|
||||
#
|
||||
Set-Variable -Name Filename -Value ($newfilename_prefix + $filename + $newfilename_suffix)
|
||||
|
||||
# Does file already exist in the target directory?
|
||||
Set-Variable -Name Filetest -Value (Test-Path -PathType Leaf "$file_targetpath\$Filename")
|
||||
|
||||
IF ($Filetest -eq 'True') {
|
||||
|
||||
Func-Write-Logfile -LogEintrag ""
|
||||
Func-Write-Logfile -LogEintrag "The File already exists in the Target Directory, starting Version Check."
|
||||
|
||||
Set-Variable -Name $FileNameSplit -Value ($Filename -split "$VersionSeperator")
|
||||
Set-Variable -Name $FileVersion -Value $FileNameSplit[1]
|
||||
|
||||
# Has the new file already a Version tag?
|
||||
IF ($FileVersion -eq $NULL) {
|
||||
|
||||
Func-Write-Logfile -LogEintrag "Sourcefile includes no VersionSeperator."
|
||||
|
||||
Set-Variable -Name FileNameSplit -Value ($Filename -split "\.")
|
||||
Set-Variable -Name FileName -Value $FileNameSplit[0]
|
||||
Set-Variable -Name FileExtension -Value $FileNameSplit[1]
|
||||
|
||||
# To skip Version ~1.
|
||||
$FileVersion++
|
||||
}
|
||||
|
||||
ELSE {
|
||||
Func-Write-Logfile -LogEintrag "Sourcefile includes VersionSeperator."
|
||||
|
||||
Set-Variable -Name FileNameSplit -Value ($FileNameSplit -split "\.")
|
||||
Set-Variable -Name FileName -Value $FilenameSplit[0]
|
||||
Set-Variable -Name FileVersion -Value $FilenameSplit[1]
|
||||
Set-Variable -Name FileExtension -Value $FilenameSplit[2]
|
||||
|
||||
# To convert String Value to Integer.
|
||||
$DateiVersion = $DateiVersion -as [Int]
|
||||
}
|
||||
|
||||
DO {
|
||||
Write-Host "DEBUG Info: Count file version:" $FileVersion; $FileVersion++
|
||||
}
|
||||
|
||||
while
|
||||
(
|
||||
($Filetest = Test-Path -Path "$file_targetpath\$FileName$VersionSeperator$FileVersion.$FileExtension") -eq 'True'
|
||||
)
|
||||
|
||||
# code block for the copy or move process
|
||||
Try {
|
||||
|
||||
Set-Variable -Name FileTemp -Value (Copy-Item -Path "$filename_and_path" -Destination "$file_targetpath\$Timestamp3+"_"+$FileName" -PassThru -Force)
|
||||
Set-Variable -Name FileFinal -Value (Rename-Item -Path "FileTemp" -NewName "$FileName$VersionSeperator$FileVersion.$FileExtension")
|
||||
Func-Write-Logfile -LogEintrag "Command: $move_or_copy has been completed for file: $filename_and_path"
|
||||
Func-Write-Logfile -LogEintrag "File is ranamed to: $FileName$VersionSeperator$FileVersion.$FileExtension"
|
||||
Func-Write-Logfile -LogEintrag "and is transferd to: $file_targetpath"
|
||||
|
||||
Return "$FileFinal.Fullname"
|
||||
}
|
||||
|
||||
Catch {
|
||||
|
||||
Func-Write-Logfile -LogEintrag "Error at $move_or_copy command, processing file: $filename_and_path"
|
||||
Func-Write-Logfile -LogEintrag "Please check your privileges"
|
||||
exit
|
||||
}
|
||||
|
||||
IF ($move_or_copy -eq 'move') {
|
||||
|
||||
Func-Write-Logfile -LogEintrag "Moving action was choosen, will delete original file."
|
||||
|
||||
Try {
|
||||
|
||||
Remove-Item -Path "$filename_and_path" -Force
|
||||
}
|
||||
|
||||
Catch {
|
||||
|
||||
Func-Write-Logfile -LogEintrag "Error removing the original file."
|
||||
}
|
||||
}
|
||||
|
||||
ELSEIF ($MoveorCopy -eq 'copy') {
|
||||
|
||||
Func-Write-Logfile -LogEintrag "Coping action was choosen, will not delete original file."
|
||||
}
|
||||
}
|
||||
|
||||
ELSE {
|
||||
Set-Variable -Name FileTemp -Value (Copy-Item -Path "$filename_and_path" -Destination "$file_targetpath\$Timestamp3+"_"+$FileName" -PassThru -Force)
|
||||
Set-Variable -Name FileFinal -Value (Rename-Item -Path "FileTemp" -NewName "$FileName$VersionSeperator$FileVersion.$FileExtension")
|
||||
Func-Write-Logfile -LogEintrag "Command: $move_or_copy has been completed for file: $filename_and_path"
|
||||
Func-Write-Logfile -LogEintrag "File is ranamed to: $FileName.$FileExtension"
|
||||
Func-Write-Logfile -LogEintrag "and is transferd to: $file_targetpath"
|
||||
|
||||
Return "$FileFinal.Fullname"
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------
|
||||
####################################### Vorbereitende Arbeiten. ######################################
|
||||
#-----------------------------------------------------------------------------------------------------
|
||||
|
||||
# Lösche evtl. anzeigen.
|
||||
Clear-Host
|
||||
|
||||
# Konfigurationsdatei komplett einlesen.
|
||||
Func-ReadConfigFile -ConfigFile $ConfigFile
|
||||
|
||||
# Werte aus Konfigurationsdatei bereitstellen.
|
||||
$LogPathListe = (Func-ReadConfigValue -KonfigBezeichner LogPath)
|
||||
$LogKeepTime = (Func-ReadConfigValue -KonfigBezeichner LogKeepTime)
|
||||
$FileDelayAge = (Func-ReadConfigValue -KonfigBezeichner FileDelayAge)
|
||||
$VersionSeperator = (Func-ReadConfigValue -KonfigBezeichner VersionSeperator)
|
||||
|
||||
$Sourcepath = (Func-ReadConfigValue -KonfigBezeichner Sourcepath)
|
||||
$Destinationpath = (Func-ReadConfigValue -KonfigBezeichner Destinationpath)
|
||||
$FileWhiteList = (Func-ReadConfigValue -KonfigBezeichner FileWhiteList)
|
||||
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------
|
||||
####################################### Hauptprogramm starten. #######################################
|
||||
#-----------------------------------------------------------------------------------------------------
|
||||
Write-Host ""
|
||||
Func-Write-Logfile -LogEintrag "*******************************************************************************************"
|
||||
Func-Write-Logfile -LogEintrag "Program Startup: $ScriptName on $env:computername from Account $env:USERDOMAIN\$env:USERNAME."
|
||||
Func-Write-Logfile -LogEintrag "*******************************************************************************************"
|
||||
|
||||
Func-Path-Check -Path $Sourcepath
|
||||
Func-Path-Check -Path $Destinationpath
|
||||
|
||||
$Items = (Func-Dateien-zusammensuchen -SuchPath "$Sourcepath\*" -SuchWhiteList $FileWhiteList | where-object {$_.lastwritetime -lt (get-date).addminutes(-$FileDelayAge)} )
|
||||
|
||||
FOREACH ($Item in $Items)
|
||||
{
|
||||
Func-File-copy-or-move -filename_and_path "$Item" -file_targetpath $Destionationpath -move_or_copy move
|
||||
}
|
||||
|
||||
|
||||
#-----------------------------------------------------------------------------------------------------
|
||||
####################################### Abschließende Arbeiten. ######################################
|
||||
#-----------------------------------------------------------------------------------------------------
|
||||
|
||||
# Löschen alter Log-Dateien.
|
||||
Func-Write-Logfile -LogEintrag ""
|
||||
Func-Write-Logfile -LogEintrag "-------------------------------------------------------------------------------------------"
|
||||
Func-Write-Logfile -LogEintrag "Prüfe ob zu löschende Log-Dateien vorhanden sind."
|
||||
Func-Write-Logfile -LogEintrag "-------------------------------------------------------------------------------------------"
|
||||
IF ($LogKeepTime -gt 0)
|
||||
{
|
||||
Func-Write-Logfile -LogEintrag "Log Files should be removed which are older than $LogKeepTime Day(s)."
|
||||
$Items = (Func-Dateien-zusammensuchen -SuchPath "$LogPath\*" -SuchWhiteList *.log | where {$_.Name -like "*$ScriptName*" -and $_.lastwritetime -lt $((Get-Date).AddDays(-$LogKeepTime)) -and -not $_.psiscontainer})
|
||||
IF ($Items -eq $null)
|
||||
{
|
||||
Func-Write-Logfile -LogEintrag "Keine zu löschenden Log-Dateien vorhanden."
|
||||
}
|
||||
ELSE
|
||||
{
|
||||
Func-Write-Logfile -LogEintrag "Dateien gefunden, folgende Log-Dateien werden aufgund ihres alters gelöscht:"
|
||||
FOREACH ($Item in $Items)
|
||||
{
|
||||
Func-Write-Logfile -LogEintrag "Log-Datei: $Item wird entfernt."
|
||||
Remove-Item -Path $Item -Force -Verbose
|
||||
}
|
||||
}
|
||||
}
|
||||
ELSE
|
||||
{
|
||||
Func-Write-Logfile -LogEintrag "Sie haben in der Konfigurationsdatei angegeben, das Log Dateien nicht automatisch gelöscht werden sollen!"
|
||||
}
|
||||
|
||||
Func-Write-Logfile -LogEintrag ""
|
||||
Func-Write-Logfile -LogEintrag "*******************************************************************************************"
|
||||
Func-Write-Logfile -LogEintrag "Program Finish: $ScriptName on $env:computername from Account $env:USERDOMAIN\$env:USERNAME."
|
||||
Func-Write-Logfile -LogEintrag "*******************************************************************************************"
|
||||
|
||||
# Definierte Variablen wieder löschen, damit sie nicht im Arbeitsspeicher verbleiben.
|
||||
Remove-Variable -Name Skript* -Force
|
||||
Remove-Variable -name Konfig* -Force
|
||||
Remove-Variable -name ZeitStempel* -Force
|
||||
Remove-Variable -name Log* -Force
|
||||
Remove-Variable -name FileDelayAge -Force
|
||||
Remove-Variable -Name Path* -Force
|
||||
Remove-Variable -Name *Datei* -Force
|
||||
Remove-Variable -Name *Test* -Force
|
||||
|
||||
Remove-Variable -Name Item -Force
|
||||
Remove-Variable -Name Items -Force
|
||||
|
||||
$error.clear()
|
||||
6
test/Get-ACList.ps1
Normal file
6
test/Get-ACList.ps1
Normal file
@@ -0,0 +1,6 @@
|
||||
$acl = Get-Acl -Path D:\Skiptentwicklung
|
||||
|
||||
$acl.Access | ForEach-Object { $_.identityReference.value |
|
||||
Where-Object { $_ -eq '$env:USERNAME' } } | format-list
|
||||
|
||||
Write-Host $acl
|
||||
12
test/Get-Drives.ps1
Normal file
12
test/Get-Drives.ps1
Normal file
@@ -0,0 +1,12 @@
|
||||
#[System.IO.DriveInfo]::getdrives() | Where-Object {$_.DriveType -eq 'Fixed'} | Select Name
|
||||
|
||||
New-Variable -Name lw -Value $null
|
||||
|
||||
$lw = [System.IO.DriveInfo]::getdrives() | Where-Object {$_.DriveType -eq 'Fixed'} #| DESC #| Select-object Name # | Out-GridView
|
||||
|
||||
foreach ($dr in $lw)
|
||||
{
|
||||
Write-Host "Laufwerk: " $dr
|
||||
}
|
||||
|
||||
#Get-Command -CommandType cmdlet | Out-GridView
|
||||
18
test/Get-MailboxRights-from-Exchange-for-MailStore.ps1
Normal file
18
test/Get-MailboxRights-from-Exchange-for-MailStore.ps1
Normal file
@@ -0,0 +1,18 @@
|
||||
$UserCredential = Get-Credential
|
||||
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://mc2-vmx01-com01.mc2.local/PowerShell/ -Authentication Kerberos -Credential $UserCredential
|
||||
Import-PSSession $Session
|
||||
|
||||
$test = Get-Mailbox mkaufmann_hp | Get-MailboxPermission | ?{($_.IsInherited -eq $False) -and -not ($_.User -match “NT AUTHORITY”) -and -not ($_.User -match “NT-AUTORITÄT”)} | Select User,@{Name=”AccessRights”;Expression={$_.AccessRights}}
|
||||
$test = Get-Mailbox "hkeller" | Get-MailboxPermission | ?{($_.IsInherited -eq $False) -and -not ($_.User -match “NT AUTHORITY”) -and -not ($_.User -match “NT-AUTORITÄT”)} | Select User,@{Name=”AccessRights”;Expression={$_.AccessRights}}
|
||||
|
||||
#Get-Mailbox {Zu überprüfende Mailbox} | Get-MailboxPermission -User {AD-Benutzer}
|
||||
#Get-Mailbox -ResultSize Unlimited |Get-MailboxPermission -User {ADBenutzer} | Format-Table Identity,AccessRights, Deny
|
||||
|
||||
#$user =”Krishna.k” get-mailbox -identity $user| Get-MailboxPermission | ?{($_.IsInherited -eq $False) -and -not ($_.User -match “NT AUTHORITY”)}
|
||||
#Get-mailbox | Get-MailboxPermission | ?{($_.IsInherited -eq $False) -and -not ($_.User -match “NT AUTHORITY”)} |Select User,Identity,@{Name=”AccessRights”;Expression={$_.AccessRights}} | Export-csv C:\mailboxPermission.csv
|
||||
|
||||
#im MailStore:
|
||||
#users-list
|
||||
#SetUserPrivilegesOnFolder --userName=nvo --folder=mkaufmann --privileges=read
|
||||
|
||||
#Remove-PSSession $Session
|
||||
28
test/Get-OSVersion.ps1
Normal file
28
test/Get-OSVersion.ps1
Normal file
@@ -0,0 +1,28 @@
|
||||
IF (((Get-WmiObject -class Win32_OperatingSystem).version) -match 6.2) {
|
||||
|
||||
write-host "Windows Version: 8.0 was detected."
|
||||
Set-Variable -Name OSVersion -Value "Win8.0"
|
||||
|
||||
} #end if
|
||||
|
||||
ELSEIF (((Get-WmiObject -class Win32_OperatingSystem).version) -match 6.3) {
|
||||
|
||||
write-host "Windows Version: 8.1 was detected."
|
||||
Set-Variable -Name OSVersion -Value "Win8.1"
|
||||
|
||||
} #end elseif
|
||||
|
||||
ELSEIF (((Get-WmiObject -class Win32_OperatingSystem).version) -match 10.0) {
|
||||
|
||||
Write-Host "Windows Version: 10.0 was detected."
|
||||
Set-Variable -Name OSVersion -Value "Win10.0"
|
||||
|
||||
} #end elseif
|
||||
|
||||
ELSE {
|
||||
|
||||
Write-Host "Windows Version:" ((Get-WmiObject -class Win32_OperatingSystem).version) "was detected."
|
||||
Write-Host "ERROR: The Operation-System Version is unknown, cant proceed!"
|
||||
Write-Host "This Script works only with Windows 8, 8.1 and 10 Versions."
|
||||
|
||||
} #end else
|
||||
60
test/Get-SharePermissions.ps1
Normal file
60
test/Get-SharePermissions.ps1
Normal file
@@ -0,0 +1,60 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
This script will list all shares on a computer, and list all the share permissions for each share.
|
||||
|
||||
.DESCRIPTION
|
||||
The script will take a list all shares on a local or remote computer.
|
||||
|
||||
.PARAMETER Computer
|
||||
Specifies the computer or array of computers to process
|
||||
|
||||
.INPUTS
|
||||
Get-SharePermissions accepts pipeline of computer name(s)
|
||||
|
||||
.OUTPUTS
|
||||
Produces an array object for each share found.
|
||||
|
||||
.EXAMPLE
|
||||
C:\PS> .\Get-SharePermissions # Operates against local computer.
|
||||
|
||||
.EXAMPLE
|
||||
C:\PS> 'computerName' | .\Get-SharePermissions
|
||||
|
||||
.EXAMPLE
|
||||
C:\PS> Get-Content 'computerlist.txt' | .\Get-SharePermissions | Out-File 'SharePermissions.txt'
|
||||
|
||||
.EXAMPLE
|
||||
Get-Help .\Get-SharePermissions -Full
|
||||
#>
|
||||
|
||||
# Written by BigTeddy November 15, 2011
|
||||
# Last updated 9 September 2012
|
||||
# Ver. 2.0
|
||||
# Thanks to Michal Gajda for input with the ACE handling.
|
||||
|
||||
[cmdletbinding()]
|
||||
|
||||
param([Parameter(ValueFromPipeline=$True,
|
||||
ValueFromPipelineByPropertyName=$True)]$Computer = '.')
|
||||
|
||||
$shares = gwmi -Class win32_share -ComputerName $computer | select -ExpandProperty Name
|
||||
|
||||
foreach ($share in $shares) {
|
||||
$acl = $null
|
||||
Write-Host $share -ForegroundColor Green
|
||||
Write-Host $('-' * $share.Length) -ForegroundColor Green
|
||||
$objShareSec = Get-WMIObject -Class Win32_LogicalShareSecuritySetting -Filter "name='$Share'" -ComputerName $computer
|
||||
try {
|
||||
$SD = $objShareSec.GetSecurityDescriptor().Descriptor
|
||||
foreach($ace in $SD.DACL){
|
||||
$UserName = $ace.Trustee.Name
|
||||
If ($ace.Trustee.Domain -ne $Null) {$UserName = "$($ace.Trustee.Domain)\$UserName"}
|
||||
If ($ace.Trustee.Name -eq $Null) {$UserName = $ace.Trustee.SIDString }
|
||||
[Array]$ACL += New-Object Security.AccessControl.FileSystemAccessRule($UserName, $ace.AccessMask, $ace.AceType)
|
||||
} #end foreach ACE
|
||||
} # end try
|
||||
catch
|
||||
{ Write-Host "Unable to obtain permissions for $share" }
|
||||
$ACL
|
||||
Write-Host $('=' * 50)
|
||||
} # end foreach $share
|
||||
77
test/GetSearchDocuments.txt
Normal file
77
test/GetSearchDocuments.txt
Normal file
@@ -0,0 +1,77 @@
|
||||
Public Function GetSearchDocuments(ByVal wdfLocation As String)
|
||||
|
||||
|
||||
wdfLocation = wdfLocation.Replace("W:", "\\windream\objects")
|
||||
If System.IO.File.Exists(wdfLocation) Then
|
||||
|
||||
Try
|
||||
Dim ProfileName = wdfLocation.Substring(wdfLocation.LastIndexOf("\") + 1)
|
||||
Dim ProfilePath = wdfLocation.Substring(0, wdfLocation.Length - ProfileName.Length)
|
||||
|
||||
|
||||
|
||||
Me.oController.CheckSearchProfile(wdfLocation.ToLower)
|
||||
Dim suchTyp = Me.oController.SearchProfileTargetProgID
|
||||
Dim ExSettings As Object
|
||||
Dim oSearch As Object
|
||||
ExSettings = Me.oController.SearchProfileExSettings
|
||||
If ExSettings = 0 Then ExSettings = 7
|
||||
Dim srchQuick As WMOSRCHLib.WMQuickSearch = CreateObject("WMOSrch.WMQuickSearch")
|
||||
Dim srchIndex As WMOSRCHLib.WMIndexSearch = CreateObject("WMOSrch.WMIndexSearch")
|
||||
Dim srchObjectType As WMOSRCHLib.WMObjectTypeSearch = CreateObject("WMOSrch.WMObjectTypeSearch")
|
||||
|
||||
'' Der öffentliche Member CheckSearchProfile für den Typ IWMQuickSearch7 wurde nicht gefunden. [Microsoft.VisualBasic] => GetSearchDocuments()
|
||||
Select Case suchTyp.ToString.ToUpper
|
||||
Case "WMOSRCH.WMQUICKSEARCH"
|
||||
'srchQuick.WMSession = CreateObject("Windream.WMSession", Me.GetCurrentServer)
|
||||
|
||||
'Me.oConnect.LoginSession(oWMSession) 'srchQuick.WMSession)
|
||||
|
||||
srchQuick.ClearSearch()
|
||||
srchQuick.SearchProfilePath = ProfilePath
|
||||
srchQuick.LoadSearchProfile(ProfileName)
|
||||
|
||||
oSearch = srchQuick.GetSearch()
|
||||
|
||||
Case "WMOSRCH.WMINDEXSEARCH"
|
||||
srchIndex.WMSession = oWMSession 'CreateObject("Windream.WMSession", Me.GetCurrentServer)
|
||||
|
||||
'Me.oConnect.LoginSession(srchIndex.WMSession)
|
||||
|
||||
srchIndex.ClearSearch()
|
||||
srchIndex.SearchProfilePath = ProfilePath
|
||||
srchIndex.LoadSearchProfile(ProfileName)
|
||||
|
||||
oSearch = srchIndex.GetSearch()
|
||||
|
||||
Case "WMOSRCH.WMOBJECTTYPESEARCH"
|
||||
srchObjectType.WMSession = oWMSession 'CreateObject("Windream.WMSession", Me.GetCurrentServer)
|
||||
|
||||
'Me.oConnect.LoginSession(oWMSession) 'srchObjectType.WMSession)
|
||||
|
||||
srchObjectType.ClearSearch()
|
||||
srchObjectType.SearchProfilePath = ProfilePath
|
||||
srchObjectType.LoadSearchProfile(ProfileName)
|
||||
|
||||
oSearch = srchObjectType.GetSearch()
|
||||
|
||||
Case Else
|
||||
_Logger.Debug("KEIN GÜLTIGER WINDREAM-SUCHTYP")
|
||||
Return Nothing
|
||||
End Select
|
||||
Dim WMObjects As Object
|
||||
_Logger.Debug("Start der Suche: " & Now)
|
||||
' System.Threading.Thread.Sleep(200000)
|
||||
WMObjects = oSearch.Execute
|
||||
Return oSearch.execute
|
||||
Catch ex As Exception
|
||||
' bei einem Fehler einen Eintrag in der Logdatei machen
|
||||
_Logger.Error(ex)
|
||||
Return Nothing
|
||||
End Try
|
||||
|
||||
End If
|
||||
|
||||
Return Nothing
|
||||
|
||||
End Function
|
||||
46
test/Inputbox_angepasst.ps1
Normal file
46
test/Inputbox_angepasst.ps1
Normal file
@@ -0,0 +1,46 @@
|
||||
|
||||
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
|
||||
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
|
||||
|
||||
$objForm = New-Object System.Windows.Forms.Form
|
||||
$objForm.Text = "Data Entry Form"
|
||||
$objForm.Size = New-Object System.Drawing.Size(300,200)
|
||||
$objForm.StartPosition = "CenterScreen"
|
||||
|
||||
$objForm.KeyPreview = $True
|
||||
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Enter")
|
||||
{$x=$objTextBox.Text;$objForm.Close()}})
|
||||
$objForm.Add_KeyDown({if ($_.KeyCode -eq "Escape")
|
||||
{$objForm.Close()}})
|
||||
|
||||
$OKButton = New-Object System.Windows.Forms.Button
|
||||
$OKButton.Location = New-Object System.Drawing.Size(75,120)
|
||||
$OKButton.Size = New-Object System.Drawing.Size(75,23)
|
||||
$OKButton.Text = "OK"
|
||||
$OKButton.Add_Click({$x=$objTextBox.Text;$objForm.Close()})
|
||||
$objForm.Controls.Add($OKButton)
|
||||
|
||||
$CancelButton = New-Object System.Windows.Forms.Button
|
||||
$CancelButton.Location = New-Object System.Drawing.Size(150,120)
|
||||
$CancelButton.Size = New-Object System.Drawing.Size(75,23)
|
||||
$CancelButton.Text = "Cancel"
|
||||
$CancelButton.Add_Click({$objForm.Close()})
|
||||
$objForm.Controls.Add($CancelButton)
|
||||
|
||||
$objLabel = New-Object System.Windows.Forms.Label
|
||||
$objLabel.Location = New-Object System.Drawing.Size(10,20)
|
||||
$objLabel.Size = New-Object System.Drawing.Size(280,20)
|
||||
$objLabel.Text = "Please enter the information in the space below:"
|
||||
$objForm.Controls.Add($objLabel)
|
||||
|
||||
$objTextBox = New-Object System.Windows.Forms.TextBox
|
||||
$objTextBox.Location = New-Object System.Drawing.Size(10,40)
|
||||
$objTextBox.Size = New-Object System.Drawing.Size(260,20)
|
||||
$objForm.Controls.Add($objTextBox)
|
||||
|
||||
$objForm.Topmost = $True
|
||||
|
||||
$objForm.Add_Shown({$objForm.Activate()})
|
||||
[void] $objForm.ShowDialog()
|
||||
|
||||
$x
|
||||
28
test/Konfig_auslesen.ps1
Normal file
28
test/Konfig_auslesen.ps1
Normal file
@@ -0,0 +1,28 @@
|
||||
|
||||
LoadConfig Konfig_auslesen.xml
|
||||
|
||||
param($path = $(throw "You must specify a config file"))
|
||||
$global:appSettings = @{}
|
||||
$config = [xml](get-content $path)
|
||||
foreach ($addNode in $config.configuration.appsettings.add) {
|
||||
if ($addNode.Value.Contains(‘,’)) {
|
||||
# Array case
|
||||
$value = $addNode.Value.Split(‘,’)
|
||||
|
||||
for ($i = 0; $i -lt $value.length; $i++) {
|
||||
$value[$i] = $value[$i].Trim()
|
||||
}
|
||||
}
|
||||
else {
|
||||
# Scalar case
|
||||
$value = $addNode.Value
|
||||
}
|
||||
$global:appSettings[$addNode.Key] = $value
|
||||
}
|
||||
|
||||
|
||||
$appSettings["MaxScanDetailRows"]
|
||||
|
||||
$appSettings["datatypes"]
|
||||
|
||||
$appSettings["datatypes"][0]
|
||||
70
test/List-Software.ps1
Normal file
70
test/List-Software.ps1
Normal file
@@ -0,0 +1,70 @@
|
||||
######################################################################
|
||||
#
|
||||
# List-Software.ps1
|
||||
#
|
||||
# PowerShell-Script to list and classify installed software
|
||||
# Version: 1.0, 25.10.2009
|
||||
#
|
||||
# Input-csv-file: List-Software-Classifications.txt
|
||||
# Format: SoftwareClass,PartOfName
|
||||
# Examples: "FreeWare","Adobe Reader"
|
||||
# "Software","Microsoft Office Enterprise 2007"
|
||||
# "Driver","SigmaTel Audio"
|
||||
# "MS-Components","Microsoft .NET"
|
||||
#
|
||||
# (c) 2009, Andreas Lauer IT Service, www.alits.de
|
||||
# Free Usage for www.powershell-ag.de
|
||||
#
|
||||
######################################################################
|
||||
|
||||
#-----------------------------------------------------------------
|
||||
# Functions
|
||||
#-----------------------------------------------------------------
|
||||
|
||||
Function Get-SoftwareList {
|
||||
#Get All Users Software-List
|
||||
$Keys = Get-ChildItem "HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall"
|
||||
$SoftwareMachine = @($Keys | foreach-object {Get-ItemProperty $_.PsPath})
|
||||
Write-Host "Count of Software for All Users:" $SoftwareMachine.Count
|
||||
|
||||
#Get Current User Software-List
|
||||
$Keys = Get-ChildItem "HKCU:\Software\Microsoft\Windows\CurrentVersion\Uninstall"
|
||||
$SoftwareUser = @($Keys | foreach-object {Get-ItemProperty $_.PsPath})
|
||||
Write-Host "Count of Software for Current User:" $SoftwareUser.Count
|
||||
|
||||
#Add both Software-Lists
|
||||
$SoftwareAll = $SoftwareMachine + $SoftwareUser
|
||||
Write-Host "Total Count of Software:" $SoftwareAll.Count
|
||||
|
||||
#Drop SystemComponents and Software with empty Name
|
||||
$Software = ($SoftwareAll | Where-Object {(($_.DisplayName+" ") -ne " ") -and ($_.SystemComponent -ne 1)}| Sort-Object DisplayName)
|
||||
Write-Host "Count of Installed Software:" $Software.Count
|
||||
|
||||
#Import csv-File with Software-Classifications - to be edited
|
||||
$ClassificationListFile = "List-Software-Classifications.txt"
|
||||
$ClassificationList = Import-Csv $ClassificationListFile
|
||||
|
||||
#Classify Software, use Property "PsPath" for Classification-Text
|
||||
foreach ($Item in $Software) {
|
||||
$Item.PsPath = "**unknown**"
|
||||
foreach ($Class in $ClassificationList) {
|
||||
if (($Item.DisplayName+" ").Contains($Class.PartOfName)) {
|
||||
$Item.PsPath = $Class.SoftwareClass
|
||||
Break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#Output
|
||||
$Software | ft PsPath, DisplayName, DisplayVersion, Publisher, InstallDate -AutoSize | Out-File SoftwareList.txt
|
||||
$Software | select-object PsPath, DisplayName, DisplayVersion, Publisher, InstallDate | Export-Csv SoftwareList.csv -NoTypeInformation
|
||||
}
|
||||
|
||||
#-----------------------------------------------------------------
|
||||
# Main program
|
||||
#-----------------------------------------------------------------
|
||||
|
||||
Clear-Host
|
||||
Write-Host "Starting ..."
|
||||
Get-SoftwareList
|
||||
Write-Host "... Done."
|
||||
24
test/Lockyscript_v4.ps1
Normal file
24
test/Lockyscript_v4.ps1
Normal file
@@ -0,0 +1,24 @@
|
||||
clear
|
||||
Push-Location $(Split-Path $Script:MyInvocation.MyCommand.Path)
|
||||
$datei = Get-content .\20160829_Ransomware.txt
|
||||
|
||||
Remove-FsrmFileGroup -Name "Locky*"
|
||||
Remove-FsrmFileScreen -Path E:\Test
|
||||
|
||||
$var = $datei.split(",")
|
||||
for($i=0; $i -lt $var.Length; $i=$i+20){
|
||||
|
||||
$j = $i + 19
|
||||
Write-Host "$i..$j"
|
||||
$var.replace("""", $null)[$i..$j] -join ","
|
||||
|
||||
New-FsrmFileGroup -Name "Locky$i" -IncludePattern $var[$i..$j]
|
||||
}
|
||||
|
||||
$array = @()
|
||||
for($i=0; $i -lt $var.length; $i=$i+20){
|
||||
$array += 'Locky' + $i
|
||||
}
|
||||
$Notification = New-FsrmAction -Type Email -MailTo Test@test.de -Subject “FEHLER!!!!!!” -Body “[Violated File Group] located at: [Source File Path]. It was created by User: [Source Io Owner]. Ressource-Manager should block future accessing.” -RunLimitInterval 120
|
||||
$Notification1 = New-FsrmAction -Type Event -EventType Warning -Body "Alert text here" -RunlimitInterval 30
|
||||
New-FsrmFileScreen -Path E:\Test -IncludeGroup $array -Notification $Notification,$Notification1
|
||||
702
test/Make-PS1ExeWrapper.ps1
Normal file
702
test/Make-PS1ExeWrapper.ps1
Normal file
@@ -0,0 +1,702 @@
|
||||
#requires -version 2.0
|
||||
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Creates an EXE wrapper from a PowerShell script by compressing the script and embedding into
|
||||
a newly generated assembly.
|
||||
.DESCRIPTION
|
||||
Creates an EXE wrapper from a PowerShell script by compressing the script and embedding into
|
||||
a newly generated assembly.
|
||||
.PARAMETER Path
|
||||
The path to the .
|
||||
.PARAMETER LiteralPath
|
||||
Specifies a path to one or more locations. Unlike Path, the value of LiteralPath is used exactly as it
|
||||
is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose
|
||||
it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any
|
||||
characters as escape sequences.
|
||||
.PARAMETER OutputAssembly
|
||||
The name (including path) of the EXE to generate.
|
||||
.PARAMETER IconPath
|
||||
The path to an optional icon to be embedded as the application icon for the EXE.
|
||||
.PARAMETER STA
|
||||
By default the console app created uses MTAThread. If this switch is specified, then it uses STAThread.
|
||||
.EXAMPLE
|
||||
C:\PS> .\Make-PS1ExeWrapper.ps1 .\MyScript.ps1 .\MyScript.exe .\app.ico -Sta
|
||||
This creates an console application called MyScript.exe that internally hosts the PowerShell
|
||||
engine and runs the script specified by MyScript.ps1. Optionally the file app.ico is
|
||||
embedded into the EXE as the application's icon.
|
||||
.NOTES
|
||||
Author: Keith Hill
|
||||
Date: Aug 7, 2010
|
||||
Issues: This implementation is more of a feasibility test and isn't fully functional. It doesn't
|
||||
support an number of PSHostUserInterface members as well as a number of PSHostRawUserInterface
|
||||
members. This approach also suffers from the same problem of running script "interactively"
|
||||
and not loading it from a file. That is, the entire script output is run through Out-Default
|
||||
and PowerShell gets confused. It formats the first types it sees correctly but after that the
|
||||
formatting is off. To correct this, you have to append | Out-Default where you script outputs
|
||||
to the host without using a Write-* cmdlet e.g.:
|
||||
|
||||
MyScript.ps1:
|
||||
-------------------------------
|
||||
Get-Process svchost
|
||||
Get-Date | Out-Default
|
||||
Dir C:\ | Out-Default
|
||||
Dir c:\idontexist | Out-Default
|
||||
$DebugPreference = 'Continue'
|
||||
$VerbosePreference = 'Continue'
|
||||
Write-Host "host"
|
||||
Write-Warning "warning"
|
||||
Write-Verbose "verbose"
|
||||
Write-Debug "debug"
|
||||
Write-Error "error"
|
||||
#>
|
||||
[CmdletBinding(DefaultParameterSetName="Path")]
|
||||
param(
|
||||
[Parameter(Mandatory=$true, Position=0, ParameterSetName="Path",
|
||||
ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true,
|
||||
HelpMessage="Path to bitmap file")]
|
||||
[ValidateNotNullOrEmpty()]
|
||||
[string[]]
|
||||
$Path,
|
||||
|
||||
[Alias("PSPath")]
|
||||
[Parameter(Mandatory=$true, Position=0, ParameterSetName="LiteralPath",
|
||||
ValueFromPipelineByPropertyName=$true,
|
||||
HelpMessage="Path to bitmap file")]
|
||||
[ValidateNotNullOrEmpty()]
|
||||
[string[]]
|
||||
$LiteralPath,
|
||||
|
||||
[Parameter(Mandatory = $true, Position = 1)]
|
||||
[string]
|
||||
$OutputAssembly,
|
||||
|
||||
[Parameter(Position = 2)]
|
||||
[string]
|
||||
$IconPath,
|
||||
|
||||
[Parameter()]
|
||||
[switch]
|
||||
$STA
|
||||
)
|
||||
|
||||
Begin {
|
||||
Set-StrictMode -Version latest
|
||||
|
||||
$MainAttribute = ''
|
||||
$ApartmentState = 'System.Threading.ApartmentState.MTA'
|
||||
if ($Sta)
|
||||
{
|
||||
$MainAttribute = '[STAThread]'
|
||||
$ApartmentState = 'System.Threading.ApartmentState.STA'
|
||||
}
|
||||
|
||||
$src = @'
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.IO.Compression;
|
||||
using System.Management.Automation;
|
||||
using System.Management.Automation.Host;
|
||||
using System.Management.Automation.Runspaces;
|
||||
using System.Reflection;
|
||||
using System.Security;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
|
||||
[assembly: AssemblyTitle("")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("")]
|
||||
//[assembly: AssemblyCopyright("Copyright © 2013")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")
|
||||
|
||||
namespace PS1ToExeTemplate
|
||||
{
|
||||
class Program
|
||||
{
|
||||
private static object _powerShellLock = new object();
|
||||
private static readonly Host _host = new Host();
|
||||
private static PowerShell _powerShellEngine;
|
||||
|
||||
'@ + @"
|
||||
$MainAttribute
|
||||
|
||||
"@ + @'
|
||||
static void Main(string[] args)
|
||||
{
|
||||
Console.CancelKeyPress += Console_CancelKeyPress;
|
||||
Console.TreatControlCAsInput = false;
|
||||
|
||||
string script = GetScript();
|
||||
RunScript(script, args, null);
|
||||
}
|
||||
|
||||
private static string GetScript()
|
||||
{
|
||||
string script = String.Empty;
|
||||
|
||||
Assembly assembly = Assembly.GetExecutingAssembly();
|
||||
using (Stream stream = assembly.GetManifestResourceStream("Resources.Script.ps1.gz"))
|
||||
{
|
||||
var gZipStream = new GZipStream(stream, CompressionMode.Decompress, true);
|
||||
var streamReader = new StreamReader(gZipStream);
|
||||
script = streamReader.ReadToEnd();
|
||||
}
|
||||
|
||||
return script;
|
||||
}
|
||||
|
||||
private static void RunScript(string script, string[] args, object input)
|
||||
{
|
||||
lock (_powerShellLock)
|
||||
{
|
||||
_powerShellEngine = PowerShell.Create();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
_powerShellEngine.Runspace = RunspaceFactory.CreateRunspace(_host);
|
||||
_powerShellEngine.Runspace.ApartmentState =
|
||||
'@ + @"
|
||||
$ApartmentState;
|
||||
|
||||
"@ + @'
|
||||
_powerShellEngine.Runspace.Open();
|
||||
_powerShellEngine.AddScript(script);
|
||||
_powerShellEngine.AddCommand("Out-Default");
|
||||
_powerShellEngine.Commands.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);
|
||||
|
||||
if (input != null)
|
||||
{
|
||||
_powerShellEngine.Invoke(new[] { input });
|
||||
}
|
||||
else
|
||||
{
|
||||
_powerShellEngine.Invoke();
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_powerShellLock)
|
||||
{
|
||||
_powerShellEngine.Dispose();
|
||||
_powerShellEngine = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
|
||||
{
|
||||
try
|
||||
{
|
||||
lock (_powerShellLock)
|
||||
{
|
||||
if (_powerShellEngine != null && _powerShellEngine.InvocationStateInfo.State == PSInvocationState.Running)
|
||||
{
|
||||
_powerShellEngine.Stop();
|
||||
}
|
||||
}
|
||||
e.Cancel = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_host.UI.WriteErrorLine(ex.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class Host : PSHost
|
||||
{
|
||||
private PSHostUserInterface _psHostUserInterface = new HostUserInterface();
|
||||
|
||||
public override void SetShouldExit(int exitCode)
|
||||
{
|
||||
Environment.Exit(exitCode);
|
||||
}
|
||||
|
||||
public override void EnterNestedPrompt()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override void ExitNestedPrompt()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override void NotifyBeginApplication()
|
||||
{
|
||||
}
|
||||
|
||||
public override void NotifyEndApplication()
|
||||
{
|
||||
}
|
||||
|
||||
public override string Name
|
||||
{
|
||||
get { return "PSCX-PS1ToExeHost"; }
|
||||
}
|
||||
|
||||
public override Version Version
|
||||
{
|
||||
get { return new Version(1, 0); }
|
||||
}
|
||||
|
||||
public override Guid InstanceId
|
||||
{
|
||||
get { return new Guid("E4673B42-84B6-4C43-9589-95FAB8E00EB2"); }
|
||||
}
|
||||
|
||||
public override PSHostUserInterface UI
|
||||
{
|
||||
get { return _psHostUserInterface; }
|
||||
}
|
||||
|
||||
public override CultureInfo CurrentCulture
|
||||
{
|
||||
get { return Thread.CurrentThread.CurrentCulture; }
|
||||
}
|
||||
|
||||
public override CultureInfo CurrentUICulture
|
||||
{
|
||||
get { return Thread.CurrentThread.CurrentUICulture; }
|
||||
}
|
||||
}
|
||||
|
||||
class HostUserInterface : PSHostUserInterface, IHostUISupportsMultipleChoiceSelection
|
||||
{
|
||||
private PSHostRawUserInterface _psRawUserInterface = new HostRawUserInterface();
|
||||
|
||||
public override PSHostRawUserInterface RawUI
|
||||
{
|
||||
get { return _psRawUserInterface; }
|
||||
}
|
||||
|
||||
public override string ReadLine()
|
||||
{
|
||||
return Console.ReadLine();
|
||||
}
|
||||
|
||||
public override SecureString ReadLineAsSecureString()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override void Write(string value)
|
||||
{
|
||||
string output = value ?? "null";
|
||||
Console.Write(output);
|
||||
}
|
||||
|
||||
public override void Write(ConsoleColor foregroundColor, ConsoleColor backgroundColor, string value)
|
||||
{
|
||||
string output = value ?? "null";
|
||||
var origFgColor = Console.ForegroundColor;
|
||||
var origBgColor = Console.BackgroundColor;
|
||||
Console.ForegroundColor = foregroundColor;
|
||||
Console.BackgroundColor = backgroundColor;
|
||||
Console.Write(output);
|
||||
Console.ForegroundColor = origFgColor;
|
||||
Console.BackgroundColor = origBgColor;
|
||||
}
|
||||
|
||||
public override void WriteLine(string value)
|
||||
{
|
||||
string output = value ?? "null";
|
||||
Console.WriteLine(output);
|
||||
}
|
||||
|
||||
public override void WriteErrorLine(string value)
|
||||
{
|
||||
string output = value ?? "null";
|
||||
var origFgColor = Console.ForegroundColor;
|
||||
Console.ForegroundColor = ConsoleColor.Red;
|
||||
Console.WriteLine(output);
|
||||
Console.ForegroundColor = origFgColor;
|
||||
}
|
||||
|
||||
public override void WriteDebugLine(string message)
|
||||
{
|
||||
WriteYellowAnnotatedLine(message, "DEBUG");
|
||||
}
|
||||
|
||||
public override void WriteVerboseLine(string message)
|
||||
{
|
||||
WriteYellowAnnotatedLine(message, "VERBOSE");
|
||||
}
|
||||
|
||||
public override void WriteWarningLine(string message)
|
||||
{
|
||||
WriteYellowAnnotatedLine(message, "WARNING");
|
||||
}
|
||||
|
||||
private void WriteYellowAnnotatedLine(string message, string annotation)
|
||||
{
|
||||
string output = message ?? "null";
|
||||
var origFgColor = Console.ForegroundColor;
|
||||
var origBgColor = Console.BackgroundColor;
|
||||
Console.ForegroundColor = ConsoleColor.Yellow;
|
||||
Console.BackgroundColor = ConsoleColor.Black;
|
||||
WriteLine(String.Format(CultureInfo.CurrentCulture, "{0}: {1}", annotation, output));
|
||||
Console.ForegroundColor = origFgColor;
|
||||
Console.BackgroundColor = origBgColor;
|
||||
}
|
||||
|
||||
public override void WriteProgress(long sourceId, ProgressRecord record)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override Dictionary<string, PSObject> Prompt(string caption, string message, Collection<FieldDescription> descriptions)
|
||||
{
|
||||
if (String.IsNullOrEmpty(caption) && String.IsNullOrEmpty(message) && descriptions.Count > 0)
|
||||
{
|
||||
Console.Write(descriptions[0].Name + ": ");
|
||||
}
|
||||
else
|
||||
{
|
||||
this.Write(ConsoleColor.DarkCyan, ConsoleColor.Black, caption + "\n" + message + " ");
|
||||
}
|
||||
var results = new Dictionary<string, PSObject>();
|
||||
foreach (FieldDescription fd in descriptions)
|
||||
{
|
||||
string[] label = GetHotkeyAndLabel(fd.Label);
|
||||
this.WriteLine(label[1]);
|
||||
string userData = Console.ReadLine();
|
||||
if (userData == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
results[fd.Name] = PSObject.AsPSObject(userData);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override PSCredential PromptForCredential(string caption, string message, string userName, string targetName, PSCredentialTypes allowedCredentialTypes, PSCredentialUIOptions options)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override int PromptForChoice(string caption, string message, Collection<ChoiceDescription> choices, int defaultChoice)
|
||||
{
|
||||
// Write the caption and message strings in Blue.
|
||||
this.WriteLine(ConsoleColor.Blue, ConsoleColor.Black, caption + "\n" + message + "\n");
|
||||
|
||||
// Convert the choice collection into something that is
|
||||
// easier to work with. See the BuildHotkeysAndPlainLabels
|
||||
// method for details.
|
||||
string[,] promptData = BuildHotkeysAndPlainLabels(choices);
|
||||
|
||||
// Format the overall choice prompt string to display.
|
||||
var sb = new StringBuilder();
|
||||
for (int element = 0; element < choices.Count; element++)
|
||||
{
|
||||
sb.Append(String.Format(CultureInfo.CurrentCulture, "|{0}> {1} ", promptData[0, element], promptData[1, element]));
|
||||
}
|
||||
|
||||
sb.Append(String.Format(CultureInfo.CurrentCulture, "[Default is ({0}]", promptData[0, defaultChoice]));
|
||||
|
||||
// Read prompts until a match is made, the default is
|
||||
// chosen, or the loop is interrupted with ctrl-C.
|
||||
while (true)
|
||||
{
|
||||
this.WriteLine(sb.ToString());
|
||||
string data = Console.ReadLine().Trim().ToUpper(CultureInfo.CurrentCulture);
|
||||
|
||||
// If the choice string was empty, use the default selection.
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return defaultChoice;
|
||||
}
|
||||
|
||||
// See if the selection matched and return the
|
||||
// corresponding index if it did.
|
||||
for (int i = 0; i < choices.Count; i++)
|
||||
{
|
||||
if (promptData[0, i] == data)
|
||||
{
|
||||
return i;
|
||||
}
|
||||
}
|
||||
|
||||
this.WriteErrorLine("Invalid choice: " + data);
|
||||
}
|
||||
}
|
||||
|
||||
#region IHostUISupportsMultipleChoiceSelection Members
|
||||
|
||||
public Collection<int> PromptForChoice(string caption, string message, Collection<ChoiceDescription> choices, IEnumerable<int> defaultChoices)
|
||||
{
|
||||
this.WriteLine(ConsoleColor.Blue, ConsoleColor.Black, caption + "\n" + message + "\n");
|
||||
|
||||
string[,] promptData = BuildHotkeysAndPlainLabels(choices);
|
||||
|
||||
var sb = new StringBuilder();
|
||||
for (int element = 0; element < choices.Count; element++)
|
||||
{
|
||||
sb.Append(String.Format(CultureInfo.CurrentCulture, "|{0}> {1} ", promptData[0, element], promptData[1, element]));
|
||||
}
|
||||
|
||||
var defaultResults = new Collection<int>();
|
||||
if (defaultChoices != null)
|
||||
{
|
||||
int countDefaults = 0;
|
||||
foreach (int defaultChoice in defaultChoices)
|
||||
{
|
||||
++countDefaults;
|
||||
defaultResults.Add(defaultChoice);
|
||||
}
|
||||
|
||||
if (countDefaults != 0)
|
||||
{
|
||||
sb.Append(countDefaults == 1 ? "[Default choice is " : "[Default choices are ");
|
||||
foreach (int defaultChoice in defaultChoices)
|
||||
{
|
||||
sb.AppendFormat(CultureInfo.CurrentCulture, "\"{0}\",", promptData[0, defaultChoice]);
|
||||
}
|
||||
sb.Remove(sb.Length - 1, 1);
|
||||
sb.Append("]");
|
||||
}
|
||||
}
|
||||
|
||||
this.WriteLine(ConsoleColor.Cyan, ConsoleColor.Black, sb.ToString());
|
||||
|
||||
var results = new Collection<int>();
|
||||
while (true)
|
||||
{
|
||||
ReadNext:
|
||||
string prompt = string.Format(CultureInfo.CurrentCulture, "Choice[{0}]:", results.Count);
|
||||
this.Write(ConsoleColor.Cyan, ConsoleColor.Black, prompt);
|
||||
string data = Console.ReadLine().Trim().ToUpper(CultureInfo.CurrentCulture);
|
||||
|
||||
if (data.Length == 0)
|
||||
{
|
||||
return (results.Count == 0) ? defaultResults : results;
|
||||
}
|
||||
|
||||
for (int i = 0; i < choices.Count; i++)
|
||||
{
|
||||
if (promptData[0, i] == data)
|
||||
{
|
||||
results.Add(i);
|
||||
goto ReadNext;
|
||||
}
|
||||
}
|
||||
|
||||
this.WriteErrorLine("Invalid choice: " + data);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private static string[,] BuildHotkeysAndPlainLabels(Collection<ChoiceDescription> choices)
|
||||
{
|
||||
// Allocate the result array
|
||||
string[,] hotkeysAndPlainLabels = new string[2, choices.Count];
|
||||
|
||||
for (int i = 0; i < choices.Count; ++i)
|
||||
{
|
||||
string[] hotkeyAndLabel = GetHotkeyAndLabel(choices[i].Label);
|
||||
hotkeysAndPlainLabels[0, i] = hotkeyAndLabel[0];
|
||||
hotkeysAndPlainLabels[1, i] = hotkeyAndLabel[1];
|
||||
}
|
||||
|
||||
return hotkeysAndPlainLabels;
|
||||
}
|
||||
|
||||
private static string[] GetHotkeyAndLabel(string input)
|
||||
{
|
||||
string[] result = new string[] { String.Empty, String.Empty };
|
||||
string[] fragments = input.Split('&');
|
||||
if (fragments.Length == 2)
|
||||
{
|
||||
if (fragments[1].Length > 0)
|
||||
{
|
||||
result[0] = fragments[1][0].ToString().
|
||||
ToUpper(CultureInfo.CurrentCulture);
|
||||
}
|
||||
|
||||
result[1] = (fragments[0] + fragments[1]).Trim();
|
||||
}
|
||||
else
|
||||
{
|
||||
result[1] = input;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
class HostRawUserInterface : PSHostRawUserInterface
|
||||
{
|
||||
public override KeyInfo ReadKey(ReadKeyOptions options)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override void FlushInputBuffer()
|
||||
{
|
||||
}
|
||||
|
||||
public override void SetBufferContents(Coordinates origin, BufferCell[,] contents)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override void SetBufferContents(Rectangle rectangle, BufferCell fill)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override BufferCell[,] GetBufferContents(Rectangle rectangle)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override void ScrollBufferContents(Rectangle source, Coordinates destination, Rectangle clip, BufferCell fill)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override ConsoleColor ForegroundColor
|
||||
{
|
||||
get { return Console.ForegroundColor; }
|
||||
set { Console.ForegroundColor = value; }
|
||||
}
|
||||
|
||||
public override ConsoleColor BackgroundColor
|
||||
{
|
||||
get { return Console.BackgroundColor; }
|
||||
set { Console.BackgroundColor = value; }
|
||||
}
|
||||
|
||||
public override Coordinates CursorPosition
|
||||
{
|
||||
get { return new Coordinates(Console.CursorLeft, Console.CursorTop); }
|
||||
set { Console.SetCursorPosition(value.X, value.Y); }
|
||||
}
|
||||
|
||||
public override Coordinates WindowPosition
|
||||
{
|
||||
get { return new Coordinates(Console.WindowLeft, Console.WindowTop); }
|
||||
set { Console.SetWindowPosition(value.X, value.Y); }
|
||||
}
|
||||
|
||||
public override int CursorSize
|
||||
{
|
||||
get { return Console.CursorSize; }
|
||||
set { Console.CursorSize = value; }
|
||||
}
|
||||
|
||||
public override Size BufferSize
|
||||
{
|
||||
get { return new Size(Console.BufferWidth, Console.BufferHeight); }
|
||||
set { Console.SetBufferSize(value.Width, value.Height); }
|
||||
}
|
||||
|
||||
public override Size WindowSize
|
||||
{
|
||||
get { return new Size(Console.WindowWidth, Console.WindowHeight); }
|
||||
set { Console.SetWindowSize(value.Width, value.Height); }
|
||||
}
|
||||
|
||||
public override Size MaxWindowSize
|
||||
{
|
||||
get { return new Size(Console.LargestWindowWidth, Console.LargestWindowHeight); }
|
||||
}
|
||||
|
||||
public override Size MaxPhysicalWindowSize
|
||||
{
|
||||
get { return new Size(Console.LargestWindowWidth, Console.LargestWindowHeight); }
|
||||
}
|
||||
|
||||
public override bool KeyAvailable
|
||||
{
|
||||
get { return Console.KeyAvailable; }
|
||||
}
|
||||
|
||||
public override string WindowTitle
|
||||
{
|
||||
get { return Console.Title; }
|
||||
set { Console.Title = value; }
|
||||
}
|
||||
}
|
||||
}
|
||||
'@
|
||||
}
|
||||
|
||||
Process {
|
||||
if ($psCmdlet.ParameterSetName -eq "Path")
|
||||
{
|
||||
# In the -Path (non-literal) case we may need to resolve a wildcarded path
|
||||
$resolvedPaths = @($Path | Resolve-Path | Convert-Path)
|
||||
}
|
||||
else
|
||||
{
|
||||
# Must be -LiteralPath
|
||||
$resolvedPaths = @($LiteralPath | Convert-Path)
|
||||
}
|
||||
|
||||
foreach ($rpath in $resolvedPaths)
|
||||
{
|
||||
Write-Verbose "Processing $rpath"
|
||||
|
||||
$gzItem = Get-ChildItem $rpath | Write-GZip -Quiet
|
||||
$resourcePath = "$($gzItem.Directory)\Resources.Script.ps1.gz"
|
||||
if (Test-Path $resourcePath) { Remove-Item $resourcePath }
|
||||
Rename-Item $gzItem $resourcePath
|
||||
|
||||
# Configure the compiler parameters
|
||||
$referenceAssemblies = 'System.dll',([psobject].Assembly.Location)
|
||||
$outputPath = $OutputAssembly
|
||||
if (![IO.Path]::IsPathRooted($outputPath))
|
||||
{
|
||||
$outputPath = [io.path]::GetFullPath((Join-Path $pwd $outputPath))
|
||||
}
|
||||
if ($rpath -eq $outputPath)
|
||||
{
|
||||
throw 'Oops, you don''t really want to overwrite your script with an EXE.'
|
||||
}
|
||||
|
||||
$cp = new-object System.CodeDom.Compiler.CompilerParameters $referenceAssemblies,$outputPath,$true
|
||||
$cp.TempFiles = new-object System.CodeDom.Compiler.TempFileCollection ([IO.Path]::GetTempPath())
|
||||
$cp.GenerateExecutable = $true
|
||||
$cp.GenerateInMemory = $false
|
||||
$cp.IncludeDebugInformation = $true
|
||||
if ($IconPath)
|
||||
{
|
||||
$rIconPath = Resolve-Path $IconPath
|
||||
$cp.CompilerOptions = " /win32icon:$rIconPath"
|
||||
}
|
||||
[void]$cp.EmbeddedResources.Add($resourcePath)
|
||||
|
||||
# Create the C# codedom compiler
|
||||
$dict = new-object 'System.Collections.Generic.Dictionary[string,string]'
|
||||
$dict.Add('CompilerVersion','v3.5')
|
||||
$provider = new-object Microsoft.CSharp.CSharpCodeProvider $dict
|
||||
|
||||
# Compile the source and report errors
|
||||
$results = $provider.CompileAssemblyFromSource($cp, $src)
|
||||
if ($results.Errors.Count)
|
||||
{
|
||||
$errorLines = ""
|
||||
foreach ($error in $results.Errors)
|
||||
{
|
||||
$errorLines += "`n`t" + $error.Line + ":`t" + $error.ErrorText
|
||||
}
|
||||
Write-Error $errorLines
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
test/Messageboxen mit Eingabeaufforderung und Icons.ps1
Normal file
BIN
test/Messageboxen mit Eingabeaufforderung und Icons.ps1
Normal file
Binary file not shown.
BIN
test/Messageboxen mit Eingabeaufforderung und Icons2.ps1
Normal file
BIN
test/Messageboxen mit Eingabeaufforderung und Icons2.ps1
Normal file
Binary file not shown.
60
test/Move-Files2CreationDateFolders.ps1
Normal file
60
test/Move-Files2CreationDateFolders.ps1
Normal file
@@ -0,0 +1,60 @@
|
||||
#MK / 15.01.2021
|
||||
cls
|
||||
|
||||
[String]$Sourcepath = "E:\KammM\PS2EXE-GUI - Kopie"
|
||||
[String]$Targetpath = "E:\KammM"
|
||||
|
||||
[Array]$Items = $NULL
|
||||
[String]$ItemFinalPath = $NULL
|
||||
[String]$ItemLastWriteTime = $NULL
|
||||
[String]$DateSeperator = "/"
|
||||
[String]$ItemYear = $NULL
|
||||
[String]$ItemMonth = $NULL
|
||||
[String]$ItemDay = $NULL
|
||||
|
||||
$Items = gci $Sourcepath -Filter *.* #-Force -Recurse
|
||||
|
||||
FOREACH ($Item in $Items) {
|
||||
|
||||
Write-Host "-------------------------------------------"
|
||||
Write-Host "Processing File: $($Item.fullname)"
|
||||
|
||||
Write-Host "Attributes: $($Item.CreationTime)"
|
||||
Write-Host "Attributes: $($Item.Attributes)"
|
||||
Write-Host "Attributes: $($Item.LastAccessTime)"
|
||||
Write-Host "Attributes: $($Item.LastWriteTime)"
|
||||
|
||||
$ItemLastWriteTime = $($Item.LastWriteTime)
|
||||
|
||||
$ItemLastWriteTime = $ItemLastWriteTime.Split(" ")[0]
|
||||
$ItemYear = $ItemLastWriteTime.Split($DateSeperator)[2]
|
||||
$ItemMonth = $ItemLastWriteTime.Split($DateSeperator)[0]
|
||||
$ItemDay = $ItemLastWriteTime.Split($DateSeperator)[1]
|
||||
|
||||
$ItemFinalPath = $Targetpath+"\"+$ItemYear+"\"+$ItemMonth+"\"+$ItemDay
|
||||
Write-host "Targetpath: $($ItemFinalPath)"
|
||||
|
||||
IF (($ItemLastWriteTime) -and ($ItemYear) -and ($ItemMonth) -and ($ItemDay)) {
|
||||
|
||||
Try {
|
||||
|
||||
New-Item -Path $($ItemFinalPath) -ItemType container -ErrorAction SilentlyContinue
|
||||
|
||||
If (Test-Path $($ItemFinalPath)) {
|
||||
|
||||
$Item | Move-Item -Destination $($ItemFinalPath) -Force
|
||||
}
|
||||
|
||||
} #end try
|
||||
|
||||
Catch {
|
||||
|
||||
Write-Error $Error.Item(0)
|
||||
|
||||
} #end catch
|
||||
|
||||
} #end if
|
||||
|
||||
} #end foreach
|
||||
|
||||
Remove-Variable * -ErrorAction SilentlyContinue
|
||||
33
test/New-Password.ps1
Normal file
33
test/New-Password.ps1
Normal file
@@ -0,0 +1,33 @@
|
||||
cls
|
||||
|
||||
[int]$counter = 0
|
||||
[int]$count = 7
|
||||
[string]$pw = $NULL
|
||||
|
||||
DO {
|
||||
|
||||
$pw += Get-Random a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z
|
||||
[int]$counter++ | Out-Null
|
||||
$pw += Get-Random 0,1,2,3,4,5,6,7,8,9
|
||||
[int]$counter++ | Out-Null
|
||||
$pw += Get-Random A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z
|
||||
[int]$counter++ | Out-Null
|
||||
$pw += Get-Random '!','§','$','%','&','/','(',')','?','#'
|
||||
[int]$counter++ | Out-Null
|
||||
|
||||
} #end do
|
||||
|
||||
UNTIL (($counter -eq $count) -or ($counter -gt $count))
|
||||
|
||||
Write-Host $pw
|
||||
|
||||
#pw neu mischen
|
||||
#$CA = $pw.ToCharArray()
|
||||
#$SA = $CA | get-random -count $ca.length
|
||||
#$output = -join $SA
|
||||
|
||||
$CA = $pw.ToCharArray()
|
||||
$SA = $CA | get-random -count $ca.length
|
||||
$output = -join $SA
|
||||
|
||||
Write-Host $output
|
||||
32
test/OpenFolderDialog.ps1
Normal file
32
test/OpenFolderDialog.ps1
Normal file
@@ -0,0 +1,32 @@
|
||||
function Get-BrowseLocation
|
||||
{
|
||||
[Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms") | Out-Null
|
||||
[System.Windows.Forms.Application]::EnableVisualStyles()
|
||||
$browse = New-Object System.Windows.Forms.FolderBrowserDialog
|
||||
$browse.RootFolder = [System.Environment+SpecialFolder]'MyComputer'
|
||||
$browse.ShowNewFolderButton = $true
|
||||
$browse.Description = "Choose a directory"
|
||||
|
||||
$loop = $true
|
||||
while($loop)
|
||||
{
|
||||
if ($browse.ShowDialog() -eq "OK")
|
||||
{
|
||||
$loop = $false
|
||||
}
|
||||
else
|
||||
{
|
||||
$res = [System.Windows.Forms.MessageBox]::Show("You clicked Cancel. Try again or exit script?", "Choose a directory", [System.Windows.Forms.MessageBoxButtons]::RetryCancel)
|
||||
if($res -eq "Cancel")
|
||||
{
|
||||
#End script
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
$browse.SelectedPath
|
||||
$browse.Dispose()
|
||||
}
|
||||
|
||||
Get-BrowseLocation
|
||||
write-host $browse
|
||||
BIN
test/PS_Beispiel_Aufrufparameter.ps1
Normal file
BIN
test/PS_Beispiel_Aufrufparameter.ps1
Normal file
Binary file not shown.
30
test/PS_WPF_Sample.ps1
Normal file
30
test/PS_WPF_Sample.ps1
Normal file
@@ -0,0 +1,30 @@
|
||||
cls
|
||||
Add-Type -AssemblyName PresentationFramework
|
||||
Add-Type -AssemblyName System
|
||||
|
||||
if (test-path -Path "D:\PS_WPF_Sample.xaml"){
|
||||
[XML]$XAML = Get-Content D:\PS_WPF_Sample.xaml
|
||||
}
|
||||
|
||||
$XAML.Window.RemoveAttribute("x:Class")
|
||||
$Reader = New-Object System.Xml.XmlNodeReader $XAML
|
||||
$Form = [Windows.Markup.XamlReader]::Load($Reader)
|
||||
|
||||
$btnOKClick = {$PSLabel.Content = $PSText.Text}
|
||||
|
||||
$btnExitClick = {$Form.Close()}
|
||||
|
||||
Function GenerateForm {
|
||||
#create objects from controls
|
||||
$PSText = $Form.FindName('PSText')
|
||||
$PSLabel = $Form.FindName('PSLabel')
|
||||
$PSBtnOK = $Form.FindName('PSBtnOK')
|
||||
$PSBtnExit = $Form.FindName('PSBtnExit')
|
||||
|
||||
#Add the events to the controls
|
||||
$PSBtnOK.Add_Click($btnOKClick)
|
||||
$PSBtnExit.Add_Click($btnExitClick)
|
||||
|
||||
$Form.ShowDialog()| Out-Null
|
||||
}
|
||||
GenerateForm
|
||||
BIN
test/Password Change Notification.ps1
Normal file
BIN
test/Password Change Notification.ps1
Normal file
Binary file not shown.
99
test/PowerShellRunAs.ps1
Normal file
99
test/PowerShellRunAs.ps1
Normal file
@@ -0,0 +1,99 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Script to read and store the password value of a user credential as a securestring to/from file
|
||||
|
||||
.DESCRIPTION
|
||||
Script with both both the ability to set and get. When the Set switch is specified the script will prompt for credentials
|
||||
and write the password to the file file specified. When the script is running with the Get switch the script will read the password
|
||||
from the file specified in the $filename variable and use the username specified in the $username variable. This essentially allows you
|
||||
to runas another identity without having to enter credentials.
|
||||
|
||||
.SWITCH Get
|
||||
This switch runs the script in get mode
|
||||
|
||||
.SWITCH Set
|
||||
This switch runs the script in set mode
|
||||
|
||||
.PARAMETER Username
|
||||
The username to be written to file or to be used with the password that is extracted from the file.
|
||||
|
||||
.PARAMETER Filename
|
||||
Optional parameter, if not filled in it will default to $username.txt with backspaces removed
|
||||
|
||||
.NOTES
|
||||
Name: PowerShellRunAs.ps1
|
||||
Author: Jaap Brasser
|
||||
DateCreated: 22-03-2012
|
||||
|
||||
.EXAMPLE
|
||||
.\PowerShellRunAs.ps1 -get contoso\svc_remoterestart \\fileserver\share\file.pwd
|
||||
|
||||
Description
|
||||
-----------
|
||||
This command will get the password from file.pwd on the fileserver and use that in combination with contoso\svc_remoterestart
|
||||
to return the $credentials variable which can be directly used in another script. See the next example as to how you can use
|
||||
this script within another script.
|
||||
|
||||
.EXAMPLE
|
||||
-credential (C:\Script\PowerShellRunAs.ps1 -get contoso\svc_remoterestart \\fileserver\share\file.pwd)
|
||||
|
||||
Description
|
||||
-----------
|
||||
This command will get the password from file.pwd on the fileserver and use that in combination with contoso\svc_remoterestart
|
||||
to return the $credentials variable directly into -credential. This allows you to run as a different user and can be used in
|
||||
certain scheduled tasks or scripts in which typing the command can be bothersome.
|
||||
|
||||
.EXAMPLE
|
||||
-credential (PowerShellRunAs -get contoso\svc_remoterestart)
|
||||
|
||||
Description
|
||||
-----------
|
||||
This third example when you run the command as a function within your script. Because the filename was omitted the script will
|
||||
try and look for a standard filename in this case .\contoso_svc_remoterestart.pwd. Other than that is functions the same as the
|
||||
previous two examples and allows you to directly use the credentials to run an application as a different identity.
|
||||
|
||||
.EXAMPLE
|
||||
.\PowerShellRunAs.ps1 -set contoso\svc_remoterestart \\fileserver\share\file.pwd
|
||||
|
||||
Description
|
||||
-----------
|
||||
The last example shows how you can write the credentials to file. By running this a pop up will appear in which the password can
|
||||
be entered. After clicking okay the password will be written to file as a PowerShell securestring.
|
||||
#>
|
||||
|
||||
#function PowerShellRunAs {
|
||||
param
|
||||
(
|
||||
[string]$username,
|
||||
[string]$filename,
|
||||
[switch]$get,
|
||||
[switch]$set
|
||||
)
|
||||
|
||||
# Checks whether the correct values have been entered for this script to run, exits otherwise
|
||||
if (!($get) -and !($set)) {write-output "No get or set, exiting script";return}
|
||||
if (($get) -and ($set)) {write-output "Both get and set specified, exiting script";return}
|
||||
if (!($username)) {write-output "No username specified";return}
|
||||
if (!($filename)) {$filename = ($username -replace "\\", "_")+".pwd"}
|
||||
|
||||
# Runs the get sequence of the script, exits function if $filename is not found. Outputs $credential which can be used
|
||||
# in combination with -credential
|
||||
if ($get)
|
||||
{
|
||||
if (!(test-path $filename)) {write-output "File not found $filename, exiting script";return}
|
||||
$password = Get-Content $filename | ConvertTo-SecureString
|
||||
$credential = New-Object System.Management.Automation.PsCredential($username,$password)
|
||||
$credential
|
||||
return
|
||||
}
|
||||
|
||||
# Runs the set sequence of the script where the password securestring is written to file
|
||||
# Erroractionpreference is set to suppress errors when user closes credentials input
|
||||
if ($set)
|
||||
{
|
||||
$erroractionpreference = 0
|
||||
$credential = Get-Credential -Credential $username
|
||||
$credential.Password | ConvertFrom-SecureString | Set-Content $filename
|
||||
return
|
||||
}
|
||||
#}
|
||||
15
test/Regex-test1.ps1
Normal file
15
test/Regex-test1.ps1
Normal file
@@ -0,0 +1,15 @@
|
||||
cls
|
||||
|
||||
# PowerShell RegEx with Groups as result
|
||||
# Help from https://mcpmag.com/articles/2015/09/30/regex-groups-with-powershell.aspx
|
||||
|
||||
$txt1 = $NULL
|
||||
$res1 = $NULL
|
||||
|
||||
$txt1 = "#SCAN#DD-Eingangsrechnung"
|
||||
|
||||
#$res1 = ($txt1 | Select-String -pattern "(?:#SCAN#(DD-[a-zA-Z-üÜöÖäÄ]{1,}))" -AllMatches | %{$_.matches} | %{$_.value})
|
||||
|
||||
$res1 = ([regex]::Match("$txt1", "(?:#SCAN#(DD-[a-zA-Z-üÜöÖäÄ]{1,}))").Groups[1].Value)
|
||||
|
||||
echo $res1
|
||||
668
test/Registry.ps1
Normal file
668
test/Registry.ps1
Normal file
@@ -0,0 +1,668 @@
|
||||
################################################################################
|
||||
# Registry (stand alone) functions library
|
||||
# Author: $cript Fanatic (Shay Levi)
|
||||
# Blog: http://scriptolog.blogspot.com
|
||||
# Description: Read,Write,Delete,Test registry keys/values from local/remote computer
|
||||
#
|
||||
# For all functions, values for registry hive can be one of the enum values for
|
||||
# [Microsoft.Win32.RegistryHive]. To get a list of possible values type:
|
||||
# [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
#
|
||||
# For all functions, values for registry value kind can be one of the enum values for
|
||||
# [Microsoft.Win32.RegistryValueKind]. To get a list of possible kind values type:
|
||||
# [enum]::getnames([Microsoft.Win32.RegistryValueKind])
|
||||
#
|
||||
# NOTE: get/set the CurrentUser hive on a remote server is N/A
|
||||
#
|
||||
################################################################################
|
||||
#
|
||||
# Function: Get-RegString
|
||||
# Description: Get registry string value (REG_SZ)
|
||||
# Return Value: The string value or the value to return if name does not exist
|
||||
# usage:
|
||||
#
|
||||
# get the default home page url from the local computer:
|
||||
# Get-RegString . CurrentUser "Software\Microsoft\Internet Explorer\Main" "Start Page"
|
||||
#
|
||||
# get the product id from remote server
|
||||
# Get-RegString ServerName LocalMachine SOFTWARE\Microsoft\Windows\CurrentVersion ProductId
|
||||
|
||||
function Get-RegString{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
[string]$valueName,
|
||||
[object]$defaultValue="Your default value"
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
$subKey.GetValue($valueName,$defaultValue);
|
||||
}
|
||||
|
||||
################################################################################
|
||||
# Function: Set-RegString
|
||||
# Description: Create/Update the specified registry string value
|
||||
# Return Value: True/false respectively
|
||||
|
||||
function Set-RegString{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
[string]$valueName,
|
||||
[string]$value
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName,$true);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
$subKey.SetValue($valueName, $value, [Microsoft.Win32.RegistryValueKind]::String);
|
||||
if($?) {$true} else {$false}
|
||||
}
|
||||
|
||||
|
||||
################################################################################
|
||||
# Function: Get-RegMultipleString
|
||||
# Description: Gets an array strings (REG_MULTI_SZ)
|
||||
# Return Value: Array object
|
||||
|
||||
function Get-RegMultipleString{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
[string]$valueName,
|
||||
[object]$defaultValue="Your default value"
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
$subKey.GetValue($valueName,$defaultValue);
|
||||
}
|
||||
|
||||
################################################################################
|
||||
# Function: Set-RegMultipleString
|
||||
# Description: Create/Update the specified registry as strings array (REG_MULTI_SZ)
|
||||
# Return Value: True/false respectively
|
||||
|
||||
function Set-RegMultipleString{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
[string]$valueName,
|
||||
[String[]]$value
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName,$true);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
$subKey.SetValue($valueName, $value,[Microsoft.Win32.RegistryValueKind]::MultiString);
|
||||
if($?) {$true} else {$false}
|
||||
}
|
||||
|
||||
|
||||
################################################################################
|
||||
# Function: Get-RegBinary
|
||||
# Description: Gets the registry value (REG_BINARY)
|
||||
# Return Value: Array object
|
||||
|
||||
function Get-RegBinary{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
[string]$valueName,
|
||||
[object]$defaultValue="Your default value"
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName);
|
||||
$subKey.GetValue($valueName,$defaultValue);
|
||||
}
|
||||
|
||||
################################################################################
|
||||
# Function: Set-RegBinary
|
||||
# Description: Create/Update the registry value (REG_BINARY)
|
||||
# Return Value: True/false respectively
|
||||
|
||||
function Set-RegBinary{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
[string]$valueName,
|
||||
[byte[]]$value
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName,$true);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
$subKey.SetValue($valueName, $value,[Microsoft.Win32.RegistryValueKind]::Binary);
|
||||
if($?) {$true} else {$false}
|
||||
|
||||
}
|
||||
|
||||
################################################################################
|
||||
# Function: Set-RegDWord
|
||||
# Description: Create/Update the registry value (REG_DWORD)
|
||||
# Return Value: True/false respectively
|
||||
|
||||
function Set-RegDWord{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
[string]$valueName,
|
||||
[double]$value
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName,$true);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
$subKey.SetValue($valueName, $value,[Microsoft.Win32.RegistryValueKind]::DWord);
|
||||
if($?) {$true} else {$false}
|
||||
}
|
||||
|
||||
################################################################################
|
||||
# Function: Get-RegDWord
|
||||
# Description: Gets the registry value (REG_DWORD)
|
||||
# Return Value: registry dword value
|
||||
|
||||
function Get-RegDWord{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
[string]$valueName,
|
||||
[object]$defaultValue="Your default value"
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
$subKey.GetValue($valueName,$defaultValue);
|
||||
}
|
||||
|
||||
################################################################################
|
||||
# Function: Set-RegExpandString
|
||||
# Description: Create/Update the registry value (REG_EXPAND_SZ)
|
||||
# Return Value: True/false respectively
|
||||
|
||||
function Set-RegExpandString{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
[string]$valueName,
|
||||
[string]$value
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName,$true);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
$subKey.SetValue($valueName, $value,[Microsoft.Win32.RegistryValueKind]::ExpandString);
|
||||
if($?) {$true} else {$false}
|
||||
}
|
||||
|
||||
|
||||
################################################################################
|
||||
# Function: Set-RegExpandString
|
||||
# Description: Get the registry value (REG_EXPAND_SZ)
|
||||
# Return Value: registry value expanded or not based on -expand switch
|
||||
|
||||
function Get-RegExpandString{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
[string]$valueName,
|
||||
[object]$defaultValue="Your default value",
|
||||
[switch]$expand
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
if($expand){
|
||||
$subKey.GetValue($valueName,$defaultValue);
|
||||
} else {
|
||||
$subKey.GetValue($valueName,$defaultValue,[Microsoft.Win32.RegistryValueOptions]::DoNotExpandEnvironmentNames);
|
||||
}
|
||||
}
|
||||
|
||||
################################################################################
|
||||
# Function: Get-RegQuadWord
|
||||
# Description: get the registry value (REG_QWORD)
|
||||
# Return Value: registry value
|
||||
|
||||
function Get-RegQuadWord{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
[string]$valueName,
|
||||
[object]$defaultValue="Your default value"
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
$subKey.GetValue($valueName,$defaultValue);
|
||||
}
|
||||
|
||||
################################################################################
|
||||
# Function: Set-RegExpandString
|
||||
# Description: Get the registry value (REG_QWORD)
|
||||
# Return Value: True/false respectively
|
||||
|
||||
function Set-RegQuadWord{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
[string]$valueName,
|
||||
[long]$value
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName,$true);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
$subKey.SetValue($valueName, $value,[Microsoft.Win32.RegistryValueKind]::QWord);
|
||||
if($?) {$true} else {$false}
|
||||
}
|
||||
|
||||
|
||||
################################################################################
|
||||
# Function: Get-RegDefault
|
||||
# Description: Get the registry default value
|
||||
# Return Value: registry default value
|
||||
|
||||
function Get-RegDefault{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
$subKey.GetValue($null);
|
||||
}
|
||||
|
||||
|
||||
################################################################################
|
||||
# Function: Set-RegDefault
|
||||
# Description: Set the registry default value
|
||||
# Return Value: True/false respectively
|
||||
|
||||
function Set-RegDefault{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
$value
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName,$true);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
#$regKey.SetValue($null, $value,[Microsoft.Win32.RegistryValueKind]::String);
|
||||
$subKey.SetValue($null, $value,[Microsoft.Win32.RegistryValueKind]::String);
|
||||
|
||||
if($?) {$true} else {$false}
|
||||
}
|
||||
|
||||
################################################################################
|
||||
# Function: New-RegSubKey
|
||||
# Description: Create the registry key
|
||||
# Return Value: True/false respectively
|
||||
|
||||
function New-RegSubKey{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
[void]$regKey.CreateSubKey($keyName);
|
||||
|
||||
if($?) {$true} else {$false}
|
||||
}
|
||||
|
||||
################################################################################
|
||||
# Function: Remove-RegSubKey
|
||||
# Description: Delete the registry key
|
||||
# Return Value: Throws error in case the key doesnt exist
|
||||
|
||||
function Remove-RegSubKey{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$regKey.DeleteSubKey($keyName,$true);
|
||||
}
|
||||
|
||||
################################################################################
|
||||
# Function: Remove-RegSubKeyTree
|
||||
# Description: Delete the registry key tree
|
||||
# Return Value: None
|
||||
|
||||
function Remove-RegSubKeyTree{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$regKey.DeleteSubKeyTree($keyName);
|
||||
}
|
||||
|
||||
################################################################################
|
||||
# Function: Get-RegValueKind
|
||||
# Description: Get the registry value type (e.g, string,dword etc)
|
||||
# Return Value: None
|
||||
|
||||
function Get-RegValueKind{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
[string]$valueName
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
$regVal=$subKey.GetValueKind($valueName);
|
||||
|
||||
if(!$regVal){
|
||||
write-error "The specified registry value does not exist.";
|
||||
return;
|
||||
} else {
|
||||
$regVal;
|
||||
}
|
||||
}
|
||||
|
||||
################################################################################
|
||||
# Function: Test-RegSubKey
|
||||
# Description: Test the existence of the registry key
|
||||
# Return Value: True/false respectively
|
||||
|
||||
function Test-RegSubKey{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName);
|
||||
|
||||
if(!$subKey){$false} else {$true}
|
||||
}
|
||||
|
||||
################################################################################
|
||||
# Function: Test-RegValue
|
||||
# Description: Test the existence of the registry value
|
||||
# Return Value: True/false respectively
|
||||
|
||||
|
||||
function Test-RegValue{
|
||||
param(
|
||||
[string]$server = ".",
|
||||
[string]$hive,
|
||||
[string]$keyName,
|
||||
[string]$valueName
|
||||
)
|
||||
|
||||
$hives = [enum]::getnames([Microsoft.Win32.RegistryHive])
|
||||
|
||||
if($hives -notcontains $hive){
|
||||
write-error "Invalid hive value";
|
||||
return;
|
||||
}
|
||||
|
||||
$regHive = [Microsoft.Win32.RegistryHive]$hive;
|
||||
$regKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey($regHive,$server);
|
||||
$subKey = $regKey.OpenSubKey($keyName);
|
||||
|
||||
if(!$subKey){
|
||||
write-error "The specified registry key does not exist.";
|
||||
return;
|
||||
}
|
||||
|
||||
$regVal=$subKey.GetValue($valueName);
|
||||
if(!$regVal){$false} else {$true}
|
||||
}
|
||||
3
test/Remove-AllVariables.ps1
Normal file
3
test/Remove-AllVariables.ps1
Normal file
@@ -0,0 +1,3 @@
|
||||
Remove-Variable * -Force -ErrorAction SilentlyContinue
|
||||
$error.clear()
|
||||
cls
|
||||
BIN
test/SelectFolderDialog.ps1
Normal file
BIN
test/SelectFolderDialog.ps1
Normal file
Binary file not shown.
BIN
test/Show_MessageBox.ps1
Normal file
BIN
test/Show_MessageBox.ps1
Normal file
Binary file not shown.
92
test/SimpleCopy.ps1
Normal file
92
test/SimpleCopy.ps1
Normal file
@@ -0,0 +1,92 @@
|
||||
Set-Variable -Name SourcePath -Value "E:\EDMServiceDebug" -Force
|
||||
Set-Variable -Name DestinationsPath -Value "D:\ProgramFiles\Digital Data\SERVICES\EDM_SERVICE" -Force
|
||||
Set-Variable -Name ServiceName -Value "Digital Data EDM Service" -Force
|
||||
|
||||
IF ($SourcePath -and $DestinationsPath -and $ServiceName) {
|
||||
|
||||
TRY {
|
||||
|
||||
$Items = Get-ChildItem -Path $SourcePath -Exclude "*.db, desktop.ini"
|
||||
|
||||
} #end try
|
||||
|
||||
CATCH {
|
||||
|
||||
Write-Host "Error getting SourcePath content!"
|
||||
|
||||
} #end catch
|
||||
|
||||
IF ($Items.count -gt 0) {
|
||||
|
||||
Write-Host "Found $($Items.count) File(s)"
|
||||
Write-Host "Stopping Service: $ServiceName"
|
||||
|
||||
TRY {
|
||||
|
||||
Stop-Service -Name $ServiceName -Force
|
||||
|
||||
} #end try
|
||||
|
||||
CATCH {
|
||||
|
||||
Write-Host "Service could not be stopped"
|
||||
pause
|
||||
break
|
||||
|
||||
}#end catch
|
||||
|
||||
FOREACH ($Item in $Items) {
|
||||
|
||||
TRY {
|
||||
|
||||
$Item | Move-Item -Destination $DestinationsPath -Force -ErrorAction Stop
|
||||
Write-Host "Moved File: $($Item.name)"
|
||||
|
||||
} #end try
|
||||
|
||||
CATCH {
|
||||
|
||||
Write-Host "Error moving File: $($Item.name)"
|
||||
pause
|
||||
|
||||
} #end catch
|
||||
|
||||
} #end foreach
|
||||
|
||||
TRY {
|
||||
|
||||
Start-Service -Name $ServiceName
|
||||
|
||||
} #end try
|
||||
|
||||
CATCH {
|
||||
|
||||
Write-Host "Service could not be started"
|
||||
pause
|
||||
break
|
||||
|
||||
}#end catch
|
||||
|
||||
Start-Sleep 3
|
||||
|
||||
} #end if
|
||||
|
||||
ELSE {
|
||||
|
||||
Write-Host "No Files to Process!"
|
||||
pause
|
||||
|
||||
} #end else
|
||||
|
||||
} #end if
|
||||
|
||||
ELSE {
|
||||
|
||||
Write-Host "Missing Values!"
|
||||
pause
|
||||
|
||||
} #end else
|
||||
|
||||
Remove-Variable $SourcePath
|
||||
Remove-Variable $DestinationsPath
|
||||
Remove-Variable $ServiceName
|
||||
261
test/SystemDriver.ps1
Normal file
261
test/SystemDriver.ps1
Normal file
@@ -0,0 +1,261 @@
|
||||
#############################################################################
|
||||
# Commandlet: get-sysdriver und set-sysdriver #
|
||||
# Autor: Armin Friedrich #
|
||||
# Klasse: Win32_SystemDriver #
|
||||
# Beschreibung: #
|
||||
# Systemtreiber fuer Basisdienste ausgeben, starten bzw. stoppen #
|
||||
# Aufruf der Commandlets mit Parametern durch , getrennt #
|
||||
# Beispiele: #
|
||||
# get-sysdriver, get-sysdriver g1_11,netbios, get-systreiber netbios #
|
||||
# set-sysdriver, set-sysdriver beep,start, set-systreiber g1_10,beep,stop #
|
||||
#############################################################################
|
||||
|
||||
function get-SysDriver {
|
||||
param([string[]]$arg)
|
||||
begin{
|
||||
$anz=0 # Variable fuer die Anzahl der eingegebenen Parameter
|
||||
# Schleife zur Ermittlung Anzahl Parameter
|
||||
if($arg){
|
||||
foreach ($anzahl in $arg)
|
||||
{
|
||||
$anz++ # Anzahl der Parameter
|
||||
}
|
||||
}
|
||||
|
||||
# Pruefung, von welchem Rechner die Systemtreiber abgefragt werden
|
||||
# inklusive Auswahl des entsprechenden Treibers
|
||||
|
||||
# Keine Eingabe - dann manuelle Auswahl Treiber und Auswahl PC
|
||||
if($anz -eq 0)
|
||||
{
|
||||
$treiber = Read-Host "Bestimmter Treiber oder <ENTER> fuer alle"
|
||||
$pc = Read-Host "Welcher PC"
|
||||
}
|
||||
# Eingabe von PC und Treiber korrekt erfolgt (z.B. get-sysdriver g1_11,vga)
|
||||
elseif ($anz -eq 2)
|
||||
{
|
||||
$pc = $arg[0]
|
||||
$treiber = $arg[1]
|
||||
}
|
||||
# Eingabe vom Treiber erfolgt (z.B. get-sysdriver vga) - Auswahl des PC moeglich
|
||||
else
|
||||
{
|
||||
$treiber = $arg[0]
|
||||
$pc = Read-Host "Welcher PC"
|
||||
}
|
||||
}
|
||||
process{
|
||||
}
|
||||
end{
|
||||
# Pruefung wenn bei PC nicht . fuer localhost eingegeben wurde
|
||||
# ob der Rechner auch erreichbar ist
|
||||
if($pc -ne ".")
|
||||
{
|
||||
$adress="Address='"+$pc+"'"
|
||||
$p=Get-WmiObject -Class Win32_PingStatus -Filter $adress |select-object statuscode
|
||||
if($p.statuscode -ne 0)
|
||||
{
|
||||
Write-Host -ForegroundColor red -BackgroundColor yellow "keine Verbindung zu dem angegebenen PC"
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# Wenn ENTER dann alle Systemtreiber ausgeben
|
||||
if($treiber -eq "")
|
||||
{
|
||||
$treiber = Get-WmiObject -Class "Win32_SystemDriver" -computername $pc -Namespace "ROOT\CIMV2"
|
||||
$treiber | select-object Name,Status,State,AcceptStop,StartMode,Systemname | Format-Table
|
||||
}
|
||||
# Ausgabe des eingegebenen Systemtreibers
|
||||
else
|
||||
{
|
||||
# Hilfsvariable zum Treibervergleich
|
||||
$tmp=$treiber
|
||||
$treiber = Get-WmiObject -Class "Win32_SystemDriver" -computername $pc -Namespace "ROOT\CIMV2" | Where-Object {$_.Name -eq $treiber}
|
||||
# Pruefung, ob der Treiber ueberhaupt existiert
|
||||
if($treiber.name -ne $tmp)
|
||||
{
|
||||
write-host -ForegroundColor red "Treiber exisitiert nicht"
|
||||
break
|
||||
}
|
||||
# Wenn Treiber exisitiert, dann Ausgabe der entsprechenden Daten
|
||||
else
|
||||
{
|
||||
Write-Host "*******************************************"
|
||||
Write-Host " Name: " $treiber.name
|
||||
Write-Host " Status: " $treiber.status
|
||||
Write-Host " State: " $treiber.state
|
||||
Write-Host " Accept Stop: " $treiber.acceptstop
|
||||
Write-Host "*******************************************"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function set-SysDriver {
|
||||
param([string[]]$arg)
|
||||
begin{
|
||||
$anz=0 # Variable fuer die Anzahl der eingegebenen Parameter
|
||||
# Schleife zur Ermittlung Anzahl Parameter
|
||||
if($arg){
|
||||
foreach ($anzahl in $arg)
|
||||
{
|
||||
$anz++ # Anzahl der Parameter
|
||||
}
|
||||
}
|
||||
|
||||
# Pruefung, ob Parameter eingegeben wurden:
|
||||
if($anz -le 1)
|
||||
{
|
||||
# Gar kein Parameter wurde eingegeben (z.B. set-sysdriver)
|
||||
falscheeingabe
|
||||
$pc = Read-Host "Welcher PC "
|
||||
$treiber = Read-Host "Welcher Systemtreiber "
|
||||
$status = Read-Host "Start oder Stop "
|
||||
if($status -ne "start" -and $status -ne "stop")
|
||||
{
|
||||
Write-Host "falsch Eingabe beim Status!!"
|
||||
$status = Read-Host "Status (start/stop)"
|
||||
}
|
||||
}
|
||||
# 2 Parameter eingegeben (z.B. set-sysdriver netbios,start)
|
||||
elseif ($anz -eq 2)
|
||||
{
|
||||
$pc = "."
|
||||
$treiber = $arg[0]
|
||||
$status = $arg[1]
|
||||
if($status -ne "start" -and $status -ne "stop")
|
||||
{
|
||||
Write-Host "falsch Eingabe beim Status!!"
|
||||
$status = Read-Host "Status (start/stop)"
|
||||
}
|
||||
}
|
||||
# 3 Parameter eingegeben (z.B. set-sysdriver g1_11,netbios,start)
|
||||
else
|
||||
{
|
||||
$pc = $arg[0]
|
||||
$treiber = $arg[1]
|
||||
$status = $arg[2]
|
||||
if($status -ne "start" -and $status -ne "stop")
|
||||
{
|
||||
Write-Host "falsch Eingabe beim Status!!"
|
||||
$status = Read-Host "Status (start/stop)"
|
||||
}
|
||||
}
|
||||
}
|
||||
process{
|
||||
}
|
||||
end{
|
||||
# Pruefung wenn bei PC nicht . fuer localhost eingegeben wurde
|
||||
# ob der Rechner auch erreichbar ist
|
||||
if($pc -ne ".")
|
||||
{
|
||||
$adress="Address='"+$pc+"'"
|
||||
$p=Get-WmiObject -Class Win32_PingStatus -Filter $adress |select-object statuscode
|
||||
if($p.statuscode -ne 0)
|
||||
{
|
||||
Write-Host -ForegroundColor red -BackgroundColor yellow "keine Verbindung zu dem angegebenen PC"
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
# Keine Treiber angegeben
|
||||
if($treiber -eq "")
|
||||
{
|
||||
write-host -ForegroundColor red "Kein Treiber angegeben"
|
||||
break
|
||||
}
|
||||
# Pruefungen, wenn Treiber angegeben
|
||||
else
|
||||
{
|
||||
# Hilfsvariable zum Treibervergleich
|
||||
$tmp=$treiber
|
||||
$treiber = Get-WmiObject -Class "Win32_SystemDriver" -computername $pc -Namespace "ROOT\CIMV2" | Where-Object {$_.Name -eq $treiber}
|
||||
# Pruefung, ob der Treiber ueberhaupt existiert
|
||||
if($treiber.name -ne $tmp)
|
||||
{
|
||||
write-host -ForegroundColor red "Treiber exisitiert nicht"
|
||||
break
|
||||
}
|
||||
# Treiber exisitiert -> Abarbeiten von Parameter Start bzw. Stop
|
||||
else
|
||||
{
|
||||
# Pruefung Status:
|
||||
switch($status)
|
||||
{
|
||||
# Pruefung ob Starten des Treibers moeglich ist:
|
||||
"Start"
|
||||
{
|
||||
# Pruefung ob der angegebene Treiber bereits laeuft:
|
||||
if($treiber.state -like "running")
|
||||
{
|
||||
Write-Host -ForegroundColor yellow "Treiber laeuft bereits"
|
||||
break
|
||||
}
|
||||
else
|
||||
{
|
||||
# Zuweisung Ergebnis Startvorgang
|
||||
$erg = $treiber.startservice()
|
||||
} # Abschluss Pruefung, ob Treiber bereits laeuft
|
||||
|
||||
# Pruefung ob der angegebene Treiber korrekt gestartet wurde:
|
||||
if($erg.returnvalue -eq "0")
|
||||
{
|
||||
Write-Host -ForegroundColor green "Treiber" $treiber.name "wurde gestartet"
|
||||
}
|
||||
else
|
||||
{
|
||||
# Fehlermeldung, da Ergebnis -ne 0 ist -> d. h. Treiber konnte nicht gestartet werden:
|
||||
Write-Host -ForegroundColor Red "Treiber" $treiber.name "konnte nicht gestartet werden"
|
||||
Write-Host -ForegroundColor Red "Fehler-Nummer" $erg.returnvalue
|
||||
} # Abschluss Pruefung, ob Treiber korrekt gestartet wurde
|
||||
} # Ende Start
|
||||
|
||||
# Pruefung ob Stoppen des Treibers moeglich ist:
|
||||
"Stop"
|
||||
{
|
||||
# Pruefung, ob ein stoppen des Treibers ueberhaupt moeglich ist
|
||||
if($treiber.AcceptStop -like "false")
|
||||
{
|
||||
Write-Host -ForegroundColor red "Treiber kann nicht gestoppt werden"
|
||||
break
|
||||
} # Abschluss Pruefung, ob Treiber gestoppt werden kann
|
||||
|
||||
# Pruefung ob der angegebene Treiber schon gestoppt ist:
|
||||
if($treiber.state -like "stopped")
|
||||
{
|
||||
Write-Host "Treiber ist bereits gestoppt"
|
||||
break
|
||||
}
|
||||
else
|
||||
{
|
||||
# Zuweisung Ergebnis Startvorgang
|
||||
$erg = $treiber.stopservice()
|
||||
} # Abschluss Pruefung, ob Treiber bereits gestoppt
|
||||
|
||||
if($erg.returnvalue -eq "0")
|
||||
{
|
||||
Write-Host -ForegroundColor green "Treiber" $treiber.name "wurde gestoppt"
|
||||
}
|
||||
else
|
||||
{
|
||||
# Fehlermeldung, da Ergebnis -ne 0 ist -> d. h. Treiber konnte nicht gestartet werden:
|
||||
Write-Host -ForegroundColor Red "Treiber" $treiber.name "konnte nicht gestoppt werden"
|
||||
Write-Host -ForegroundColor Red "Fehler-Nummer" $erg.returnvalue
|
||||
} # Abschluss Pruefung, ob Treiber korrekt gestartet wurde
|
||||
} # Ende Stop
|
||||
} # Ende switch
|
||||
} # Ende Abarbeitung Treiber existiert
|
||||
} # Ende Pruefung wenn Treiber angegeben
|
||||
} # Ende end
|
||||
} # Ende function set-sysdriver
|
||||
|
||||
function falscheeingabe
|
||||
{
|
||||
Write-Host -ForegroundColor blue -backgroundcolor yellow "Folgende Eingaben beim naechsten Mal beruecksichtigen: "
|
||||
write-host -ForegroundColor blue -backgroundcolor yellow "-> set-sysdriver treiber, status "
|
||||
Write-Host -ForegroundColor blue -backgroundcolor yellow "-> set-sysdriver pc,treiber,status "
|
||||
}
|
||||
|
||||
#zur Erfolgskontrolle:
|
||||
"Das Commandlet fuer die Systemtreiber wurde erfolgreich geladen"
|
||||
213
test/Tail-Content.ps1
Normal file
213
test/Tail-Content.ps1
Normal file
@@ -0,0 +1,213 @@
|
||||
<#
|
||||
.NOTES
|
||||
AUTHOR: Keith Hill, r_keith_hill@hotmail.com
|
||||
DATE: Jan 25, 2009
|
||||
NAME: Tail-Content.ps1
|
||||
LICENSE: BSD, http://en.wikipedia.org/wiki/BSD_license
|
||||
Copyright (c) 2009, Keith Hill
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice,
|
||||
this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright
|
||||
notice, this list of conditions and the following disclaimer in the
|
||||
documentation and/or other materials provided with the distribution.
|
||||
* Neither the name of the COPYRIGHT HOLDERS nor the names of its contributors
|
||||
may be used to endorse or promote products derived from this software
|
||||
without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
|
||||
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
|
||||
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
|
||||
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
|
||||
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
|
||||
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
|
||||
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
||||
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
||||
POSSIBILITY OF SUCH DAMAGE.
|
||||
.LINK
|
||||
http://KeithHill.spaces.live.com
|
||||
.SYNOPSIS
|
||||
Tail-Content efficiently displays the specified number of lines from the end of an ASCII file.
|
||||
.DESCRIPTION
|
||||
Tail-Content efficiently displays the specified number of lines from the end of an ASCII file.
|
||||
When you use Get-Content foo.txt | Select-Object -Tail 5 every line in the foo.txt file
|
||||
is processed. This can be very inefficient and slow on large log files. Tail-Content
|
||||
uses stream processing to read the lines from the end of the file.
|
||||
.PARAMETER LiteralPath
|
||||
Specifies the path to an item. Unlike Path, the value of LiteralPath is used exactly as it is typed.
|
||||
No characters are interpreted as wildcards. If the path includes escape characters, enclose it in
|
||||
single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters
|
||||
as escape sequences.
|
||||
.PARAMETER Path
|
||||
Specifies the path to an item. Get-Content retrieves the content of the item. Wildcards are permitted.
|
||||
The parameter name ("-Path" or "-FilePath") is optional.
|
||||
.PARAMETER Last
|
||||
Specifies how many lines to get from the end of the file. The default
|
||||
.PARAMETER Newline
|
||||
Specifies the default newline character sequence the default is [System.Environment]::Newline.
|
||||
.EXAMPLE
|
||||
C:\PS>Tail-Content foo.txt
|
||||
|
||||
Displays the last line of a file. Note the last line of a file is quite often an empty line.
|
||||
.EXAMPLE
|
||||
C:\PS>Tail-Content *.txt -Last 10
|
||||
|
||||
Displays the last 10 lines of all the .txt files in the current directory.
|
||||
.EXAMPLE
|
||||
C:\PS>Get-ChildItem . -inc *.log -r | tail-content -last 5
|
||||
|
||||
Uses pipepline bound path parameter to determine path of file to tail.
|
||||
#>
|
||||
|
||||
#requires -version 2.0
|
||||
|
||||
[CmdletBinding(DefaultParameterSetName="Path")]
|
||||
param(
|
||||
[Parameter(Mandatory=$true,
|
||||
Position=0,
|
||||
ParameterSetName="Path",
|
||||
ValueFromPipeline=$true,
|
||||
ValueFromPipelineByPropertyName=$true)]
|
||||
[ValidateNotNullOrEmpty()]
|
||||
[string[]]
|
||||
$Path,
|
||||
|
||||
[Alias("PSPath")]
|
||||
[Parameter(Mandatory=$true,
|
||||
Position=0,
|
||||
ParameterSetName="LiteralPath",
|
||||
ValueFromPipelineByPropertyName=$true)]
|
||||
[ValidateNotNullOrEmpty()]
|
||||
[string[]]
|
||||
$LiteralPath,
|
||||
|
||||
[Parameter()]
|
||||
[switch]
|
||||
$Wait,
|
||||
|
||||
[Parameter()]
|
||||
[ValidateRange(0, 2GB)]
|
||||
[int]
|
||||
$Last = 10,
|
||||
|
||||
[Parameter()]
|
||||
[ValidateNotNullOrEmpty()]
|
||||
[string]
|
||||
$Newline = $([Environment]::Newline)
|
||||
)
|
||||
|
||||
Begin
|
||||
{
|
||||
Set-StrictMode -Version 2.0
|
||||
$fs = $null
|
||||
}
|
||||
|
||||
Process
|
||||
{
|
||||
if ($psCmdlet.ParameterSetName -eq "Path")
|
||||
{
|
||||
# In the non-literal case we may need to resolve a wildcarded path
|
||||
$resolvedPaths = @()
|
||||
foreach ($apath in $Path)
|
||||
{
|
||||
$resolvedPaths += @(Resolve-Path $apath | Foreach { $_.Path })
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$resolvedPaths = $LiteralPath
|
||||
}
|
||||
|
||||
if ($Wait -and ($resolvedPaths.Length -gt 1))
|
||||
{
|
||||
throw "Wait is only supported on one file at a time."
|
||||
}
|
||||
|
||||
foreach ($rpath in $resolvedPaths)
|
||||
{
|
||||
$numLines = $Last
|
||||
$seekOffset = -1;
|
||||
$PathIntrinsics = $ExecutionContext.SessionState.Path
|
||||
|
||||
if ($PathIntrinsics.IsProviderQualified($rpath))
|
||||
{
|
||||
$rpath = $PathIntrinsics.GetUnresolvedProviderPathFromPSPath($rpath)
|
||||
}
|
||||
|
||||
Write-Verbose "Tail-Content processing $rpath"
|
||||
|
||||
try
|
||||
{
|
||||
$output = New-Object "System.Text.StringBuilder"
|
||||
$newlineIndex = $Newline.Length - 1
|
||||
|
||||
$fs = New-Object "System.IO.FileStream" $rpath,"Open","Read","ReadWrite"
|
||||
$oldLength = $fs.Length
|
||||
|
||||
while ($numLines -gt 0 -and (($fs.Length + $seekOffset) -ge 0))
|
||||
{
|
||||
[void]$fs.Seek($seekOffset--, "End")
|
||||
$ch = $fs.ReadByte()
|
||||
|
||||
if ($ch -eq 0 -or $ch -gt 127)
|
||||
{
|
||||
throw "Tail-Content only works on ASCII encoded files"
|
||||
}
|
||||
|
||||
[void]$output.Insert(0, [char]$ch)
|
||||
|
||||
# Count line terminations
|
||||
if ($ch -eq $Newline[$newlineIndex])
|
||||
{
|
||||
if (--$newlineIndex -lt 0)
|
||||
{
|
||||
$newlineIndex = $Newline.Length - 1
|
||||
# Ignore the newline at the end of the file
|
||||
if ($seekOffset -lt -($Newline.Length + 1))
|
||||
{
|
||||
$numLines--
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
# Remove beginning line terminator
|
||||
$output = $output.ToString().TrimStart([char[]]$Newline)
|
||||
Write-Host $output -NoNewline
|
||||
|
||||
if ($Wait)
|
||||
{
|
||||
# Now push pointer to end of file
|
||||
[void]$fs.Seek($oldLength, "Begin")
|
||||
|
||||
for(;;)
|
||||
{
|
||||
if ($fs.Length -gt $oldLength)
|
||||
{
|
||||
$numNewBytes = $fs.Length - $oldLength
|
||||
$buffer = new-object byte[] $numNewBytes
|
||||
$numRead = $fs.Read($buffer, 0, $buffer.Length)
|
||||
|
||||
$string = [System.Text.Encoding]::Ascii.GetString($buffer, 0, $buffer.Length)
|
||||
Write-Host $string -NoNewline
|
||||
|
||||
$oldLength += $numRead
|
||||
}
|
||||
Start-Sleep -Milliseconds 300
|
||||
}
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
if ($fs) { $fs.Close() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
BIN
test/Test-withNewModul.ps1
Normal file
BIN
test/Test-withNewModul.ps1
Normal file
Binary file not shown.
BIN
test/Verschlüsselung.ps1
Normal file
BIN
test/Verschlüsselung.ps1
Normal file
Binary file not shown.
BIN
test/WOL.ps1
Normal file
BIN
test/WOL.ps1
Normal file
Binary file not shown.
61
test/WriteLog.ps1
Normal file
61
test/WriteLog.ps1
Normal file
@@ -0,0 +1,61 @@
|
||||
# PowerShell 4.0 Script
|
||||
# Log Datei schreiben
|
||||
|
||||
# Digital Data
|
||||
# Ludwig-Rinn-Strasse 16
|
||||
# 35452 Heuchelheim
|
||||
# Tel.: 0641 / 202360
|
||||
# E-Mail: info@didalog.de
|
||||
|
||||
# Version 1.0
|
||||
# Letzte Aktualisierung: 15.04.2014
|
||||
|
||||
# Mindestanforderung für dieses Skript:
|
||||
# Microsoft Windows 7 SP1 / Server 2008 R2 SP1 -> siehe KB976932
|
||||
# Microsoft .NET Framework 4.5 -> siehe KB2858728
|
||||
# Microsoft PowerShell 4.0 -> siehe KB2819745
|
||||
|
||||
# WICHTIG: Falls sich dieses Skript nicht ausführen lässt,
|
||||
# muss dieser PS-Befehl noch mit administrativen Rechten ausgeführt werden:
|
||||
# set-executionpolicy unrestricted
|
||||
|
||||
# Definition der Variablen
|
||||
|
||||
Set-Variable -name SkriptName -value $MyInvocation.MyCommand.Name -Description "Name dieser Datei, wird verwendet, für Erstellung von Logs."
|
||||
Set-Variable -name timestamp -value $(Get-Date -Format 'ddMMyyyy_hhmmss') -Description "Datum wird in einem gewissen Format aufbereitet und dann Log-Dateien anhangen."
|
||||
Set-Variable -name LogPath -value "e:\" -Description "Pfad für Log-Dateien."
|
||||
Set-Variable -name Logfile -value "$SkriptName`_$timestamp.log" -Description "Name für Log-Dateien."
|
||||
Set-Variable -name LogEntfernen -value $(Get-Date).AddDays(-1) -Description "Zahlenwert, wie lange Log-Dateien aufbewahrt werden sollen z.B. -30 = 30 Tage aufbewahren."
|
||||
|
||||
# Definition der Funktionen
|
||||
|
||||
Function LogWrite
|
||||
{
|
||||
Param ([string]$logstring)
|
||||
|
||||
Add-content $LogPath\$Logfile -value $logstring
|
||||
Write-Host $logstring
|
||||
}
|
||||
|
||||
Function CheckPath
|
||||
{
|
||||
Test-Path ()
|
||||
}
|
||||
|
||||
# Überprüfen ob Logpfad angelegt ist, wenn nicht vorhanden, wird er angelegt.
|
||||
|
||||
|
||||
# Eigentlicher Programmstart.
|
||||
|
||||
Sub Main
|
||||
|
||||
LogWrite "Programmstart am $(Get-Date -Format dd.MM.yyyy) um $(Get-Date -Format hh.mm.ss) auf $env:COMPUTERNAME."
|
||||
LogWrite "Die Ausführung erfolgt unter dem Konto: $env:USERDNSDOMAIN\$env:USERNAME."
|
||||
|
||||
|
||||
|
||||
End Sub
|
||||
|
||||
# Löschen alter Log-Dateien.
|
||||
|
||||
get-childitem “$LogPath ” | where {$_.lastwritetime -lt $LogEntfernen -and -not $_.psiscontainer} |% {remove-item $_.fullname -force -verbose }
|
||||
BIN
test/array-test1.ps1
Normal file
BIN
test/array-test1.ps1
Normal file
Binary file not shown.
481
test/cleanup-disk.ps1
Normal file
481
test/cleanup-disk.ps1
Normal file
@@ -0,0 +1,481 @@
|
||||
<#----------------------------------------------------------------------------
|
||||
LEGAL DISCLAIMER
|
||||
This Sample Code is provided for the purpose of illustration only and is not
|
||||
intended to be used in a production environment. THIS SAMPLE CODE AND ANY
|
||||
RELATED INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER
|
||||
EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. We grant You a
|
||||
nonexclusive, royalty-free right to use and modify the Sample Code and to
|
||||
reproduce and distribute the object code form of the Sample Code, provided
|
||||
that You agree: (i) to not use Our name, logo, or trademarks to market Your
|
||||
software product in which the Sample Code is embedded; (ii) to include a valid
|
||||
copyright notice on Your software product in which the Sample Code is embedded;
|
||||
and (iii) to indemnify, hold harmless, and defend Us and Our suppliers from and
|
||||
against any claims or lawsuits, including attorneys’ fees, that arise or result
|
||||
from the use or distribution of the Sample Code.
|
||||
|
||||
This posting is provided "AS IS" with no warranties, and confers no rights. Use
|
||||
of included script samples are subject to the terms specified
|
||||
at http://www.microsoft.com/info/cpyright.htm.
|
||||
|
||||
|
||||
Author: Tom Moser, PFE
|
||||
Date: 5/13/2014
|
||||
|
||||
Version 1.0
|
||||
-Initial Release
|
||||
|
||||
Usage: .\Cleanup-Disk.Ps1 [-NoReboot] [-LogPath <String>]
|
||||
|
||||
Switch: NoReboot - Specify this switch ONLY if you DO NOT want the server to reboot
|
||||
post update. It is recommendend that you do NOT use this switch.
|
||||
|
||||
LogPath - Specify this parameter with a log location to write out the script log.
|
||||
Will default to log.txt in the script directory.
|
||||
|
||||
Notes: In order to schedule the script successfully, the name must remain Cleanup-Disk.ps1.
|
||||
The log file will contain all relevent information - no console output should be expected.
|
||||
|
||||
Summary:
|
||||
This script requires KB2852386.
|
||||
|
||||
The script itself will perform the following:
|
||||
-Verify the KB is installed
|
||||
-Install the Desktop Experience feature
|
||||
-Install a scheduled task that restarts the script 60 seconds after reboot
|
||||
-Reboot, if necessary
|
||||
-Update registry keys for cleanmgr.exe to run.
|
||||
-Run cleanmgr.exe
|
||||
-Reboot
|
||||
-Remove Desktop Experience
|
||||
-Reboot
|
||||
-Remove scheduled task
|
||||
-Exit
|
||||
|
||||
-----------------------------------------------------------------------------#>
|
||||
|
||||
Param([string]$LogPath="$(join-path $(split-path -parent $MyInvocation.MyCommand.Definition) log.txt)",
|
||||
[switch]$NoReboot=$false)
|
||||
|
||||
|
||||
if((get-hotfix KB2852386).InstalledOn -eq $null)
|
||||
{
|
||||
Write-Error "KB2862386 is required for script. Please install hotfix and re-run."
|
||||
Exit
|
||||
}
|
||||
|
||||
|
||||
#Reg Paths/Vars
|
||||
Set-Variable -Name ScriptRegKey -Value "HKLM:\Software\WinSXSCleanup" -Option Constant
|
||||
Set-Variable -Name ScriptRegValueName -Value "Phase" -Option Constant
|
||||
Set-Variable -Name ScriptSageValueName -Value "SageSet" -Option Constant
|
||||
Set-Variable -Name ScriptSpaceBeforeValue -Value "SpaceBefore" -Option Constant
|
||||
Set-Variable -Name SchTaskName -Value "CleanMgr Task Cleanup" -Option Constant
|
||||
Set-Variable -Name ScriptDEStatusatStart -Value "DEInstalledAtStart" -Option Constant
|
||||
Set-Variable -Name UpdateCleanupPath -value "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Update Cleanup" -Option Constant
|
||||
Set-Variable -Name ServicePackCleanupPath -Value "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches\Service Pack Cleanup" -Option Constant
|
||||
Set-Variable -Name VolumeCachesPath -Value "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches" -Option Constant
|
||||
Set-Variable -Name StateFlagClean -Value 2 -Option Constant
|
||||
Set-Variable -Name StateFlagNoAction -Value 0 -Option Constant
|
||||
|
||||
$ScriptPath = split-path -parent $MyInvocation.MyCommand.Definition
|
||||
|
||||
#Phase Constants
|
||||
Set-Variable -Name PhaseInit -Value -1 -Option Constant
|
||||
Set-Variable -Name PhaseStarted -Value 0 -Option Constant
|
||||
Set-Variable -Name PhaseDEInstalled -Value 1 -Option Constant
|
||||
Set-Variable -Name PhaseSageSetComplete -Value 2 -Option Constant
|
||||
Set-Variable -Name PhaseSageRunStarted -Value 3 -Option Constant
|
||||
Set-Variable -Name PhaseSageRunComplete -Value 4 -Option Constant
|
||||
Set-Variable -Name PhaseDERemoved -Value 5 -Option Constant
|
||||
Set-Variable -Name PhaseTaskRemoved -Value 6 -Option Constant
|
||||
|
||||
#import-module
|
||||
Import-Module ServerManager
|
||||
|
||||
#read state value, use switch statement
|
||||
|
||||
Function DateStamp
|
||||
{
|
||||
return "$(Get-Date -UFormat %Y%m%d-%H%M%S):"
|
||||
}
|
||||
|
||||
Function LogEntry([string]$LogData)
|
||||
{
|
||||
Add-Content $LogPath "$(DateStamp) $LogData"
|
||||
}
|
||||
|
||||
Function GetCurrentState
|
||||
{
|
||||
return (Get-ItemProperty -Path $ScriptRegKey -Name $ScriptRegValueName -ErrorAction SilentlyContinue).Phase
|
||||
}
|
||||
|
||||
Function CreateScheduledTask
|
||||
{
|
||||
Param([string]$ScriptPath,
|
||||
[string]$TaskName,
|
||||
[string]$fLogPath,
|
||||
[string]$fNoReboot=$false)
|
||||
try
|
||||
{
|
||||
$Scheduler = New-Object -ComObject "Schedule.Service"
|
||||
$Scheduler.Connect("Localhost")
|
||||
$root = $Scheduler.GetFolder("\")
|
||||
$newTask = $Scheduler.NewTask(0)
|
||||
$newTask.RegistrationInfo.Author = $TaskName
|
||||
$newTask.RegistrationInfo.Description = ""
|
||||
$newtask.Settings.StartWhenAvailable = $true
|
||||
$trigger = $newTask.Triggers.Create(8) #Trigger at boot
|
||||
$trigger.Delay = "PT60S"
|
||||
$trigger.Id = "LogonTriggerId"
|
||||
$newTask.Principal.UserId = "NT AUTHORITY\SYSTEM"
|
||||
$newTask.Principal.RunLevel = 1
|
||||
$newTask.Principal.LogonType = 5
|
||||
|
||||
$action = $newtask.Actions.Create(0)
|
||||
$action.Path = "C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe"
|
||||
|
||||
if($fNoReboot -eq $true)
|
||||
{
|
||||
$action.Arguments = "-command $(join-path $ScriptPath cleanup-disk.ps1) -LogPath $fLogPath -NoReboot -NonInteractive -NoLogo -Version 2"
|
||||
}
|
||||
else
|
||||
{
|
||||
$action.Arguments = "-command $(join-path $ScriptPath cleanup-disk.ps1) -LogPath $fLogPath -NonInteractive -NoLogo -Version 2"
|
||||
}
|
||||
|
||||
$root.RegisterTaskDefinition("CleanMgr Cleanup Task", $newTask, 6, "NT AUTHORITY\SYSTEM", $null , 4)
|
||||
}
|
||||
catch
|
||||
{
|
||||
LogEntry "Failed to register scheduled task."
|
||||
LogEntry $Error[0].Exception
|
||||
throw "Failed to register scheduled task..."
|
||||
}
|
||||
}
|
||||
Function DeleteScheduledTask
|
||||
{
|
||||
Param([string]$TaskName)
|
||||
c:\windows\system32\schtasks.exe /delete /TN "CleanMgr Cleanup Task" /f
|
||||
}
|
||||
|
||||
if(Test-Path $ScriptRegKey)
|
||||
{
|
||||
$CurrentState = GetCurrentState
|
||||
}
|
||||
else
|
||||
{
|
||||
$CurrentState = $PhaseInit
|
||||
}
|
||||
|
||||
|
||||
|
||||
LogEntry "CurrentState: $CurrentState"
|
||||
LogEntry "NoReboot Flag: $NoReboot"
|
||||
|
||||
do
|
||||
{
|
||||
LogEntry "**** Current State: $CurrentState"
|
||||
|
||||
#Evalute current state against all possibilities.
|
||||
Switch($CurrentState)
|
||||
{
|
||||
|
||||
$PhaseInit
|
||||
{
|
||||
LogEntry "Switch: Null"
|
||||
|
||||
try
|
||||
{
|
||||
#Calculate and log freespace
|
||||
$FreeSpace = (Get-WmiObject win32_logicaldisk | where { $_.DeviceID -eq $env:SystemDrive }).FreeSpace
|
||||
if((Test-Path $ScriptRegKey) -eq $false)
|
||||
{
|
||||
New-Item -Path $ScriptRegKey
|
||||
}
|
||||
Set-ItemProperty -Path $ScriptRegKey -Name $ScriptSpaceBeforeValue -Value $FreeSpace
|
||||
LogEntry "PhaseInit: Current Free Space: $([Math]::Round(($FreeSpace / 1GB),2))GB"
|
||||
|
||||
#Check to see if DE is already installed.
|
||||
#If yes, set reg key to 1, else 0. Used to prevent DE from uninstalling unintentionally.
|
||||
if((Get-WindowsFeature Desktop-Experience).Installed -eq $true)
|
||||
{
|
||||
Set-ItemProperty -Path $ScriptRegKey -name $ScriptDEStatusAtStart -Value 1
|
||||
}
|
||||
else
|
||||
{
|
||||
Set-ItemProperty -Path $ScriptRegKey -name $ScriptDEStatusAtStart -Value 0
|
||||
}
|
||||
|
||||
#Start Installing DE
|
||||
LogEntry "Feature: Installing Desktop Experience."
|
||||
$FeatureResult = Add-WindowsFeature Desktop-Experience
|
||||
LogEntry "PhaseInit: Feature: ExitCode: $($FeatureResult.ExitCode)"
|
||||
LogEntry "PhaseInit: Feature: RestartRequired: $($FeatureResult.RestartNeeded)"
|
||||
LogEntry "PhaseInit: Feature: Success: $($FeatureResult.Success)"
|
||||
|
||||
#If DE fails, throw error.
|
||||
if($FeatureResult.Success -eq $false -and $FeatureResult.RestartNeeded -eq "No")
|
||||
{
|
||||
throw "PhaseInit: Failed to install Desktop Experience. This is a required feature for WinSXS Cleanup."
|
||||
}
|
||||
|
||||
#If DE exists with no change needed or success, update reg keys. Reboot if required. Create task.
|
||||
elseif($FeatureResult.ExitCode -eq "NoChangeNeeded" -or ($FeatureResult.Success))
|
||||
{
|
||||
LogEntry "PhaseInit: Feature: Desktop Experience Installed. Updating $ScriptRegKey\$ScriptRegValueName to $PhaseStarted"
|
||||
#New-Item $ScriptRegKey -Force
|
||||
New-ItemProperty -Path $ScriptRegKey -Name $ScriptRegValueName -Value $PhaseStarted -Force
|
||||
|
||||
if($NoReboot -eq $false -and $FeatureResult.RestartNeeded -eq "Yes")
|
||||
{
|
||||
LogEntry "PhastInit: Creating Scheduled Task..."
|
||||
CreateScheduledTask -ScriptPath $ScriptPath -TaskName $SchTaskName -fLogPath $LogPath
|
||||
LogEntry "PhaseInit: Created Scheduled Task $SchTaskName"
|
||||
$CurrentState = GetCurrentState
|
||||
Restart-Computer
|
||||
Sleep 10
|
||||
}
|
||||
elseif($FeatureResult.ExitCode -eq "NoChangeNeeded")
|
||||
{
|
||||
LogEntry "DE Already Installed. No reboot required."
|
||||
LogEntry "PhastInit: Creating Scheduled Task..."
|
||||
CreateScheduledTask -ScriptPath "$ScriptPath" -TaskName $SchTaskName -fLogPath $LogPath -fNoReboot "`$$NoReboot"
|
||||
LogEntry "PhaseInit: Created Scheduled Task $SchTaskName"
|
||||
|
||||
$CurrentState = GetCurrentState
|
||||
}
|
||||
else
|
||||
{
|
||||
CreateScheduledTask -ScriptPath "$ScriptPath" -TaskName $SchTaskName -fLogPath $LogPath -fNoReboot "`$$NoReboot"
|
||||
LogEntry "Phaseinit: Restart switch not specified. Please manually reboot the server to continue cleanup."
|
||||
Exit
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
catch
|
||||
{
|
||||
LogEntry $error[0]
|
||||
exit
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
$PhaseStarted
|
||||
{
|
||||
LogEntry "PhaseStarted: Verifying DE installation..."
|
||||
if((Get-WindowsFeature Desktop-Experience).Installed -eq $true) #check for pending reboot
|
||||
{
|
||||
LogEntry "PhaseStarted: DE Installed. Moving to PhaseDEInstalled."
|
||||
Set-ItemProperty -Path $ScriptRegKey -Name $ScriptRegValueName -Value $PhaseDEInstalled
|
||||
}
|
||||
Else
|
||||
{
|
||||
LogEntry "PhaseStarted: DE not installed. Resetting phase to null."
|
||||
New-ItemProperty -Path $ScriptRegKey -Name $ScriptRegValueName -Value $null
|
||||
}
|
||||
|
||||
$CurrentState = GetCurrentState
|
||||
break
|
||||
}
|
||||
|
||||
$PhaseDEInstalled
|
||||
{
|
||||
try
|
||||
{
|
||||
LogEntry "PhaseDEInstalled: Starting PhaseDEInstalled..."
|
||||
LogEntry "PhaseDEInstalled: Setting SagetSet..."
|
||||
#use static SageSet Value. Insert in to registry.
|
||||
$SageSet = "0010"
|
||||
Set-Variable -Name StateFlags -Value "StateFlags$SageSet" -Option Constant
|
||||
LogEntry "PhaseDEInstalled: SageSet complete."
|
||||
LogEntry "PhaseDEInstalled: Setting VolumeCaches reg keys..."
|
||||
#Set all VolumeCache keys to StateFlags = 0 to prevent cleanup. After, set the proper keys to 2 to allow cleanup.
|
||||
$SubKeys = Get-Childitem HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\VolumeCaches
|
||||
Foreach ($Key in $SubKeys)
|
||||
{
|
||||
Set-ItemProperty -Path $Key.PSPath -Name $StateFlags -Value $StateFlagNoAction
|
||||
}
|
||||
|
||||
LogEntry "PhaseDEInstalled: VolumeCaches keys set."
|
||||
LogEntry "PhaseDEInstalled: Setting UPdate and Service Pack Keys..."
|
||||
#Set all script reg values for persistence through reboots.
|
||||
Set-ItemProperty -Path $ScriptRegKey -Name $ScriptSageValueName -Value $SageSet
|
||||
Set-ItemProperty -Path $UpdateCleanUpPath -Name $StateFlags -Value $StateFlagClean
|
||||
Set-ItemProperty -Path $ServicePackCleanUpPath -Name $StateFlags -Value $StateFlagClean
|
||||
LogEntry "PhaseDEInstalled: Done."
|
||||
|
||||
#Update state key
|
||||
Set-ItemProperty -Path $ScriptRegKey -Name $ScriptRegValueName -Value $PhaseSageSetComplete
|
||||
$CurrentState = GetCurrentState
|
||||
LogEntry "PhaseDEInstalled: Complete."
|
||||
}
|
||||
|
||||
catch
|
||||
{
|
||||
LogEntry "PhaseDEInstalled: Failed to update reg keys."
|
||||
LogEntry $Error[0].Exception
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
$PhaseSageSetComplete
|
||||
{
|
||||
LogEntry "PhaseSageSetComplete: Starting cleanmgr."
|
||||
try
|
||||
{
|
||||
$SageSet = (Get-ItemProperty -Path $ScriptRegKey -Name $ScriptSageValueName).SageSet
|
||||
|
||||
LogEntry "PhaseSageSetComplete: CleanMgr.exe running... "
|
||||
$StartTime = Get-Date
|
||||
&"C:\Windows\System32\Cleanmgr.exe" + " /sagerun:$SageSet"
|
||||
Wait-Process cleanmgr
|
||||
$EndTime = Get-Date
|
||||
LogEntry "PhaseSageSetComplete: CleanMgr.exe complete..."
|
||||
LogEntry "PhaseSageSetComplete: Seconds Elapsed: $((New-TimeSpan $StartTime $EndTime).TotalSeconds)"
|
||||
LogEntry "PhaseSageSetComplete: Updating State..."
|
||||
Set-ItemProperty -Path $ScriptRegKey -Name $ScriptRegValueName -Value $PhaseSageRunComplete
|
||||
$CurrentState = GetCurrentState
|
||||
LogEntry "PhaseSageSetComplete: Complete."
|
||||
}
|
||||
|
||||
catch
|
||||
{
|
||||
LogEntry "PhaseSageSetComplete: ERROR."
|
||||
LogEntry $Error[0].Exception
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
$PhaseSageRunComplete
|
||||
{
|
||||
try
|
||||
{
|
||||
$DEStatusInit = (Get-ItemProperty -Path $ScriptRegKey -Name $ScriptDEStatusAtStart)."$ScriptDEStatusAtStart"
|
||||
LogEntry "PhaseSageRunComplete: Starting PhaseSageRunComplete."
|
||||
LogEntry "PhaseSageRunComplete: Getting DE Status."
|
||||
|
||||
$DEStatus = (Get-WindowsFeature Desktop-Experience).Installed
|
||||
|
||||
LogEntry "PhaseSageRunComplete: DEInstalled = $DEStatus"
|
||||
LogEntry "PhaseSageRunComplete: DEStatus at Start was $DEStatusInit"
|
||||
|
||||
if($DEStatusInit -eq 1)
|
||||
{
|
||||
LogEntry "PhaseSageRunComplete: DE removal not required. Continuing..."
|
||||
Set-ItemProperty -Path $ScriptRegKey -Name $ScriptRegValueName -Value $PhaseDERemoved
|
||||
$CurrentState = GetCurrentState
|
||||
Continue
|
||||
}
|
||||
|
||||
#remove DE
|
||||
if($DEStatus -eq $true)
|
||||
{
|
||||
LogEntry "PhaseSageRunComplete: Removing DE"
|
||||
$FeatureResult = Remove-WindowsFeature Desktop-Experience
|
||||
|
||||
if($NoReboot -eq $false -and $FeatureResult.Success -and $FeatureResult.RestartNeeded -eq "Yes")
|
||||
{
|
||||
LogEntry "PhaseSageRunComplete: Result: $($FeatureResult.Success)"
|
||||
LogEntry "PhaseSageRunComplete: RestartNeeded: $($FeatureResult.RestartNeeded)"
|
||||
|
||||
LogEntry "PhaseSageRunComplete: Feature removed successfully."
|
||||
LogEntry "PhaseSageRunComplete: Rebooting..."
|
||||
Restart-Computer -Force
|
||||
Sleep 10
|
||||
}
|
||||
elseif(($NoReboot -eq $false) -and ($FeatureResult.Success -eq $false) -and ($FeatureResult.RestartNeeded -eq "Yes"))
|
||||
{
|
||||
LogEntry "PhaseSageRunComplete: Result: $($FeatureResult.Success)"
|
||||
LogEntry "PhaseSageRunComplete: RestartNeeded: $($FeatureResult.RestartNeeded)"
|
||||
LogEntry "PhaseSageRunComplete: Reboot already pending. Rebooting..."
|
||||
LogEntry "PhaseSageRunComplete: Rebooting..."
|
||||
Restart-Computer -Force
|
||||
Sleep 10
|
||||
}
|
||||
Else
|
||||
{
|
||||
LogEntry "PhaseSageRunComplete: Result: $($FeatureResult.Success)"
|
||||
LogEntry "PhaseSageRunComplete: RestartNeeded: $($FeatureResult.RestartNeeded)"
|
||||
LogEntry "Reboot Required: *** MANUAL REBOOT REQUIRED ***"
|
||||
Exit
|
||||
}
|
||||
}
|
||||
elseif($DEStatus -eq $false)
|
||||
{
|
||||
#DE removed, update status
|
||||
LogEntry "PhaseSageRunComplete: DE Removed. Updating status..."
|
||||
Set-ItemProperty -Path $ScriptRegKey -Name $ScriptRegValueName -Value $PhaseDERemoved
|
||||
}
|
||||
else
|
||||
{
|
||||
LogEntry "PhaseSageRunComplete: ERROR."
|
||||
LogEntry $Error[0].Exception
|
||||
}
|
||||
$CurrentState = GetCurrentState
|
||||
|
||||
}
|
||||
|
||||
catch
|
||||
{
|
||||
LogEntry "PhaseSageRunComplete: Caught Exception."
|
||||
LogEntry "$($Error[0].Exception)"
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
$PhaseDERemoved
|
||||
{
|
||||
try
|
||||
{
|
||||
#Retrieving initial space
|
||||
$SpaceAtStart = (Get-ItemProperty -Path $ScriptRegKey -Name $ScriptSpaceBeforeValue)."$ScriptSpaceBeforeValue"
|
||||
|
||||
#remove reg key
|
||||
LogEntry "PhaseDERemoved: Removing Script Reg Key."
|
||||
Remove-Item $ScriptRegKey
|
||||
$CurrentState = $PhaseTaskRemoved
|
||||
}
|
||||
|
||||
catch
|
||||
{
|
||||
LogEntry "PhaseDERemoved: ERROR."
|
||||
LogEntry $Error[0].Exception
|
||||
}
|
||||
break
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
#Prevents infinite loops consuming resources.
|
||||
Sleep 1
|
||||
|
||||
} until ($CurrentState -eq $PhaseTaskRemoved)
|
||||
|
||||
if($CurrentState -eq $PhaseTaskRemoved)
|
||||
{
|
||||
try
|
||||
{
|
||||
LogEntry "PhaseTaskRemoved: Removing Scheduled Task"
|
||||
DeleteScheduledTask -TaskName $SchTaskName
|
||||
LogEntry "PhaseTaskRemoved: Scheduled Task Deleted."
|
||||
LogEntry "PhaseTaskRemoved: Script Complete."
|
||||
|
||||
$CurrentSpace = (Get-WmiObject win32_logicaldisk | where { $_.DeviceID -eq $env:SystemDrive }).FreeSpace
|
||||
LogEntry "PhaseTaskRemoved: Current Disk Space: $([Math]::Round(($CurrentSpace / 1GB),2)) GB"
|
||||
|
||||
$Savings = [Math]::Round(((($CurrentSpace / $SpaceAtStart) - 1) * 100),2)
|
||||
|
||||
$message = @"
|
||||
****** CleanMgr complete.
|
||||
****** Starting Free Space: $SpaceAtStart
|
||||
****** Current Free Space: $CurrentSpace
|
||||
****** Savings: $Savings%
|
||||
****** Exiting.
|
||||
"@
|
||||
|
||||
LogEntry $message
|
||||
}
|
||||
BIN
test/clear.ps1
Normal file
BIN
test/clear.ps1
Normal file
Binary file not shown.
191
test/create_ad_users.ps1
Normal file
191
test/create_ad_users.ps1
Normal file
@@ -0,0 +1,191 @@
|
||||
###########################################################
|
||||
# AUTHOR : Marius / Hican - http://www.hican.nl - @hicannl
|
||||
# DATE : 26-04-2012
|
||||
# EDIT : 07-08-2014
|
||||
# COMMENT : This script creates new Active Directory users,
|
||||
# including different kind of properties, based
|
||||
# on an input_create_ad_users.csv.
|
||||
# VERSION : 1.3
|
||||
###########################################################
|
||||
|
||||
# CHANGELOG
|
||||
# Version 1.2: 15-04-2014 - Changed the code for better
|
||||
# - Added better Error Handling and Reporting.
|
||||
# - Changed input file with more logical headers.
|
||||
# - Added functionality for account Enabled,
|
||||
# PasswordNeverExpires, ProfilePath, ScriptPath,
|
||||
# HomeDirectory and HomeDrive
|
||||
# - Added the option to move every user to a different OU.
|
||||
# Version 1.3: 08-07-2014
|
||||
# - Added functionality for ProxyAddresses
|
||||
|
||||
# ERROR REPORTING ALL
|
||||
Set-StrictMode -Version latest
|
||||
|
||||
#----------------------------------------------------------
|
||||
# LOAD ASSEMBLIES AND MODULES
|
||||
#----------------------------------------------------------
|
||||
Try
|
||||
{
|
||||
Import-Module ActiveDirectory -ErrorAction Stop
|
||||
}
|
||||
Catch
|
||||
{
|
||||
Write-Host "[ERROR]`t ActiveDirectory Module couldn't be loaded. Script will stop!"
|
||||
Exit 1
|
||||
}
|
||||
|
||||
#----------------------------------------------------------
|
||||
#STATIC VARIABLES
|
||||
#----------------------------------------------------------
|
||||
$path = Split-Path -parent $MyInvocation.MyCommand.Definition
|
||||
$newpath = $path + "\import_create_ad_users.csv"
|
||||
$log = $path + "\create_ad_users.log"
|
||||
$date = Get-Date
|
||||
$addn = (Get-ADDomain).DistinguishedName
|
||||
$dnsroot = (Get-ADDomain).DNSRoot
|
||||
$i = 1
|
||||
|
||||
#----------------------------------------------------------
|
||||
#START FUNCTIONS
|
||||
#----------------------------------------------------------
|
||||
Function Start-Commands
|
||||
{
|
||||
Create-Users
|
||||
}
|
||||
|
||||
Function Create-Users
|
||||
{
|
||||
"Processing started (on " + $date + "): " | Out-File $log -append
|
||||
"--------------------------------------------" | Out-File $log -append
|
||||
Import-CSV $newpath | ForEach-Object {
|
||||
If (($_.Implement.ToLower()) -eq "yes")
|
||||
{
|
||||
If (($_.GivenName -eq "") -Or ($_.LastName -eq "") -Or ($_.Initials -eq ""))
|
||||
{
|
||||
Write-Host "[ERROR]`t Please provide valid GivenName, LastName and Initials. Processing skipped for line $($i)`r`n"
|
||||
"[ERROR]`t Please provide valid GivenName, LastName and Initials. Processing skipped for line $($i)`r`n" | Out-File $log -append
|
||||
}
|
||||
Else
|
||||
{
|
||||
# Set the target OU
|
||||
$location = $_.TargetOU + ",$($addn)"
|
||||
|
||||
# Set the Enabled and PasswordNeverExpires properties
|
||||
If (($_.Enabled.ToLower()) -eq "true") { $enabled = $True } Else { $enabled = $False }
|
||||
If (($_.PasswordNeverExpires.ToLower()) -eq "true") { $expires = $True } Else { $expires = $False }
|
||||
|
||||
# A check for the country, because those were full names and need
|
||||
# to be land codes in order for AD to accept them. I used Netherlands
|
||||
# as example
|
||||
If($_.Country -eq "Netherlands")
|
||||
{
|
||||
$_.Country = "NL"
|
||||
}
|
||||
Else
|
||||
{
|
||||
$_.Country = "EN"
|
||||
}
|
||||
# Replace dots / points (.) in names, because AD will error when a
|
||||
# name ends with a dot (and it looks cleaner as well)
|
||||
$replace = $_.Lastname.Replace(".","")
|
||||
If($replace.length -lt 4)
|
||||
{
|
||||
$lastname = $replace
|
||||
}
|
||||
Else
|
||||
{
|
||||
$lastname = $replace.substring(0,4)
|
||||
}
|
||||
# Create sAMAccountName according to this 'naming convention':
|
||||
# <FirstLetterInitials><FirstFourLettersLastName> for example
|
||||
# htehp
|
||||
$sam = $_.Initials.substring(0,1).ToLower() + $lastname.ToLower()
|
||||
Try { $exists = Get-ADUser -LDAPFilter "(sAMAccountName=$sam)" }
|
||||
Catch { }
|
||||
If(!$exists)
|
||||
{
|
||||
# Set all variables according to the table names in the Excel
|
||||
# sheet / import CSV. The names can differ in every project, but
|
||||
# if the names change, make sure to change it below as well.
|
||||
$setpass = ConvertTo-SecureString -AsPlainText $_.Password -force
|
||||
|
||||
Try
|
||||
{
|
||||
Write-Host "[INFO]`t Creating user : $($sam)"
|
||||
"[INFO]`t Creating user : $($sam)" | Out-File $log -append
|
||||
New-ADUser $sam -GivenName $_.GivenName -Initials $_.Initials `
|
||||
-Surname $_.LastName -DisplayName ($_.LastName + "," + $_.Initials + " " + $_.GivenName) `
|
||||
-Office $_.OfficeName -Description $_.Description -EmailAddress $_.Mail `
|
||||
-StreetAddress $_.StreetAddress -City $_.City -State $_.State `
|
||||
-PostalCode $_.PostalCode -Country $_.Country -UserPrincipalName ($sam + "@" + $dnsroot) `
|
||||
-Company $_.Company -Department $_.Department -EmployeeID $_.EmployeeID `
|
||||
-Title $_.Title -OfficePhone $_.Phone -AccountPassword $setpass -Manager $_.Manager `
|
||||
-profilePath $_.ProfilePath -scriptPath $_.ScriptPath -homeDirectory $_.HomeDirectory `
|
||||
-homeDrive $_.homeDrive -Enabled $enabled -PasswordNeverExpires $expires
|
||||
Write-Host "[INFO]`t Created new user : $($sam)"
|
||||
"[INFO]`t Created new user : $($sam)" | Out-File $log -append
|
||||
|
||||
$dn = (Get-ADUser $sam).DistinguishedName
|
||||
# Set an ExtensionAttribute
|
||||
If ($_.ExtensionAttribute1 -ne "" -And $_.ExtensionAttribute1 -ne $Null)
|
||||
{
|
||||
$ext = [ADSI]"LDAP://$dn"
|
||||
$ext.Put("extensionAttribute1", $_.ExtensionAttribute1)
|
||||
Try { $ext.SetInfo() }
|
||||
Catch { Write-Host "[ERROR]`t Couldn't set the Extension Attribute : $($_.Exception.Message)" }
|
||||
}
|
||||
|
||||
# Set ProxyAdresses
|
||||
Try { $dn | Set-ADUser -Add @{proxyAddresses = ($_.ProxyAddresses -split ";")} -ErrorAction Stop }
|
||||
Catch { Write-Host "[ERROR]`t Couldn't set the ProxyAddresses Attributes : $($_.Exception.Message)" }
|
||||
|
||||
# Move the user to the OU ($location) you set above. If you don't
|
||||
# want to move the user(s) and just create them in the global Users
|
||||
# OU, comment the string below
|
||||
If ([adsi]::Exists("LDAP://$($location)"))
|
||||
{
|
||||
Move-ADObject -Identity $dn -TargetPath $location
|
||||
Write-Host "[INFO]`t User $sam moved to target OU : $($location)"
|
||||
"[INFO]`t User $sam moved to target OU : $($location)" | Out-File $log -append
|
||||
}
|
||||
Else
|
||||
{
|
||||
Write-Host "[ERROR]`t Targeted OU couldn't be found. Newly created user wasn't moved!"
|
||||
"[ERROR]`t Targeted OU couldn't be found. Newly created user wasn't moved!" | Out-File $log -append
|
||||
}
|
||||
|
||||
# Rename the object to a good looking name (otherwise you see
|
||||
# the 'ugly' shortened sAMAccountNames as a name in AD. This
|
||||
# can't be set right away (as sAMAccountName) due to the 20
|
||||
# character restriction
|
||||
$newdn = (Get-ADUser $sam).DistinguishedName
|
||||
Rename-ADObject -Identity $newdn -NewName ($_.GivenName + " " + $_.LastName)
|
||||
Write-Host "[INFO]`t Renamed $($sam) to $($_.GivenName) $($_.LastName)`r`n"
|
||||
"[INFO]`t Renamed $($sam) to $($_.GivenName) $($_.LastName)`r`n" | Out-File $log -append
|
||||
}
|
||||
Catch
|
||||
{
|
||||
Write-Host "[ERROR]`t Oops, something went wrong: $($_.Exception.Message)`r`n"
|
||||
}
|
||||
}
|
||||
Else
|
||||
{
|
||||
Write-Host "[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!`r`n"
|
||||
"[SKIP]`t User $($sam) ($($_.GivenName) $($_.LastName)) already exists or returned an error!" | Out-File $log -append
|
||||
}
|
||||
}
|
||||
}
|
||||
Else
|
||||
{
|
||||
Write-Host "[SKIP]`t User ($($_.GivenName) $($_.LastName)) will be skipped for processing!`r`n"
|
||||
"[SKIP]`t User ($($_.GivenName) $($_.LastName)) will be skipped for processing!" | Out-File $log -append
|
||||
}
|
||||
$i++
|
||||
}
|
||||
"--------------------------------------------" + "`r`n" | Out-File $log -append
|
||||
}
|
||||
|
||||
Write-Host "STARTED SCRIPT`r`n"
|
||||
Start-Commands
|
||||
Write-Host "STOPPED SCRIPT"
|
||||
1105
test/deleteold.ps1
Normal file
1105
test/deleteold.ps1
Normal file
File diff suppressed because it is too large
Load Diff
2
test/for-loop.ps1
Normal file
2
test/for-loop.ps1
Normal file
@@ -0,0 +1,2 @@
|
||||
for ($i=1; $i -le 5; $i++)
|
||||
{Write-Host $i}
|
||||
2
test/ipconfig.ps1
Normal file
2
test/ipconfig.ps1
Normal file
@@ -0,0 +1,2 @@
|
||||
$ipconfig = ipconfig | select-string "IPv4" | select-object -first 1
|
||||
([regex]"\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b").matches($ipconfig) | % { $_.value }
|
||||
BIN
test/json_test.ps1
Normal file
BIN
test/json_test.ps1
Normal file
Binary file not shown.
17
test/mailtest-mc2.ps1
Normal file
17
test/mailtest-mc2.ps1
Normal file
@@ -0,0 +1,17 @@
|
||||
Remove-Variable * -ErrorAction SilentlyContinue
|
||||
cls
|
||||
$Error.Clear()
|
||||
$secpasswd = ConvertTo-SecureString "didalog" -AsPlainText -Force
|
||||
$mycreds = New-Object System.Management.Automation.PSCredential("digitaldata@mc2.local", $secpasswd)
|
||||
|
||||
Try {
|
||||
|
||||
Send-MailMessage -From "digitaldata@mc-2.de" -To "m.kamm@didalog.de" -Subject "test1" -SmtpServer "mc2-vmx01-com01.mc2.local" -Port 25 -UseSsl:$true -Credential $mycreds -encoding ([System.Text.Encoding]::UTF8) -ErrorAction Stop
|
||||
|
||||
} #end try
|
||||
|
||||
Catch {
|
||||
|
||||
$Error
|
||||
|
||||
} #end catch
|
||||
BIN
test/powershell-gui-dialogs.ps1
Normal file
BIN
test/powershell-gui-dialogs.ps1
Normal file
Binary file not shown.
BIN
test/sqltest.ps1
Normal file
BIN
test/sqltest.ps1
Normal file
Binary file not shown.
BIN
test/sqltest2.ps1
Normal file
BIN
test/sqltest2.ps1
Normal file
Binary file not shown.
61
test/test.cmd
Normal file
61
test/test.cmd
Normal file
@@ -0,0 +1,61 @@
|
||||
@echo off
|
||||
|
||||
@echo off
|
||||
|
||||
VER |find /i "Windows 95" >NUL
|
||||
IF NOT ERRORLEVEL 1 GOTO 9598ME
|
||||
VER |find /i "Windows 98" >NUL
|
||||
IF NOT ERRORLEVEL 1 GOTO 9598ME
|
||||
VER |find /i "Windows Millennium" >NUL
|
||||
IF NOT ERRORLEVEL 1 GOTO 9598ME
|
||||
VER | find "XP" > nul
|
||||
IF %errorlevel% EQU 0 GOTO XP
|
||||
VER | find "Microsoft Windows 2000" > NUL
|
||||
IF %errorlevel% EQU 0 GOTO 2000
|
||||
VER | find "NT" > nul
|
||||
IF %errorlevel% EQU 0 GOTO NT
|
||||
VER | find "Microsoft Windows [Version 6.1" > nul
|
||||
IF %errorlevel% EQU 0 GOTO Sieben
|
||||
VER | find "Microsoft Windows [Version 6" > nul
|
||||
IF %errorlevel% EQU 0 GOTO Vista
|
||||
VER | find "Microsoft Windows [Version 5" > nul
|
||||
IF %errorlevel% EQU 0 GOTO 2003
|
||||
goto unknown
|
||||
goto end
|
||||
|
||||
:unknown
|
||||
echo MsgBox "Betriebssystem unbekannt", VbInformation + VbOKOnly, "Ihr Betriebssystem" >%TEMP%\os.vbs
|
||||
goto end
|
||||
|
||||
:9598ME
|
||||
echo MsgBox "Sie benutzten 95, 98 oder ME", VbInformation + VbOKOnly, "Ihr Betriebssystem" >%TEMP%\os.vbs
|
||||
goto end
|
||||
|
||||
:NT
|
||||
echo MsgBox "Sie benutzten Windows NT", VbInformation + VbOKOnly, "Ihr Betriebssystem" >%TEMP%\os.vbs
|
||||
goto end
|
||||
|
||||
:2003
|
||||
echo MsgBox "Sie benutzten Windows 2003", VbInformation + VbOKOnly, "Ihr Betriebssystem" >%TEMP%\os.vbs
|
||||
goto end
|
||||
|
||||
:2000
|
||||
echo MsgBox "Sie benutzten Windows 2000", VbInformation + VbOKOnly, "Ihr Betriebssystem" >%TEMP%\os.vbs
|
||||
goto end
|
||||
|
||||
:XP
|
||||
echo MsgBox "Sie benutzten Windows XP", VbInformation + VbOKOnly, "Ihr Betriebssystem" >%TEMP%\os.vbs
|
||||
goto end
|
||||
|
||||
:Vista
|
||||
echo MsgBox "Sie benutzten Windows Vista oder Windows 7 RC", VbInformation + VbOKOnly, "Ihr Betriebssystem" >%TEMP%\os.vbs
|
||||
goto end
|
||||
|
||||
:Sieben
|
||||
echo MsgBox "Sie benutzten Windows 7 ", VbInformation + VbOKOnly, "Ihr Betriebssystem" >%TEMP%\os.vbs
|
||||
goto end
|
||||
|
||||
:end
|
||||
START %TEMP%\os.vbs
|
||||
ping 1.2.3.4 -n 1 -w 5000 > nul
|
||||
del /f %TEMP%\os.vbs
|
||||
BIN
test/test.ps1
Normal file
BIN
test/test.ps1
Normal file
Binary file not shown.
23
test/test2 (2).vbs
Normal file
23
test/test2 (2).vbs
Normal file
@@ -0,0 +1,23 @@
|
||||
set objTextFile2 = fs.OpenTextFile("\\ntlifeprotest\workarea\cdpsxh\cmelog.txt",2,True)
|
||||
Set wshshell = WScript.CreateObject("wscript.Shell")
|
||||
|
||||
retcode = Wshshell.run ("cmd /c ftp -s:cmeftp.scr "&strServer&" > objTextFile2",2,True)
|
||||
'wscript.echo ("retcode = "&retcode)
|
||||
objTextFile2.Close
|
||||
'WScript.Sleep(100000) ' 10 second delay
|
||||
|
||||
Set objTextFile3 = fs.OpenTextFile("objTextFile2", 1)
|
||||
|
||||
Do Until objTextFile3.AtEndOfStream
|
||||
|
||||
strLine = objTextFile3.Readline
|
||||
|
||||
If InStr(strLine, "Transfer complete") <> 0 Then
|
||||
wscript.echo strLine
|
||||
wscript.echo "found"
|
||||
else
|
||||
wscript.echo strLine
|
||||
wscript.echo "not found"
|
||||
End If
|
||||
|
||||
Loop
|
||||
8
test/vb.ps1
Normal file
8
test/vb.ps1
Normal file
@@ -0,0 +1,8 @@
|
||||
$test1 = (Test-Connection -ComputerName "enterprise" -Count 1 -Quiet)
|
||||
|
||||
|
||||
|
||||
Write-Host $test1
|
||||
|
||||
|
||||
#$job = Test-connection -ComputerName (Get-Content Servers.txt) -asjobPS C:\>if ($job.JobStateInfo.State -ne "Running") {$Results = Receive-Job $job}
|
||||
6
test/windows-shutdown.ps1
Normal file
6
test/windows-shutdown.ps1
Normal file
@@ -0,0 +1,6 @@
|
||||
$time = 120
|
||||
$server = "mycomputer"
|
||||
$comment = "this is my comment."
|
||||
$reboot = @("/r", "/t", $time, "/m", "\\$server", "/c", $comment)
|
||||
|
||||
& shutdown $reboot
|
||||
26
test/windreamIndexerwithDLL.ps1
Normal file
26
test/windreamIndexerwithDLL.ps1
Normal file
@@ -0,0 +1,26 @@
|
||||
cls
|
||||
$File = "W:\Digital Data - Geschäftsprozesse\Manually\File\Fuchstest.bpm"
|
||||
|
||||
|
||||
[Reflection.Assembly]::LoadFile("P:\Skriptentwickung\development\Modules\DD_LIB_Standards.dll")
|
||||
|
||||
$LogPath =[DD_LIB_Standards.clsLogger]::LOGFILE_PATH="E:\KammM\Log\Log.txt"
|
||||
Write-Host $LogPath
|
||||
exit
|
||||
$Result = [DD_LIB_Standards.clsWindream]::Create_Session()
|
||||
Write-warning $Result
|
||||
|
||||
$Result = [DD_LIB_Standards.clsWD_GET]::WDFile_exists($File)
|
||||
|
||||
IF ($Result -eq $true) {
|
||||
|
||||
$Result = [DD_LIB_Standards.clsWD_SET]::IndexFile($File, "String 37", "Doku", "Digital Data - Geschäftsprozesse")
|
||||
|
||||
}
|
||||
|
||||
###Initiieren der dll:
|
||||
###1. clsLogger.LOGFILE_PATH = "logdatei-Pfad"
|
||||
###2. windream-Session kreieren:
|
||||
### entweder impersonate: clsWindream.Create_Session ==> Returns true or false
|
||||
### oder personate: clsWindream.CreateSession_AsUser(Domain, ServerName, UserName, Password) ==> Returns true or false
|
||||
###3. Classen clsWD_SET und clsWD_GET enthalten die windream-Funktionen
|
||||
51
test/wisag-import.ps1
Normal file
51
test/wisag-import.ps1
Normal file
@@ -0,0 +1,51 @@
|
||||
#Test
|
||||
cls
|
||||
Import-module sqlps
|
||||
|
||||
$SourceFile = Get-Item "P:\Skriptentwickung\development\Import-FileContent2Database\wisag_test-dateien\AVIAFAK_LFB1.DAT"
|
||||
|
||||
Add-Member -InputObject $SourceFile -MemberType NoteProperty -Name Content -Value (Get-Content -Path $($SourceFile.FullName) -ErrorAction Stop) -Force
|
||||
Add-Member -InputObject $SourceFile -MemberType NoteProperty -Name ContentLines -Value ($SourceFile.Content | Convertfrom-csv -Delimiter “`t” -ErrorAction Stop) -Force
|
||||
#-Delimiter "`t"
|
||||
|
||||
$test = Import-Csv -Delimiter "`t" "P:\Skriptentwickung\development\Import-FileContent2Database\wisag_test-dateien\AVIAFAK_LFB1.DAT"
|
||||
|
||||
exit
|
||||
|
||||
#Setup for SQL Server connection
|
||||
#SQL Server Name
|
||||
$SQLServer = "APPLIK02\SQLEXPRESS"
|
||||
#Database Name
|
||||
$SQLDBName = "code-test"
|
||||
|
||||
#Create the SQL Connection Object
|
||||
$SQLConn = New-Object System.Data.SQLClient.SQLConnection
|
||||
#Create the SQL Command Object, to work with the Database
|
||||
$SQLCmd = New-Object System.Data.SQLClient.SQLCommand
|
||||
|
||||
#Set the connection string one the SQL Connection Object
|
||||
$SQLConn.ConnectionString = "Server=$SQLServer;Database=$SQLDBName; Integrated Security=SSPI"
|
||||
#Open the connection
|
||||
$SQLConn.Open()
|
||||
|
||||
#Handle the query with SQLCommand Object
|
||||
$SQLCmd.CommandText = $query
|
||||
#Provide the open connection to the Command Object as a property
|
||||
$SQLCmd.Connection = $SQLConn
|
||||
|
||||
#Execute
|
||||
$SQLReturn=$SQLCmd.ExecuteReader()
|
||||
|
||||
Import-module sqlps
|
||||
$tablename = "dbo."+$name
|
||||
$database = 'foxdeploy'
|
||||
$server = '.'
|
||||
$table = 'dbo.powershell_test'
|
||||
|
||||
Import-CSV .\yourcsv.csv | ForEach-Object {Invoke-Sqlcmd `
|
||||
-Database $database -ServerInstance $server `
|
||||
-Query "insert into $table VALUES ('$($_.Column1)','$($_.Column2)')"
|
||||
}
|
||||
|
||||
$SQLReturn.Close()
|
||||
$SQLConn.Close()
|
||||
Reference in New Issue
Block a user