简体   繁体   English

新实例中的 PowerShell 启动脚本

[英]PowerShell launch script in new instance

I have a Master script that has several options.我有一个主脚本,它有几个选项。 When you select 1 in the menu, action 1 will be executed and afterwards you'll get back to the menu.当您在菜单中选择 1 时,将执行操作 1,然后您将返回菜单。 This is working fine but I would like to be able to select for example 8, which launches the code block of the Permissions script in a new PowerShell window.这工作正常,但我希望能够选择例如 8,它会在新的 PowerShell 窗口中启动权限脚本的代码块。 I would like to have all code in one script and not call another script.我想在一个脚本中包含所有代码,而不是调用另一个脚本。

I know this can be done with 'Start-Process powershell' as found in several threats.我知道这可以通过在几个威胁中找到的“Start-Process powershell”来完成。 This does open an new PowerShell window but doesn't execute the code block properly of the Permissions script .这确实会打开一个新的 PowerShell 窗口,但不会正确执行Permissions 脚本的代码块。 Any help would be appreciated.任何帮助,将不胜感激。

Master script:主脚本:

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

Permissions script:权限脚本:

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

What I tried so far, with a shorter code block but also without success:到目前为止我尝试过的代码块较短但也没有成功:

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

Instead of starting a cmd to start a new powershell instance you can:您可以:

start powershell {echo hello}

To prevent immediate exit of new started powershell:为了防止新启动的 powershell 立即退出:

start powershell {echo hello; Read-Host}

To launch in an external PS window, you can use the following:要在外部 PS 窗口中启动,您可以使用以下命令:

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

Eg:例如:

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

使用cmd启动powershell?

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

Although start powershell command looks cleaner, it doesn't allow you to do everything that you can do with invoke-expression .尽管start powershell命令看起来更start powershell ,但它不允许您执行使用invoke-expression可以执行的所有操作。 For example, the following opens a new window, changes its title and background color, and leaves the window open:例如,以下打开一个新窗口,更改其标题和背景颜色,并使窗口保持打开状态:

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";                                                            `
}';

It also runs fine from within another powershell script.它也可以在另一个 powershell 脚本中正常运行。

If you try to do this using the start powershell {...} syntax it will give an error on the title-changing line, and won't keep the window open.如果您尝试使用start powershell {...}语法执行此操作,它将在标题更改行上显示错误,并且不会保持窗口打开。 (I suppose It's possible that there's some obscure syntax hack that will make start powershell work, but I haven't been able to find one.) (我想可能有一些晦涩的语法技巧可以使start powershell正常工作,但我一直找不到。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM