sourcecode

새 인스턴스에서 PowerShell 시작 스크립트

codebag 2023. 8. 21. 21:14
반응형

새 인스턴스에서 PowerShell 시작 스크립트

몇 가지 옵션이 있는 마스터 스크립트가 있습니다.메뉴에서 1을 선택하면 작업 1이 실행되고 메뉴로 돌아갑니다.이것은 잘 작동하지만 예를 들어 8을 선택하면 새 PowerShell 창에서 Permissions 스크립트의 코드 블록이 실행됩니다.다른 스크립트를 호출하지 않고 모든 코드를 한 스크립트에 넣고 싶습니다.

여러 위협에서 발견된 '시작-프로세스 파워셸'로 이 작업을 수행할 수 있습니다.그러면 새 PowerShell 창이 열리지만 Permissions 스크립트의 코드 블록이 제대로 실행되지 않습니다.어떤 도움이라도 주시면 감사하겠습니다.

마스터 스크립트:

<# 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.."

권한 스크립트:

####### 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 :)"

더 짧은 코드 블록으로 지금까지 시도했지만 성공하지 못했습니다.

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"}}}

cmd를 시작하여 새 powershell 인스턴스를 시작하는 대신 다음을 수행할 수 있습니다.

start powershell {echo hello}

새로 시작된 파워셸이 즉시 종료되지 않도록 하려면:

start powershell {echo hello; Read-Host}

외부 PS 창에서 시작하려면 다음을 사용할 수 있습니다.

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

예:

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

cmd를 사용하여 파워셸을 시작하시겠습니까?

start-process powershell -ArgumentList '-noexit -command 'Commands for the new PowerShell''

비록 ~일지라도start powershell명령어는 더 깨끗해 보입니다. 사용할 수 있는 모든 것을 허용하지 않습니다.invoke-expression예를 들어, 다음은 새 창을 열고 제목과 배경색을 변경한 후 창을 열어 둡니다.

invoke-expression 'cmd /c start powershell -NoExit -Command {                           `
    cd -path $env:homedrive$env:homepath/Documents/MySillyFolder;                  `
    $host.UI.RawUI.WindowTitle = "A Silly Little Title";                                `
    color -background "red";                                                            `
}';

또한 다른 파워셸 스크립트 내에서도 정상적으로 실행됩니다.

사용하여 이 작업을 수행하려는 경우start powershell {...}구문은 제목 변경 줄에 오류를 줄 것이고, 창을 열어두지 않을 것입니다. (아마도 모호한 구문 해킹이 있을 것입니다.)start powershell일은 하지만 찾을 수 없었습니다.)

언급URL : https://stackoverflow.com/questions/23237473/powershell-launch-script-in-new-instance

반응형