Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Export Group Policy Settings to Excel

$
0
0

Using Windows Powershell i can get all the group policy settings into an nice HTML format, however i would like to know if similar information can be exported into an Excel Format. I want all the GPO's where they are linked to and what each GPO settings and values are. Can you assist how this can accomplished using Powershell or using any other method.


Remote exe Installation

$
0
0

Hello,

I tried those commands, but none send any sort of error, they just do nothing..

Invoke-Command-ComputerName remoteComp -ScriptBlock{C:\temp\installer.exe}-ArgumentList/SILENTInvoke-Command-ComputerName remoteComp {Start-Process C:\temp\installer.exe -ArgumentList/SILENT -Wait}


please help

how to retrieve Username and designation of the DirectReports of the users from the AD

$
0
0

Hi Forum,

I am new to do code in powershell.

Please assist me how to retrieve the  username and designation from the direct reports users. 

Please kindly assist me.

$OUpath = 'OU=Test,OU=Test,OU=Test,DC=Test,DC=com' 
$ExportPath = 'D:\Test\Test.csv' 
Get-ADUser -Filter * -SearchBase $OUpath  -Properties * | Select -property Title,Department,City,DisplayName,EmailAddress,MobilePhone,Office,OfficePhone,@{n='directReports';e={$_.directreports -join '; '}} | Export-Csv -NoType $ExportPath

The above code i am getting the Directreports as CN:Test,OU:Test.

But i need to fetch CN values of the users  along with their designation.

Regards,

Deepak.


Rama

Help with Desired state configuration

$
0
0
I have a issue while creating multiple OUs and groups when using foreach in desired state configuration. In my config data I have part like this
Data = @{
ADOU = 'Windows Server 2012','Windows Server 2012 R2','Windows Server 2016','Windows Server 2019'
}
This is the part of the code in the script that I use to create those OUs
foreach ($OU in $Data.ADOrganizationalUnit) {

xADOrganizationalUnit OU {

Name = ($_ -replace '-')
Path = $DomainInfo.DomainDN
ProtectedFromAccidentalDeletion = $true
}
}
Does not matter what I do I get this
xActiveDirectory\xADOrganizationalUnit : A duplicate resource identifier......Change the name of this resource so that it is unique with in the node..

Problem with writing help

$
0
0
Hi Guys,
I have issue with writing help in my script. Somehow when I run get-help on my function I don't get synopsis and rest of the parts.
<#   
.SYNOPSIS   
   A brief description of what your code does.
.DESCRIPTION 
   A full description of what your code does.
.NOTES   
    Name: Script/function/module name
    Author: Your Name
    DateCreated: The current date
#>


Function New-Something {

Please help...

Issue with user account creation PS script

$
0
0

I am having an issue with a script that I have been modifying to create AD accounts from a CSV file that gets uploaded on a daily basis. I'll start off by saying that I did not write this script, I found it online and it is available for anyone to use, I have only been modifying it to fit our needs. Also, I am really just getting into using PS more and more and definitely not a pro by any stretch, hence the reason I am here.

I'll try not to make this incredibly long and boring but want you to understand the scripts purpose and where I am having problems at. The script should look for a CSV file and use that file to create/update/disable AD user accounts based on different fields. The script checks for duplicate SAM accounts as part of this process and has a method to come up with a different username if there is a duplicate. Also, based on the "Status" field the script should either enable or disable an existing user account.

The main issue I am currently having is that the account will get created, everything seems to work properly except all accounts will be disabled during the running of the script, regardless of the status field. If I comment out those lines of the script the account will get created and be enabled like it should be so I'm not sure what I am missing.

Also, when a duplicate SAMaccountname is found, the script should come up with a unique name based on defined rules but that does not seem to work properly as I get messages during the New-ADuser command that it fails due to a user with that name already existing. 

I will post the code below and any help or guidance I could get would be greatly appreciated. I am not asking for someone to re-write this and make it work, simply point me in the right direction would be great. Again, I am not great with PS as of yet but do feel I at least understand the flow of this script, just can't seem to understand where it is going wrong at.

# Import the Active Directory functions
Import-Module ActiveDirectory

#Setup some hashtables
#For each school code in your SIS, map it to the appropriate fileserver in the format "schoolcode" = "servername";
#$server = @{"1001" = "fscluster1"; "1002" = "SchoolB-FS"; "1003" = "SchoolC-FS"}
#If you're using standardized abbreviations anywhere (perhaps your groups are named like like SITEA-Students, SITEB-Students etc) It's useful to create a map of those abbreviations
$siteabbr = @{"1001" = "2021"; "1002" = "SITEB"; "1003" = "SITEC"}
#Create a map of codes to Active Directory OUs where students should be moved/created etc. Student grade to grad year mapping.
$orgunits = @{"12" = "2019"; "11" = "2020"; "10" = "2021"; "09" = "2022"; "08" = "2023"; "07" = "2024"; "06" = "2025"; "05" = "2026"; "04" = "2027"; "03" = "2028"; "02" = "2029"; "01" = "2030"; "K" = "2031"; "PK" = "2032"}
#Create a map of grades to email distribution groups.
$emailgroup = @{"12" = "Seniors"; "11" = "Juniors"; "10" = "Sophmores"; "9" = "Freshmen"; "PK" = "PK"}

# Import the Data - This is based on using the accompanying SISsync.sql file to extract data from PowerSchool and expects a tab delimited file, if you're using a CSV from another system or autosend, change `t to , (or omit the delimiter option entirely) and modify the headers appropriately
$sisfile = Import-Csv -delimiter "`t" -Path "C:\TEMP\AD_SYNC\DATA\cts export.txt" -header "grade","givenName","sn","lunchpin","studentid","status"

#Start Processing per file line
foreach ($sisline in $sisfile) {
	#Set the username example below is gradyear+firstinitial+lastname. If a duplicate is found the format will be gradyear+firstthreeletters+lastname.
    $sisline.givenname | ForEach-Object {$firstinitial = $_[0]}
    $givenname = $sisline.givenname
    # $dup variable gets the first three letters of the students first name to use if a duplicate SAMaccountname is found.
    $dup = $sisline.givenname.Substring(0,3)
    $duplicate = $orgunits.Get_Item($sisline.Grade) + $dup + $sisline.sn
   	$sAMAccountName = $orgunits.Get_Item($sisline.Grade) + $firstinitial + $sisline.sn
	#tidy up samaccountName to make it more valid (no spaces, double periods or apostrophies. Helpful for when there's data entry 'issues' in your source
	$sAMAccountName = $sAMAccountName.replace(" ","")
	$sAMAccountName = $sAMAccountName.replace("..",".")
	$sAMAccountName = $sAMAccountName.replace("'","")
    $sAMAccountName = $sAMAccountName.replace("-","")
	#Truncate to 19 characters
	#$sAMAccountName = $sAMAccountName.substring(0,19)
	#Set the displayname for the account in AD example below is firstname space lastname
	$name = $sisline.givenName + " " + $sisline.sn
	#Set a password for the account, example below takes their Lunch PIN (LunchPIN) and assigns it as their initial password
    $pass = "wildcats" + $sisline.lunchPIN 
	$password = ConvertTo-SecureString -AsPlainText $pass -Force
	#Set the UPN for the account for most instances, should be AD Account name + @AD.FQDN. Need to change for each domain!
	$userPrincipalName = $sAMAccountName + "@slater.local"
	#Set the mail attribute for the account (if desired, usually helpful if you're synchronizing to Google Apps/Office 365)
	$mail = $sAMAccountName + "@testschool.net"
	#Set name attributes
	$givenName = $sisline.givenName
	$sn = $sisline.sn
    #Set status variable (if account gets enabled or disabled) Status is determined whether or not there is a value in this field. Only 
    #will have a value if the student has withdrawn from school.
    $status = $sisline.status
	#Store student ID in AD's "EmployeeID" attribute
	$employeeID = $sisline.studentid
	#Optional location attributes, helpful if syncing to Moodle via LDAP
	$c = "US"
	$co = "United States"
	$l = $orgunits.Get_Item($sisline.Grade)
	#Optional other attribute population we set these because they're easy to view with the MMC taskpad we push to secretaries to allow them to reset passwords
	$company = $orgunits.Get_Item($sisline.Grade)
	$physicalDeliveryOfficeName = $sisline.grade
	$description = $orgunits.Get_Item($sisline.Grade)
	$comment = $sAMAccountName + "@slater.local"
	#Create a hashtable of all the "otherattributes" this is used when we create/update the user
	$otherAttributes = @{'userPrincipalName' = "$userPrincipalName"; 'mail' = "$mail"; 'comment' = "$comment"; 'givenName' = "$givenName"; 'sn' = "$sn"; 'employeeID' = "$employeeID"; 'employeeNumber' = "$pass"; 'c' = "$c"; 'l' = "$l"; 'company' = "$company"; 'physicalDeliveryOfficeName' = "$physicalDeliveryOfficeName"; 'description' = "$description"}

	#recast description as a string because AD commands require it and it gets converted to int if it's all numeric.
	$otherAttributes.description = [string]$otherAttributes.description

	#set the path variable to the OU the student should end up in. In the example below the AD OU Structure is Slater -> Test -> Students -> 2021
	$path = "OU=" + $company + ",OU=STUDENT,OU=USERS,OU=MANAGED,DC=slater,DC=local"

	#Check if student exists
	#THIS IS WHERE IT GETS TERRIBLY SLOW IF YOU HAVEN'T ADDED EMPLOYEEID TO THE LIST OF INDEXED AD ATTRIBUTES. STRONGLY CONSIDER THIS.
	$user = Get-ADUser -Filter {employeeID -eq $employeeID}

	if ($user -eq $null) {
		#student doesn't exist, create them
		#find a valid username
		#This is probably the most inelegant backwards way of doing this, but it works. Feel free to improve
		$i = 1 
   		$sAMSearch = $sAMAccountName
		while ((Get-ADUser -Filter {sAMAccountName -eq $sAMSearch}) -ne $null) {		
			$sAMSearch = $duplicate
			$i++
		}
		$i--
		if ($i -ne 0) {
		#name was taken, update constants to reflect new name formart gradyearfirstthreelastname
			$sAMAccountName = $sAMSearch
			$otherAttributes.Set_Item("userPrincipalName", $sAMAccountName + "@slater.local")
			$otherAttributes.Set_Item("mail", $sAMAccountName + "@testschool.net")
			$otherAttributes.Set_Item("comment", $sAMAccountName + "@testschool.net")
			#$name = $name + $i
		}
		#create user using $sAMAccountName and set attributes and assign it to the $user variable
		New-ADUser -sAMAccountName $sAMAccountName -Name $name -Path $path -otherAttributes $otherAttributes -Enable $true -AccountPassword $password -CannotChangePassword $true -PasswordNeverExpires $true 
		$user = Get-ADUser -Filter {employeeID -eq $employeeID}
	} elseif (($user.Surname -ne $sn) -or ($user.givenName -ne $givenName)) {
		#The first or last names were changed in the import source, need to make some changes to the user
		#find a valid username
		#This is probably the most inelegant backwards way of doing this, but it works. Feel free to improve
		$i = 1
		$sAMSearch = $sAMAccountName
		while ((Get-ADUser -Filter {sAMAccountName -eq $sAMSearch}) -ne $null) {		
			$sAMSearch = $duplicate
			$i++
		}
		$i--
		if ($i -ne 0)
		#need to update Name, sAMAccountName, UPN and email because of name collison  
		{
			$sAMAccountName = $sAMSearch
			$otherAttributes.Add("sAMAccountName", $sAMAccountName)
			$otherAttributes.Set_Item("userPrincipalName", $sAMAccountName + "@slater.local")
			$otherAttributes.Set_Item("mail", $sAMAccountName + "@testschool.net")
			$otherAttributes.Set_Item("comment", $sAMAccountName + "@testschool.net")
			$name = $name
		}
		Rename-ADObject -Identity $user $name
		#need to re-key user variable after rename
		$user = Get-ADUser -Filter {employeeID -eq $employeeID}
		#Update AD attributes to reflect changes
		Set-ADUser -Identity $user -replace $otherAttributes -SamAccountName $sAMAccountName
	} else {
		#Update AD Attributes for existing user whos name hasn't changed. Unset anything usernamebased first since the username hasn't changed
		$otherAttributes.Remove("userPrincipalName")
		$otherAttributes.Remove("mail")
		$otherAttributes.Remove("comment")  
		Set-ADUser -Identity $user -replace $otherAttributes
	}
	#reset the samaccountname variable to what it currently queries out of AD as, probably not necessary
	$sAMAccountName = $user.SamAccountName
	#check to see if the DN of the user contains the school name, if not, move it to the correct location
	$properdn = "OU=$company,"
	write-host $properdn
	if ($user.DistinguishedName -notlike "*$properdn*")
	{
		Move-ADObject -Identity $user -TargetPath $path
		$user = Get-ADUser -Filter {employeeID -eq $employeeID}
	}
    # $user = Get-ADUser -Filter {samaccountname -eq $samaccountname}

    write $user
    

    #Enable or disable a user account. This is determined by whether or not there is a value in the 
    #withdrawal date field. If there is a value student is no longer active and should be disabled
    #if there is no value student is active and should be enabled.

    if ($status -ne " "){

    Disable-ADAccount -Identity $user}

    elseif ($status -like " "){

    Enable-ADAccount -Identity $user}

	#Check to see if folders exist on proper server, if not, create them and set permissions.
	#Used to dynamically pick fileserver based on certain field - $servername = $server.Get_Item($sisline.grade)
    $servername = "fscluster1"

	#The example below assumes student home folders exist on \\fileserver\student$\username structure
	$homepath = "\\"  + $servername + "\student$\" + $sAMAccountName
	if ((Test-Path ($homepath)) -ne $true)
	{
		#create folder and set permissions
		#Change DOMAIN below with your AD Domain
		New-Item -ItemType directory -Path $homepath
		$acl = Get-Acl $homepath
		$permission = "slater.local\$sAMAccountName","Modify","ContainerInherit,ObjectInherit","None","Allow"
		$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule $permission
		$acl.SetAccessRule($accessRule)
		$acl | Set-Acl $homepath
	}

	#A quick 100ms pause to make sure the folder has been created and the permissions applied. you may be able to dial that back or remove it entirely	
	Start-Sleep -m 100

	#Set the users homedrive
	Set-ADUser -Identity $user -HomeDirectory $homepath -HomeDrive "H:"

	#Add user to site student group and grad year group also a good place to add any other groups you may require
	#This assumes a security group with the site abbreviation-Students exists and a group called Grad#### exists
	#It doesn't check to see if the user is already a part of these groups, so it will often print an error stating it can't add them because they already exist
	$studentgroup1 = $orgunits.Get_Item($sisline.grade)
    #Add students to the correct email distribution group based on grade level.
    $studentgroup2 = $emailgroup.Get_Item($sisline.grade)
	#$gradgroup = "Grad" + $description
	Add-ADGroupMember $studentgroup1 $user
    #Add-ADGroupMember $studentgroup2 $user
	#Add-ADGroupMember ALL_STUDENT $user

}

#rename.ps1
#Change filename to whatever file needs to be renamed. 
 $fileName = "C:\TEMP\AD_SYNC\DATA\cts export.txt"

# Check the file exists
# if (-not(Test-Path $fileName)) 

# {break}

# Display the original name
"Original filename: $fileName"

$fileObj = get-item $fileName

# Get the date
$DateStamp = get-date -uformat "%Y-%m-%d@%H-%M-%S"

$extOnly = $fileObj.extension

if ($extOnly.length -eq 0) {
   $nameOnly = $fileObj.Name
   rename-item "$fileObj" "$nameOnly-$DateStamp"
   }
else {
   $nameOnly = $fileObj.Name.Replace( $fileObj.Extension,'')
   rename-item "$fileName" "$nameOnly-$DateStamp$extOnly"
   }

# Display the new name
#"New filename: $nameOnly-$DateStamp$extOnly"


#Sorts files by creation date, skips the top twenty newest files and deletes any older than the top twenty. Folder path and number of 
#skipped files can be modified to fit your needs.
Get-ChildItem C:\TEMP\AD_SYNC\DATA\ -Recurse| Where-Object{-not $_.PsIsContainer}| Sort-Object CreationTime -desc| 
    Select-Object -Skip 10| Remove-Item -Force

Here is some of the error messages I get when running the PS script:

PS C:\TEMP\AD_SYNC> C:\TEMP\AD_SYNC\SISsync.ps1
New-ADUser : The server is unwilling to process the request
At C:\TEMP\AD_SYNC\SISsync.ps1:92 char:3
+         New-ADUser -sAMAccountName $sAMAccountName -Name $name -Path  ...
+         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (CN=GivenName SN...slater,DC=local:String) [New-ADUse 
   r], ADException
    + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Comman 
   ds.NewADUser
 
OU=,
Move-ADObject : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a 
valid value for the argument, and then try running the command again.
At C:\TEMP\AD_SYNC\SISsync.ps1:137 char:27
+         Move-ADObject -Identity $user -TargetPath $path
+                                 ~~~~~
    + CategoryInfo          : InvalidData: (:) [Move-ADObject], ParameterBindingValidationExcepti 
   on
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Manageme 
   nt.Commands.MoveADObject
 
Disable-ADAccount : Cannot validate argument on parameter 'Identity'. The argument is null. 
Provide a valid value for the argument, and then try running the command again.
At C:\TEMP\AD_SYNC\SISsync.ps1:152 char:33
+     Disable-ADAccount -Identity $user}
+                                 ~~~~~
    + CategoryInfo          : InvalidData: (:) [Disable-ADAccount], ParameterBindingValidationExc 
   eption
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Manageme 
   nt.Commands.DisableADAccount
 
Set-ADUser : Cannot validate argument on parameter 'Identity'. The argument is null. Provide a 
valid value for the argument, and then try running the command again.
At C:\TEMP\AD_SYNC\SISsync.ps1:180 char:23
+     Set-ADUser -Identity $user -HomeDirectory $homepath -HomeDrive "H ...
+                          ~~~~~
    + CategoryInfo          : InvalidData: (:) [Set-ADUser], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Manageme 
   nt.Commands.SetADUser


New-NetIPAddress : Invalid parameter InterfaceAlias

$
0
0

hello,

I am trying to configure an IP address for a VM.  

My version of PS is 5-1-17134-407

I issued New-NetIPAddress -IPAddress 10.2.0.1 -PrefixLength 24 -InterfaceAlias "vEthernet_Lab_Switch"

as well as New-NetIPAddress -IPAddress 10.2.0.1 -PrefixLength 24  to force the Interface value.

I get the error posted above

thanks

Joe

Your fix

$
0
0
# Initialization section

$startGame = "False" #Variable used to determine if the game is played
$playerBusted = "False" #Variable used to track when the player busts
$playerHand = 0      #Stores the current value of the player's hand
$computerHand = 0    #Stores the current value of the computer's hand
$playAgain = "True"  #control the execution of the loop that controls the
                     #execution of logic in the Main Processing section


# Functions and Filters section

#This function gets the player's permission to begin the game
function Get-Permission {

  #Loop until a valid reply is collected
  while ($startGame -eq "False") {

    Clear-Host  #Clear the Windows command console screen

    #Display the game's opening screen 
    Write-Host "`n`n`n"
    Write-Host " Welcome to the" -foregroundColor Blue  
    write-Host ""
    Write-Host ""
    Write-Host " P O W E R S H E L L    B L A C K J A C K    G A M E"`
      -foregroundColor Blue   
    Write-Host "" 
    Write-Host "" 
    Write-Host ""
    Write-Host "" 
    Write-Host "" 
    Write-Host ""
    Write-Host ""
    Write-Host ""

    #Collect the player's input
    $response = Read-Host "`n`n`n`n`n`n`n Would you like to play? (Y/N)"

    #Validate the player's input
    if ($response -eq "Y"){  #The player wants to play
      $startGame = "True"
    }
    elseif ($response -eq "N") {  #The player wants to quit

      Check-Registry

      exit  #Terminate script execution

    }

  }

}

#This function retrieves a registry value that specifies whether or not
#the script should display a splash screen if the player chooses not to
#play a game after starting the script
function Check-Registry {

  Clear-Host   #Clear the Windows command console screen

  $currentLocation = Get-Location #Keep track of the current directory

  set-Location hkcu:\  #Change to the HKEY_CURRENT_USER hive

  #Retrieve the data stored in the Credits value under the PSBlackjack
  #subkey
  $regKey = $(Get-ItemProperty hkcu:\PSBlackjack).Credits
  $regKey2 = $(Get-ItemProperty)

  if ($regKey -eq "True") {  #If the registry value is set to true
                             #display the closing splash screen
    Write-Host " `n`n`n"
    Write-Host " P O W E R S H E L L   B L A C K J A C K`n`n`n"`
      -foregroundColor Yellow
    write-Host "     Developed by Jerry Lee Ford, Jr.`n`n"
    Write-Host "             Copyright 2014`n`n`n`n"
    Write-Host "         www.tech-publishing.com`n`n`n`n`n`n"

  }
     
  Set-Location $currentLocation  #Restore the current working directory

}

#This function controls the execution of an individual round of play
function Play-Game {

  Deal-Hand  #Call the function that deals the opening hands

  Get-PlayerHand  #Call the function that manages the player's hand

  #If the player has busted the game is over; otherwise, it is the 
  #computer's turn
  if ($script:playerBusted -eq "False") {
    Get-ComputerHand #Call the function that manages the computer's hand
  }

  Analyze-Results  #Call the function that analyzes game results and 
                   #declares a winner
}

#This function deals the player and computer's initial hands
function Deal-Hand {

  $script:playerHand = Get-Card  #Assign a card to the player's hand
  $script:computerHand = Get-Card  #Assign a card to the computer's hand

}

#This function retrieves a random number representing a card and returns
#the value of that card to the calling statement
function Get-Card {

  $number = 0

  #Generate the game's random number (between 1 - 13)
  $number = Get-Random –minimum 1 –maximum 14

  if ($number -eq 1 ) {$number = 11} #Represents an ace
  if ($number -gt 10) {$number = 10} #Represents a jack, queen or king

  $number  #Return the number to the calling statements

}

#This function is responsible for managing the computer's hand
function Get-ComputerHand {

  $tempCard = 0  #Stores the value of the computer's new card

  #The computer continues to take hits as long as its hand's value is less
  #than seventeen
  while ($computerHand -lt 17) {

    $tempCard = Get-Card  #Get a new card for the computer

    #Add the value of the new card to the computer's hand
    $script:computerHand = $script:computerHand + $tempCard

  }

}

#This function analyzes and displays the results of each game
function Analyze-Results {

  Clear-Host  #Clear the Windows command console screen

  #Display the player and computer's final hand
  Write-Host "`n`n`n`n RESULTS:`n`n"
  Write-host " Player Hand:   $playerHand`n"
  Write-Host " Computer Hand: $computerHand`n`n"

  #See if the player busted
  if ($playerBusted -eq "True") {
    Write-Host "`a You have gone bust." -ForegroundColor Red
  }
  else {  #See if the computer busted
    if ($computerHand -gt 21) {
      Write-host "`a The computer has gone bust." -ForegroundColor Red
    }
    else { #Neither the player nor the computer busted, so look for a winner
      if ($playerHand -gt $computerHand) {
         Write-Host "`a You Win!" -ForegroundColor Green
      } 
      if ($playerHand -eq $computerHand) {
         Write-Host "`a Tie!" -ForegroundColor Yellow
      }
      if ($playerHand -lt $computerHand) {
         Write-host "`a You loose." -ForegroundColor Red
      }
    }

  }

}

#This function displays the value of both the player's and the computer's
#current hands and prompts the player to take another card
function Get-PlayerHand {

  $keepGoing = "True"  #Control the execution of the loop that managers
                       #the player's hand
  $response = ""       #Store the player's input

  #Loop until a valid reply is collected
  while ($keepGoing -eq "True") {
    
    Clear-Host  #Clear the Windows command console screen

    #Display the player's and computer's current hands 
    Write-Host "`n`n"
    Write-Host ""
    write-Host " CURRENT HAND:"
    Write-Host "`n"
    Write-Host " Player Hand:   $playerHand"   
    Write-Host "" 
    Write-Host " Computer Hand: $computerHand" 
    Write-Host ""
    Write-Host "" 
    Write-Host "" 
    Write-Host ""
    Write-Host ""
    Write-Host ""

    #Prompt the player's to take another card
    $response = Read-Host "`n`n`n`n`n`n`n Do you want another card? (Y/N)"

    #Validate the player's input
    if ($response -eq "Y"){
      Get-NewCard  #Get another card for the player
    }
    elseif ($response -eq "N") {  #The player wants to quit
      $keepGoing = "False"
      Clear-Host   #Clear the Windows command console screen
    }

    if ($playerHand -gt 21) {  #The player has gone bust
      $script:playerBusted = "True"
      $keepGoing = "False"
    }

  }

}

#This function is called whenever the player elects to get a new card
#and is responsible for updating the value of the player's hand
function Get-NewCard {

  $tempCard = 0  #Store the value of the player's new card

  $tempCard = Get-Card  #Get a new card for the player

  #Add the value of the new card to the player's hand
  $script:playerHand = $script:playerHand + $tempCard

}


# Main Processing section

Get-Permission  #Call function that asks the players for permission to 
                #start the game

#Continue playing new games until the player decides to quit the game
while ($playAgain -eq "True") {

  Play-Game  #Call function that controls the play of individual games

  #Prompt the player to play a new game
  $response = Read-Host "`n`n`n`n`n`n`n`n`n`n Press Enter to play"`
     "again or Q to quit"

  if ($response -eq "Q") {  #The player wants to quit
    $playAgain = "False"
    Clear-Host   #Clear the Windows command console screen
  }
  else { #The player did not enter Q, so keep playing
    $playAgain = "True"
    $playerBusted = "False"
  }

}

Help applying retention policy using CSV file as input for set-retentioncompliancepolicy Skype For Business

$
0
0

I need help using a csv file with email addresses for users to a new S4B retention policy, my syntax is missing something.

$email = import-csv "C:\useremails.csv"
ForEach-Object {Set-RetentionCompliancePolicy -Identity "SFB Retention" -AddSkypeLocation $email}
;

Example of my csv

first.last@company.com
other.last@company.com
another.someone@company.com

No headers, just a plain csv (all data in first column)

Thanks in advance

Breaking Multiple large text files into smaller files with 1M rows max

$
0
0

Hi everyone,

I am new to Powershell and this forum and would appreciate your help.

I regularly receive multiple text files with >1M rows each of which I need split the files into chunks of 1M rows maximum. Someone told me to check out Powershell for this and I managed to grab the below from the internet and alter it to my needs.

Any advice is very much appreciated. 

Josh

Settings:

All source files are in the same folder. I wish for the code to loop through each of the source files in the folder, and divide them into multiple files containing subsets of the source file's rows (partitioned by the row's value in the final column). The final column contains a text string followed by a number. The output files will be named based on the value in the final column.

Unresolved issue:

I've tested the below code on a folder that has two source files. It runs and cuts the first source file into smaller files saving them where requested but then throws an error and does not loop through the second source file in the folder.

error is as follows:

new-object : Exception calling ".ctor" with "1" argument(s): "Access to the path
'C:\Users\josh\Desktop\testing\powershell\results' is denied."
At line:14 char:12
+     $reader = new-object IO.StreamReader($src)  # Reader for input
+               ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand

Sample source data (this sample should create two output files named DEenglish1 and DEenglish2 both containing 1 row):

COLUMN1 COLUMN2 PARTITIONCOLUMN

XXXX YYYY DEenglish1

XXXX YYYY DEenglish2

Code so far:

$fileDirectory = "C:\Users\josh\Desktop\testing\powershell";


foreach($file in Get-ChildItem $fileDirectory)
{
$src = "C:\Users\josh\Desktop\testing\powershell\" + $file.name  # Source file
$dst = "C:\Users\josh\Desktop\testing\powershell\results\{0}.txt" # Output file(s)

$reader = new-object IO.StreamReader($src)  # Reader for input

$header = Get-Content -Path $src | select -First 1 # Get the header row

$ht = @{}
$line = $reader.ReadLine() # Skip the first line, it's alread in $header

while(($line = $reader.ReadLine()) -ne $null){ # Loop the input
$match = [regex]::match($line, '(?i)(\w+\d)$') # Look for row that ends with text followed by number
if($match.Success){

  $outFileName = $match.Groups[0].value # defines the output file name

  if(-not $ht.ContainsKey($outFileName)) { # Output file is not yet in hashtable
$ht.Add($outFileName, (new-object Text.StringBuilder) )
[void]$ht[$outFileName].Append($header)
[void]$ht[$outFileName].Append([Environment]::NewLine)
  } else { # Append data to existing file
[void]$ht[$outFileName].Append($line)
[void]$ht[$outFileName].Append([Environment]::NewLine)
  }
}
}
$reader.Close() # Close the input file

# Dump the hashtable contents to individual files
$ht.GetEnumerator() | % { 
set-content $($dst -f $_.Name) ($_.Value).ToString() 

}

PowerShell - Searching Excel and replacing text

$
0
0

Hi all,

I am trying to figure out how to loop this script so that it replaces all the text that I am searching for in my Excel file.  I am able to get it to run but it only replaces the text in the first column and then ends. Any help is appreciated and thanks in advance.

-Gaz

$File="D:\test.xlsx"

# Setup Excel, open $File and set the the first worksheet
$Excel=New-Object-ComObjectExcel.Application
$Excel.visible=$true
$Workbook=$Excel.workbooks.open($file)
$Worksheets=$Workbooks.worksheets
$Worksheet=$Workbook.Worksheets.Item(1)

$SearchString="TEMP# This is the value that I will be searching for

$Range=$Worksheet.Range("A1").EntireColumn
$Search=$Range.find($SearchString)

$Search.value()="ABSENT"# This is the value that i want to replace the text with.

Powershell Script - Export Services and Compare (before & after restart)

$
0
0

Hello All,

I hoping that someone can help me (I am terrible at coding and even worse at powershell). My team performs a lot of patching/restarting of Servers - currently before we begin we log onto each server and export the services, at the end of the restarts etc we log back in and export the services again and compare to ensure that they match.

I'm looking for a way to do this quicker/easier - I discussed with a colleague who advised that we can do this via powershell, unfortunately i've been unable to get it to work, I have no idea where to start.

What i'm thinking is:

A menu screen:

1 - WMI - Pre-Patching Exports

2 - WMI - Post-Patching Exports

3 - WMI - Comparison

4 - Get Service * - Pre-Patching Exports

5 - Get Service * - Post-Patching Exports

6 - Get Service * - Comparison

With each command reads the "Server/Computer Name" from a Text file, for example:

for each Computer in $Computers {Get Service *} export to $ComputerName Before.XML

Compare $ComputerName Before.xml and $ComputerName After.xml

If anyone could help that would be great!!

Edit multiple existing directories in a share drive

$
0
0

Hello,

Im trying to figure out how to create a script that will allow me to edit existing directories using powershell. 

What im looking to do: I have a share drive at work, and theyre wanting me to edit every single folder so that they look the same, while not deleting any of the current data.

The folder architecture Should look like this:

Advisers(root folder)

     -Adviser 1(name)

          -Folder1

          -Folder2

     -Adviser 2(name)

          -Folder1

          -Folder2

Every adviser should have the same folders. And again, I would like it to not duplicate any folders if they're already there. No copies, no data deletion.  Any suggestions? 

Close Form

$
0
0

I have a form and I need to CLEAN close it when clicking 'x' button. Please advise what code should be included in OnClick_Exit. My actual form is much more complicated.

Function OnClick_Exit() {
    Write-Host 'Closed'
    # code to release any created in form
    # this is just a sample form
}

$form = New-Object System.Windows.Forms.Form
$form.Size = '600, 400'
$form.StartPosition = 'CenterScreen'
$Form.Add_FormClosing({OnClick_Exit})

$form.ShowDialog() | Out-Null

Need Powershell script help

$
0
0

Hello,

I need powershell scripting help to fetch data just like above like username, logon date, Log off date and networkip (request coming from).

could you please help me on this script.

thanks in advance.

VBRS


List folders N deep - List subfolders

$
0
0

I need to list subfolders two deep. It would seem I could do "Get-ChildItem\\test\test | Where { $_.PSIsContainer } | Select -Exp name" and pass those results into a variable and run a for each: "Get-ChildItem\\test\test\$var | Where { $_.PSIsContainer } | Select -Exp name"

However, is there a function out there that will accomplish what I need and perhaps is flexible enough to specify how deep to go?

Thank you,

How to remove Group policy permission with Powershell

$
0
0

Just like set-gppermisions and get-gppermissions is there a command for removing permission of user on Group policy object 

something like remove-ggpermission? If not then how to remove group policy permission via powershell?

Thanks,

Aatif Kungle

Search pattern in directory and extract string from files using PowerShell

$
0
0

I have almost 400 .sql files where i need to search for a specific pattern and output the results.

e.g

*file1.sql

select * from mydb.ops1_tbl from something1 <other n lines>

*file2.sql

select * from mydb.ops2_tbl from something2 <other n lines>

*file3.sql

select * from mydb.ops3_tbl ,mydb.ops4_tbl where a = b <other n lines>

Expected result

file1.sql mydb.ops1_tbl

file2.sql mydb.ops2_tbl

file3.sql mydb.ops3_tbl mydb.ops4_tbl

Below script in powershell - able to fetch the filename

Get-ChildItem-Recurse-Filter*.sql|Select-String-pattern "mydb."|group path|select name

Below script in powershell - able to fetch the line

Get-ChildItem-Recurse-Filter*.sql |Select-String-pattern "mydb."|select line

I need in the above format, someone has any pointers regarding this?


Rakesh Jayaram http://blogs.msdn.com/b/rakesh_ramblings/

re-run a script or let a diffrent script to be run

$
0
0

Hi everyone,

for school i have to write a scipt, with the function "choose 1 you re-run the first script and if you choos 2 it runs a different scrip"

and with the second script it says " the Syntax has a bad name" 

  

Clear-Host
#this is script 1 

#hier vragen we de gebruikers naam op die ze willen zoeken
[String]$username = Read-host `
-Prompt 'geef gebruikersnaam'

#als de gebruiker is gevonden dan probeert hij het wachtwoord te resseten door dit script te runnen. als de gebruiker niet is gevonden wort de 
#error melding op het scherm vermeld en dan gaat die vragen of je een nieuwe gebruiker aan wilt maken of het als je het nog een keer witl proberen.
Try {
Set-ADAccountPassword -Identity $username -Reset -NewPassword (ConvertTo-SecureString -AsPlainText "$newpassword" -Force -Verbose)  `
-PassThru -ErrorAction stop

}

Catch [System.exception] {
Write-Warning "gebruiker niet gevonden"
Write-Warning -Message ($_.exception.message)
}

Finally 

if ($Error.Count -gt 0) {Write-Host "er is iets fout gegaan
Kijk of u het de naam goed hebt geschreven en probeer opnieuw of wilt u een nieuw AD Account maken?"
$antwoord = read-host `
-prompt "als u het scipt opnieuw wilt laten runnen kies 1 als u een nieuwe gebruiker wilt aanmaken kies 2"
}

else
{Write-Host "gebruiker $username is gevonden"}
$error.Clear()
 }

#this is scirpt  2  i want to be run again

#hier gaan we vragen aan de host wat de gegevens moeten zijn om de ADUser aan te maken.


$Firstname = Read-Host `
-Prompt " geef voornaam op" 

$Lastname = Read-Host `
-Prompt "geef achternaam op" 

$Fulname = $Firstname + " " + $Lastname

$driveletter = read-host `
-Prompt "geef driveletter op" 

$domain = "MediaTech.lan"

$upn = $firstname + $domain

$OU = Read-Host `
-Prompt "geef Locatie voor gebruiker op" 

$PhoneNumber = Read-Host `
-Prompt "geef telefoon nummer op" 

#dit script is om een nieuwe gebruiker aan te maken, dit kan je ook gebruiker met behulp van een CSV bestand, als je die importeer en de variabelen koppelt aan het bestand.


New-ADUser -Name $Firstname -Surname $Lastname -DisplayName $Fulname `
-GivenName $Firstname -SamAccountName $Firstname -HomeDrive $driveletter `
-HomeDirectory $Homefolder -UserPrincipalName $upn -Path $OU -OfficePhone "$PhoneNumber" -HomePhone "$PhoneNumber" -MobilePhone "$PhoneNumber" `
-AccountPassword $setPassword -Enabled $True -PassThru `
-Department 'TEST' -Company 'MediaTech' `
-PasswordNeverExpires:$true

Thanks advaced.

get-windowscapability access denied from elevated prompt

$
0
0

Hi All,

I have Windows 10 1809 and the RSAT tools are now feature on demand. No problem.

Except I run an elevated PS prompt and I get access denied when I try to run get-windowscapability or add-windowscapability

PS C:\> Get-WindowsCapability -Name RSAT* -Online | Add-WindowsCapability –Online
Get-WindowsCapability : Access is denied.
At line:1 char:1
+ Get-WindowsCapability -Name RSAT* -Online | Add-WindowsCapability –On ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Get-WindowsCapability], COMException
    + FullyQualifiedErrorId : Microsoft.Dism.Commands.GetWindowsCapabilityCommand
 
PS C:\>

I tried all the suggestions here:

http://woshub.com/install-rsat-feature-windows-10-powershell/

But there is nothing coming up about access denied. Other commandlets work OK and I have local admin rights on my machine.

Anyone have any light to shed on this please?

Thanks Tom.

Viewing all 21975 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>