2014-04-23 5 views
9

Ich habe eine Master-Skript, die mehrere Optionen hat. Wenn Sie 1 im Menü auswählen, wird Aktion 1 ausgeführt und Sie kehren anschließend zum Menü zurück. Das funktioniert gut, aber ich möchte in der Lage sein, zum Beispiel 8 auszuwählen, das den Codeblock des Permissions-Skripts in einem neuen PowerShell-Fenster startet. Ich möchte den gesamten Code in einem Skript haben und kein anderes Skript aufrufen.PowerShell Start-Skript in neuer Instanz

Ich weiß, dass dies mit 'Start-Process Powershell' wie in mehreren Bedrohungen gefunden werden kann. Dadurch wird ein neues PowerShell-Fenster geöffnet, aber der Codeblock wird nicht korrekt vom Permissions-Skript ausgeführt. Jede Hilfe wäre willkommen.

Master-Skript:

<# Author: Me #> 
# Variables 
$User = [Environment]::UserName 
$OutputPath = "C:\Users\$User\Downloads\" 
# Functions 
Function Manager ($u) { 
$m = Get-ADObject -Identity $u.managedBy -Properties displayName,cn 
    if($m.ObjectClass -eq "user") { $m.displayName } Else{ $m.cn } } 
# Hit play 
do { 
    [int]$userMenuChoice = 0 
    cls 
    while ($userMenuChoice -lt 1 -or $userMenuChoice -gt 7) { 
    Write-Host "PowerShell for dummies" 
    Write-Host "__________________________________________________" 
    Write-Host "1. Groups created in the last 3 weeks" 
    Write-Host "2. Users created in the last 3 weeks" 
    Write-Host "3. All BEL Users" 
    Write-Host "4. Users with an incorrect display name or city" 
    Write-Host "5. Users de-provisioned within 3 weeks" 
    Write-Host "6. Files/Folders: Activate inheritance & set owner to admin" 
    Write-Host "7. Quit" 

    [int]$userMenuChoice = Read-Host "Please choose an option" 

    switch ($userMenuChoice) { 
     1{# Groups created in the last 3 weeks 
     $When = ((Get-Date).AddDays(-21)).Date 
     Get-ADGroup -SearchBase "OU=Groups,OU=BEL,OU=EU,DC=domain,DC=net" -Filter {whenCreated -ge $When} -Properties * | 
     Select whenCreated, cn, displayName, GroupScope, GroupCategory, description, info, @{Label="Managed By"; expression= { Manager $_ } } | Export-Csv $OutputPath"New groups.csv" -NoTypeInformation -Delimiter ";" -Encoding utf8; start $OutputPath"New groups.csv"} 
     2{# Users created in the last 3 weeks 
     $When = ((Get-Date).AddDays(-21)).Date 
     Get-ADUser -SearchBase "OU=BEL,OU=EU,DC=domain,DC=net" -Filter {whenCreated -ge $When} -Properties * | Select whenCreated, Name,displayName, sn, givenName, sAMAccountName, title, description, employeeType, info, department, company, homeDirectory, scriptPath, physicalDeliveryOfficeName, @{Label="Managed By"; expression= { Manager $_ } } | Export-Csv $OutputPath"New users.csv" -NoTypeInformation -Delimiter ";" -Encoding utf8; start $OutputPath"New users.csv"} 
     3{# All BEL users 
     Get-ADUser -SearchBase "OU=Users,OU=BEL,OU=EU,DC=domain,DC=net" -Filter * -Properties * | Select whenCreated, @{Name="Lastlogon"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}}, Name,displayName, sn, givenName, sAMAccountName, title, description, employeeType, info, department, company, homeDirectory, scriptPath, physicalDeliveryOfficeName, @{Label="Managed By"; expression= { Manager $_ } } | Export-Csv $OutputPath"BEL Service Accounts.csv" -NoTypeInformation -Delimiter ";" -Encoding utf8; start $OutputPath"BEL Service Accounts.csv"} 
     4{# Users with an incorrect display name or city 
     Get-ADUser -SearchBase "OU=BEL,OU=EU,DC=domain,DC=net" -Filter * -Properties * | where {$_.cn -NotLike "*$($_.l)*" -and $_.distinguishedname -notmatch 'OU=Terminated Users,OU=BEL,OU=EU,DC=grouphc,DC=net' -and $_.cn -ne "BNL Service Desk"} | Select whenCreated, Name,displayName, sn, givenName, sAMAccountName, title, description, employeeType, info, department, company, homeDirectory, scriptPath, physicalDeliveryOfficeName, @{Label="Managed By"; expression= { Manager $_ } } | Export-Csv $OutputPath"Incorrect users.csv" -NoTypeInformation -Delimiter ";" -Encoding utf8; start $OutputPath"Incorrect users.csv"} 
     5{# Users de-provisioned within 3 weeks 
     $LogonDate = ((Get-Date).AddDays(-80)).Date # GIT 104 days KB-3872 
     $CreaDate = ((Get-Date).AddDays(-60)).Date # GIT 60 days 
     $PwdDate = ((Get-Date).AddDays(-90)).Date # GIT 90 days 
     Get-ADUser -SearchBase "OU=Users,OU=BEL,OU=EU,DC=grouphc,DC=net" -Filter {(lastLogonDate -le $LogonDate) -and (WhenCreated -lt $CreaDate) -and (PwdLastSet -le $PwdDate)} -Properties * | Select LastLogonDate, WhenCreated, PasswordLastSet, Name, title, description, employeeType, info, department, company, homeDirectory, scriptPath, physicalDeliveryOfficeName, @{Label="Managed By"; expression= { Manager $_ } } | Export-Csv $OutputPath"To be deprovisioned.csv" -NoTypeInformation -Delimiter ";" -Encoding utf8; start $OutputPath"To be deprovisioned.csv"} 
     6{# Files/Folders: Activate inheritance & set owner to admin 
     Get-ADUser -SearchBase "OU=BEL,OU=EU,DC=domain,DC=net" -Filter * -Properties * | where {$_.cn -NotLike "*$($_.l)*" -and $_.distinguishedname -notmatch 'OU=Terminated Users,OU=BEL,OU=EU,DC=grouphc,DC=net' -and $_.cn -ne "BNL Service Desk"} | Select whenCreated, Name,displayName, sn, givenName, sAMAccountName, title, description, employeeType, info, department, company, homeDirectory, scriptPath, physicalDeliveryOfficeName, @{Label="Managed By"; expression= { Manager $_ } } | Export-Csv $OutputPath"Incorrect users.csv" -NoTypeInformation -Delimiter ";" -Encoding utf8; start $OutputPath"Incorrect users.csv"} 
    } 
    } 
} while ($userMenuChoice -ne 7) 
cls 
Write-Host "We left here because there's nothing else to do.." 

Berechtigungen Skript:

####### TO DO ####### 
$Target = "\\domain.net\SHARE\Target" 


# Change FOLDER owners to Admin 
If (Test-Path C:\PTemp) { Remove-Item C:\PTemp } 
New-Item -type directory -Path C:\PTemp > $null 

Write-Output "`nStart setting folder permissions on:" 

$Folders = @(Get-ChildItem -Path $Target -Directory -Recurse | Select-Object -ExpandProperty FullName) 
foreach ($Item1 in $Folders) 
{ 
# Action 
Write-Output $Item1 
$AdjustTokenPrivileges = @" 
using System; 
using System.Runtime.InteropServices; 

public class TokenManipulator 
{ 
    [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] 
    internal static extern bool AdjustTokenPrivileges(IntPtr htok, bool disall, 
    ref TokPriv1Luid newst, int len, IntPtr prev, IntPtr relen); 
    [DllImport("kernel32.dll", ExactSpelling = true)] 
    internal static extern IntPtr GetCurrentProcess(); 
    [DllImport("advapi32.dll", ExactSpelling = true, SetLastError = true)] 
    internal static extern bool OpenProcessToken(IntPtr h, int acc, ref IntPtr 
    phtok); 
    [DllImport("advapi32.dll", SetLastError = true)] 
    internal static extern bool LookupPrivilegeValue(string host, string name, 
    ref long pluid); 
    [StructLayout(LayoutKind.Sequential, Pack = 1)] 
    internal struct TokPriv1Luid 
    { 
    public int Count; 
    public long Luid; 
    public int Attr; 
    } 
    internal const int SE_PRIVILEGE_DISABLED = 0x00000000; 
    internal const int SE_PRIVILEGE_ENABLED = 0x00000002; 
    internal const int TOKEN_QUERY = 0x00000008; 
    internal const int TOKEN_ADJUST_PRIVILEGES = 0x00000020; 
    public static bool AddPrivilege(string privilege) 
    { 
    try 
    { 
    bool retVal; 
    TokPriv1Luid tp; 
    IntPtr hproc = GetCurrentProcess(); 
    IntPtr htok = IntPtr.Zero; 
    retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok); 
    tp.Count = 1; 
    tp.Luid = 0; 
    tp.Attr = SE_PRIVILEGE_ENABLED; 
    retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid); 
    retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero); 
    return retVal; 
    } 
    catch (Exception ex) 
    { 
    throw ex; 
    } 
    } 
    public static bool RemovePrivilege(string privilege) 
    { 
    try 
    { 
    bool retVal; 
    TokPriv1Luid tp; 
    IntPtr hproc = GetCurrentProcess(); 
    IntPtr htok = IntPtr.Zero; 
    retVal = OpenProcessToken(hproc, TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, ref htok); 
    tp.Count = 1; 
    tp.Luid = 0; 
    tp.Attr = SE_PRIVILEGE_DISABLED; 
    retVal = LookupPrivilegeValue(null, privilege, ref tp.Luid); 
    retVal = AdjustTokenPrivileges(htok, false, ref tp, 0, IntPtr.Zero, IntPtr.Zero); 
    return retVal; 
    } 
    catch (Exception ex) 
    { 
    throw ex; 
    } 
    } 
} 
"@ 
add-type $AdjustTokenPrivileges 
$Folder = Get-Item $Item1 
[void][TokenManipulator]::AddPrivilege("SeRestorePrivilege") 
[void][TokenManipulator]::AddPrivilege("SeBackupPrivilege") 
[void][TokenManipulator]::AddPrivilege("SeTakeOwnershipPrivilege") 
$NewOwnerACL = New-Object System.Security.AccessControl.DirectorySecurity 
$Admin = New-Object System.Security.Principal.NTAccount("BUILTIN\Administrators") 
$NewOwnerACL.SetOwner($Admin) 
$Folder.SetAccessControl($NewOwnerACL) 
# Add folder Admins to ACL with Full Control to descend folder structure 
$Acl = Get-Acl -Path C:\PTemp 
$Ar = New-Object system.security.accesscontrol.filesystemaccessrule("BUILTIN\Administrators","FullControl","Allow") 
$Acl.SetAccessRule($Ar) 
Set-Acl $Item1 $Acl 
} 

# Change FILE owners to Admin 
If (Test-Path C:\PFile) { Remove-Item C:\PFile } 
New-Item -type file -Path C:\PFile > $null 

Write-Output "`nStart setting file permissions on:" 

$Files = @(Get-ChildItem -Path $Target -File -Recurse | Select-Object -ExpandProperty FullName) 
foreach ($Item2 in $Files) 
{ 
# Action 
Write-Output $Item2 
$Account = New-Object System.Security.Principal.NTAccount("BUILTIN\Administrators") 
$FileSecurity = new-object System.Security.AccessControl.FileSecurity 
$FileSecurity.SetOwner($Account) 
[System.IO.File]::SetAccessControl($Item2, $FileSecurity) 
# Add file Admins to ACL with Full Control and activate inheritance 
$PAcl = Get-Acl -Path C:\PFile 
$PAr = New-Object system.security.accesscontrol.filesystemaccessrule("BUILTIN\Administrators","FullControl","Allow") 
$PAcl.SetAccessRule($PAr) 
Set-Acl $Item2 $PAcl 
} 

# Clean-up junk 
Write-Output "`nCleaning up.." 
rm C:\PTemp, C:\PFile 
Write-Output "`nAll done :)" 

Was ich bisher versucht, mit einem kürzeren Codeblock, sondern auch ohne Erfolg:

6{# Test 
Start-Process powershell {Get-ADUser -SearchBase "OU=Users,OU=BEL,OU=EU,DC=domain,DC=net" -Filter * -Properties * | Select whenCreated, @{Name="Lastlogon"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}}, Name,displayName, sn, givenName, sAMAccountName, title, description, employeeType, info, department, company, homeDirectory, scriptPath, physicalDeliveryOfficeName, @{Label="Managed By"; expression= { Manager $_ } } | Export-Csv $OutputPath"BEL Service Accounts.csv" -NoTypeInformation -Delimiter ";" -Encoding utf8; start $OutputPath"BEL Service Accounts.csv"}}} 

Antwort

4

Zum Starten in a n externe PS-Fenster können Sie Folgendes verwenden:

invoke-expression 'cmd /c start powershell -Command { [script block here] }' 

Z. B .:

invoke-expression 'cmd /c start powershell -Command { write-host "Hi, new window!"; set-location "C:\"; get-childitem ; sleep 3}' 
+0

Vielen Dank Arco444, Ihr Beispiel funktioniert perfekt. Aber aus dem einen oder anderen Grund funktioniert es nicht für meinen Codeblock. Könnte es sein, dass dort .Net Code drin ist? – DarkLite1

+0

Was ist der Fehler? Stellen Sie sicher, dass Sie die Befehle mit ';' trennen, alle Anführungszeichen und Sonderzeichen usw. zurücklassen. Es wäre sicherlich einfacher, den Befehl ein separates Skript aufrufen zu lassen, anstatt es inline zu übergeben, also würde ich diesen Ansatz ernsthaft in Betracht ziehen. – arco444

+0

Hi @ arco444 Sie haben Recht, es ist wahrscheinlich einfacher, nur ein Skript aufzurufen. Jetzt lass uns für diesen Befehl googlen, damit ich ihn stattdessen verwenden kann. Danke für den Tipp Mann! – DarkLite1

0

Mit cmd Powershell starten ???

Start-Prozess Power -ArgumentList '-noexit -command 'Befehle für die neue Powershell''

11

Statt ein cmd der Gründung eine neue Powershell-Instanz starten können Sie:

start powershell {echo hello} 

Um zu verhindern, sofortiger Ausgang der neuen gestarteten Powershell:

start powershell {echo hello; Read-Host} 
Verwandte Themen