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

Latest file in all subfolders

$
0
0

I'm never written or used a PS script. I need to get to understand PS. What I need is a script that will give me the latest file name and date stamp in every folder beneath the folder share.


Problem deleting files

$
0
0

Hello,

I wrote the following Script and run in to a Problem.

The Script is Supposed to send a Mail for each pdf in a source Folder
and after sending the mail the pdf shoud be moved in to a Destination Folder
The Mail part dose Work so far, but the Move the file from source to Destination part dose not.

It's the Last ForEach loop Operation (it's marked Bold and Underlined in the Code at the very end) Failing all the time, cause the script seems to be useing the files even after sending them via mail. How can I stop the script to use the files?

Also I don't want the Script to run as Admin.

can somebody help me with this?


PS: Sorry for my english. I hope it's at least somehow understandable.

param(
[string]$to = "",
[string]$subject = "Scan to Mail",
[string]$body = "",
[string]$Server = "",
[string]$Sender = "",
[string]$source = ".\PDFSource",
[alias("Dest")][string]$Destination = ".\Sent\",
[int]$Port = 587,
[alias("SetCred")][switch] $SetCredential = $False,
[alias("?")][switch]$help = $false
)

if ($help -eq $True){
Get-Content .\Helpfiles\Help.txt
exit
}

if($SetCredential -eq $True){

$Key = New-Object Byte[] 32
[Security.Cryptography.RNGCryptoServiceProvider]::Create().GetBytes($Key)
$Key | out-file .\PassKey\aes.key
$Credentials = Get-Credential
$Credentials.UserName > ".\PassKey\MyUser.txt"
$Credentials.Password | ConvertFrom-SecureString -key (get-content .\PassKey\aes.key) | set-content ".\PassKey\MyPass.txt"
$SenderUser = (Get-Content .\PassKey\MyUser.txt)
$Password = (Get-Content .\PassKey\MyPass.txt | ConvertTo-SecureString -Key (Get-Content .\PassKey\aes.key))
}
else{
$SenderUser = (Get-Content .\PassKey\MyUser.txt)
$Password = (Get-Content .\PassKey\MyPass.txt | ConvertTo-SecureString -Key (Get-Content .\PassKey\aes.key))

Write-Information "Credential remains"
}




Function  SendMail ($attachments)
{
  $smtpServer = $Server
  $smtpServerport = $Port
  $emailSmtpUser = $SenderUser
  $emailSmtpPass = "$Password"

  $emailMessage = New-Object System.Net.Mail.MailMessage
  $emailMessage.From = $Sender
  foreach ($addr in $to)
  {
    $emailMessage.To.Add($addr)
  }
  foreach ($attachment in $attachments)
  {
    $emailMessage.Attachments.Add($attachment)
  }
  $emailMessage.Subject = $subject
  $emailMessage.IsBodyHtml = $true
  $emailMessage.Body = $body

  $smtpClient = New-Object System.Net.Mail.SmtpClient($smtpServer , $smtpServerport)
  $smtpClient.EnableSsl = $false
  $smtpClient.Credentials = New-Object System.Net.NetworkCredential($emailSmtpUser , $emailSmtpPass);

  $SMTPClient.Send( $emailMessage )
}



$AtachmentToAdd = Get-ChildItem -Path $source | Where-Object {$_.Extension -eq ".pdf"}ForEach ($item in $AtachmentToAdd){
    SendMail -attachments $item.FullName
    copy-Item -Path $item.FullName -Destination $Destination
    $item.delete()
    }


Simple search and replace items from a SharePoint list using powershell

$
0
0

The script works fine replacing from "title" column with "Single line of text" but with Custom Column Name and "Multiple lines of text" it fails?

Title - Single line of text  
URLLInk - Multiple lines of text 

======================================================

WORKS $item["Title"] = $item["Title"].Replace("72PRD","PRD")

FAILS $item["URLLInk"] = $item["URLLInk"].Replace("72PRD","PRD")

======================================================

THIS IS THE ERROR MESSAGE SENT BACK TO PS:

At D:\ps\ReplaceLinks1.ps1:10 char:27
+ $value = $item["URLLink"] if($value -Contains "72PRD") {
+                           ~~
Unexpected token 'if' in expression or statement.
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : UnexpectedToken

======================================================

ENTIRE SCRIPT
Add-PSSnapin "Microsoft.SharePoint.Powershell"
$web =Get-SPWeb "http://dev"
$list= $web.Lists.TryGetList("devlist")
$web.AllowUnsafeUpdates=$true
foreach($item in $list.Items)
{
$item["URLLInk"] = $item["URLLInk"].Replace("72PRD","PRD")
$item.SystemUpdate();
}
#$list.Update();
Write-Host "Updated values in the list items are"
foreach($item in $list.Items)
{
$item["LinkData"]
}


Need scrip to migrate DiscoveryMailboxes from Exchange 2013 to O365

$
0
0

I have a need to move a discovery mailbox from my customer's on Premises Exchange 2013 server to their O365 tenant.

Running the script:

Get-Mailbox -Resultsize unlimited -Filter {RecipientTypeDetails -eq "DiscoveryMailbox"}B

Brings back the following results

The customer needs to have me move the two custom DiscoveryMailboxes from the on premises server (Exchange 2013) to their O365 tenant Exchange.  Since the "alias" is not a user alias the EAC Migration tool will not work.  PowerShell is the next logical option.

I would like to use New-MoveRequesthowever; I do not know how to construct a New-MoveRequest with paramenters to connect correctly to the on-premises server while calling this method from an active PS session connected to the O365 tenant.

Does anyone have a script example for this type of migration?

A "tail -f" equivalent command in Powershell to show real time logging

$
0
0

Hello,

Using the powershell command:
Get-Content "Filename" -Wait -Tail 10
showing Real-Time contents of a file in powershell doesn't work.

As example i would like to show Real-Time contents of a systemout.log file in a IBM Websphere Environment.

Using the above command, the shell remain in "listening mode" but nothing happens even if the Systemout.log file changes.

In a unix environment it is enough to type "tail -f filename" and everything work correctly.

Is it possible to use a "tail -f" equivalent command in Powershell to show real time logging?

Thank You in advance.

Fausto.


powershell not trusting signed certificate

$
0
0

Hi everyone,

we have the following situation (and google + technet didn't get me to an answer yet - if i failed at searching, i'm willing to take your blame :D):

Issue:

  • we are using an internal certificate authority to provide "Code Signing" certs for our Powershell scripts
  • we set the registry of all machines to run Powershell scripts "Remote Signed" (no GPO, to be able to temporarily overwrite it)
  • we put signed scripts into a central DFS
  • we run the scripts and get the following error on a hand full of servers (not all, not any specific one):

File \\DFS\<MyScript>.ps1 is published by CN="MyUser", OU=SomeOU, DC=my, DC=personal, DC=domain and is not trusted on your system. Only run scripts from trusted publishers.
[V] Never run  [D] Do not run  [R] Run once  [A] Always run  [?] Help (default is "D")

Meta-Informations:

  • we have servers with: Windows Server 2008 R2 and Windows Server 2012 R2 affected
  • Powershell 5.1(14393.2969)
  • issue can not be pin pointed to a specific OS or PS version
  • we have two certificate authorities (just recently did a redesign and build a newer CA)
  • both have our Code Signing template
  • both can issue those and you can sign scripts perfectly fine
  • all affected systems neither accept code signing from the old nor the new CA
  • we checked the installed Windows Server OS, Patches and Powershell versions - nothing indicates a specific problem
  • we upgraded everything to the newest possible versions
  • we double checked the certificates, the local certificate trust (old and new CA are trusted), we added the signing person to the local trust, we checked the connection to the CA to verify the system can check the validity of the used cert, we use a timestamp server for script signing, we even checked the complete network connection (local and network firewalls) for any indication

We are currently at a dead end and need some help to find a solution for this issue.

Do you have any tip or trick on how to further analyze this issue?

Thank you in advance!

Best regards

Matthias / TheAlcesh

User being added into a Skype for Business conferencing policy who should not be added

$
0
0

Hi,

I am testing the below, but for some reason it is adding 1 user into the new policy who is not in the below test group.

$groupmember = Get-ADGroupMember test-p2pfiletransfer | Get-ADUser
foreach ($member in $groupmember)
{
$aduser = Get-Csuser -Identity $member.UserPrincipalName | Where-Object {$_.HostingProvider -eq "SRV:"}
Get-CsUser -Identity $aduser.identity | Grant-CsConferencingPolicy -PolicyName EnableP2PFileTransfer
}

If I run the below command it doesn't output the user who should't be being added into the policy. It does ouput a user who should be added into the policy which is fine.

Get-Csuser -Identity $member.UserPrincipalName | Where-Object {$_.HostingProvider -eq "SRV:"}

The user who shouldn't be added into the list is the very first user who is displayed in the SfB Control panel when sorted from A to Z. Not too sure if that is making a difference or not.



Trouble with Script for Exporting all Teams File Permissions

$
0
0

Hello I am trying to get this script to work as I intend. 

Here is what I have.

import-module PSExcel
import-module microsoftteams


# Azure AD OAuth Application Token for Graph API
# Get OAuth token for a AAD Application (returned as $token)

# Application (client) ID, tenant ID and secret
$clientId = "xxx"
$tenantId = "xxx"
$clientSecret = 'xxx'

# Construct URI
$uri = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"

# Construct Body
$body = @{
    client_id     = $clientId
    scope         = "https://graph.microsoft.com/.default"
    client_secret = $clientSecret
    grant_type    = "client_credentials"
}

# Get OAuth 2.0 Token
$tokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType "application/x-www-form-urlencoded" -Body $body -UseBasicParsing

# Access Token
$token = ($tokenRequest.Content | ConvertFrom-Json).access_token

$authHeader = @{
   'Content-Type'='application\json'
   'Authorization'=$token
}


#Calculate Current Date

$CurrentDate = Get-Date
$Timestamp = $CurrentDate.ToString('yyyy-MM-dd')
$TodaysDate =  $CurrentDate.ToString('M/d/yyyy')
$CurrentYear = $CurrentDate.ToString('yyyy') 
$Quarter = [Math]::Ceiling($CurrentDate.Month / 3)
Switch ($Quarter) {
    1 {
        $StartDate = "1/1/" + $CurrentDate.Year.ToString()
    }
    2 {
        $StartDate = "4/1/" + $CurrentDate.Year.ToString()
    }
    3 {
        $StartDate = "7/1/" + $CurrentDate.Year.ToString()
    }
    4 {
        $StartDate = "10/1/" + $CurrentDate.Year.ToString()
    }
}
$QuarterFormatted = $CurrentYear + "-Q" + $Quarter

$FolderPath = "C:\$Quarterformatted"
New-Item -ItemType Directory -Force -Path $FolderPath

Connect-MicrosoftTeams -AadAccessToken $token -MsAccessToken $token -TenantId $tenantId -AccountId $clientId


#Get all Teams
$Teams = (get-Team -GroupId xxx)

#Loop to get users in each Team
ForEach ($Team in $Teams){

$GroupId = (($Team).GroupId)
$TeamName = (get-team -GroupId $GroupId | Select-Object DisplayName)
$TeamSummaryInfo = (get-team -GroupId $GroupId | Select-Object *)
$TeamChannels = (get-teamChannel -GroupId $GroupId | Select-Object @{Label="Channel Name"; Expression={$_.DisplayName} },Description)
$TeamDisplayName = $TeamName.DisplayName

#Lookup Group Files
$GroupURL = "https://graph.microsoft.com/v1.0/groups/" + $GroupId + "/drive/root/search(q='')"
$GroupLookup = invoke-restmethod -uri $GroupURL -Headers $authHeader

$FileList= $GroupLookup.value | Select Name,createdDateTime,LastModifiedDateTime,ID,WebUrl

#Process File List
Foreach($File in $FileList){
$FilePermissionWebRequestURL = "https://graph.microsoft.com/v1.0/groups/" + $GroupID + "/drive/items/" + $File.ID + "/permissions"
$FilePermissionWebRequestQuery = invoke-restmethod -uri $FilePermissionWebRequestURL -Headers $authHeader
$FilePermissionWebRequest = $FilePermissionWebRequestQuery.value | Select *
$FileInfoWebRequestURL = "https://graph.microsoft.com/v1.0/groups/" + $GroupID + "/drive/items/" + $File.ID
$FileInfoWebRequest = invoke-restmethod -uri $FileInfoWebRequestURL -Headers $authHeader
$GrantedTo = $FilePermissionWebRequest | Select-Object -ExpandProperty grantedTo
$Groupname = $GrantedTo.user
$Groups = $Groupname.DisplayName
$Roles = $FilePermissionWebRequest.roles
$TeamFileList = @()
$Properties = [ordered]@{'File Name' = $File.name; 'File ID' = $File.id; 'Group or User' = $groups; 'Role' = $Roles}
$TeamFileList += New-Object -TypeName PSObject -Property $Properties

}



$SavePath = $FolderPath + "\Teams-$TeamDisplayName-$Quarterformatted.xlsx"

#Delete File if it exists
if (Test-Path $SavePath) 
{
  Remove-Item $SavePath
}
$TeamSummaryInfo | Export-XLSX $SavePath -WorksheetName 'Team Summary Info' -Table -AutoFit
$TeamUsers = Get-TeamUser -GroupId $GroupId | Select-Object Name, User, Role | Export-XLSX $SavePath -WorksheetName 'Team Members' -Table -AutoFit
$TeamChannels | Export-XLSX $SavePath -WorksheetName 'Team Channels' -Table -AutoFit
$TeamFileList | Export-XLSX $SavePath -WorksheetName 'Team Files' -Table -AutoFit

#$Excel = New-Excel -Path $SavePath
#$Excel | Close-Excel -Save

}

#Erase variable
$GroupId = $null

I'm having two issues. The first is that my output is only giving me the last $file in $filelist and not adding each one to my export. i have tried several things with the last thing that are these lines.

$TeamFileList = @()
$Properties = [ordered]@{'File Name' = $File.name; 'File ID' = $File.id; 'Group or User' = $groups; 'Role' = $Roles}
$TeamFileList += New-Object -TypeName PSObject -Property $Properties

As you can see the export is only giving me the last $file in $filelist instead of all of them

I can't post images as my MS account isn't verified but essentially this is how the my excel export looks now.

            A                                  B                               C                                  D

1          File Name                      File ID                         Group or User               Role

2          Last $File in $FileList       File.id                         System.Object[]             System.Object[]

3          Empty

The second thing i'm having issues with is receiving System.object in Group or User and Role fields. I have tried several array manipulations to try to get these fields into my export but every thing that I have tried is not working.

The second thing I'm having issues with is the System.Object[] in Group or User and Role Fields. I have tried several array manipulations to try to get these fields into my export to no avail.

I am trying to get an export that look something like this:

            A                                  B                               C                                  D

1          File Name                      File ID                         Group or User               Role

2          File1                             File1.id                         Group Owners              Owner

3          File1                             File1.id                         Group Member             Write

4          File1                             File1.id                         Group Visitors              Read

5          File2                             File2.id                         Group Owners              Owner

6          File2                             File2.id                         Group Member             Write

7          File2                             File2.id                         Group Visitors              Read

8          File3   etc etc


If anyone has any ideas what I'm doing wrong I would appreciate the help. Thank you in advance.


Why can't I type my own user name in my search in PowerShell

$
0
0

I can hit tab and get the result I'm looking for, but it won't accept when I type the "M" in my own name. I'm new to this and am thoroughly confused what the underlying issue is here. Any and all information would be appreciated, thanks!....

Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

PS C:\Users\Jacob Markus Osborne> pwd

Path
----
C:\Users\Jacob Markus Osborne


PS C:\Users\Jacob Markus Osborne> cd..
PS C:\Users> pwd

Path
----
C:\Users


PS C:\Users> cd C:\Users\Jacob Markus Osborne
Set-Location : A positional parameter cannot be found that accepts argument 'Markus'.
At line:1 char:1
+ cd C:\Users\Jacob Markus Osborne
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Set-Location], ParameterBindingException
    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetLocationCommand

PS C:\Users> cd 'C:\Users\Jacob Markus Osborne\'
PS C:\Users\Jacob Markus Osborne> pwd

Path
----
C:\Users\Jacob Markus Osborne


PS C:\Users\Jacob Markus Osborne>

Blog post: PowerShell Tutorial Mini-Course: Building a Server Inventory Script

$
0
0
Hello fellow scripters, I thought I'd just this in here in case it may help someone.

Summary: In this free 9,000-word PowerShell tutorial (mini-course), learn how to build a real-world script step-by-step. This is a must read for PowerShellers.

https://adamtheautomator.com/powershell-tutorial-mini-course

Blog post: How to Check for a Pending Reboot in the Registry (Windows)

$
0
0
Hello fellow scripters, I thought I'd just this in here in case it may help someone.

Summary: Learn how to check for a pending reboot the registry on Windows Servers and how to automate it in this tutorial!

https://adamtheautomator.com/pending-reboot-registry-windows

Read PSScriptInfo

$
0
0

Hi

I have updated my ps1 files with a PSscripinfo like:

<#PSScriptInfo

.VERSION 19.0.211.8

.GUID 93cff3b2-1891-4b62-94a1-9f7a31a33639
…
#>

But how do i read this from the script itself? 

I would like to get the version number for a log.

Thanks

Kim

Enabling Office 365 ProPlus for users who already have an E3 license

$
0
0

I need to enable Office 365 ProPlus for users who already have an E3 license. These users also have Skype for Business Online (Plan 2) and the Audio Conferencing licenses enable which MUST NOT be disabled.

I have found the below article and have made rectified a couple of typo's (see script at end), but I am getting the error below. Do I need to have all of the other disable services in the array? for example:

"BPOS_S_TODO_2","FLOW_O365_P2","POWERAPPS_O365_P2","TEAMS1","SWAY","YAMMER_ENTERPRISE","SHAREPOINTWAC","SHAREPOINTENTERPRISE","RMS_S_ENTERPRISE","FORMS_PLAN_E3","PROJECTWORKMANAGEMENT","EXCHANGE_S_ENTERPRISE","Deskless","STREAM_O365_E3","KAIZALA_O365_P3","MICROSOFT_SEARCH","WHITEBOARD_PLAN2","MIP_S_CLP1","MYANALYTICS_P2"

Set-MsolUserLicense : Unable to assign this license because the license options are invalid.
At line:54 char:1+ Set-MsolUserLicense –User $Upn –LicenseOptions $LicenseOptions
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : OperationStopped: (:) [Set-MsolUserLicense], MicrosoftOnlineException+ FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.InvalidUserLicenseOptionException,Microsoft.Online.Administration.Automation.SetUserLicense

https://blogs.technet.microsoft.com/zarkatech/2012/12/05/bulk-enable-office-365-license-options/

# Import login credentials that are stored in the .cred file (XML Format)
$credential = Import-CliXml -Path "C:\Scripts\MSOL-OnlineCredentials-username.Cred"

# Create Connection to Skype for Business Online
Connect-MsolService -Credential $credential


Import-Csv c:\o365AssignOption.csv | ForEach {

#Get-MsolUser –All | Where { $_.IsLicensed –eq $true } | ForEach {

$Upn = $_.UserPrincipalName
}

$Exchange = "Disabled"; $SharePoint = "Disabled"; $Lync = "Enabled"; $Office = "Disabled"; $WebApps = "Disabled"


#We retrieve the assigned license and make note of which options are actually enabled for the user:

(Get-MsolUser -User $Upn).Licenses[0].ServiceStatus | ForEach {

If ($_.ServicePlan.ServiceName -eq "EXCHANGE_S_ENTERPRISE" –and $_.ProvisioningStatus -ne "Disabled") { $Exchange = "Enabled" }

If ($_.ServicePlan.ServiceName -eq "SHAREPOINTENTERPRISE" –and $_.ProvisioningStatus -ne "Disabled") { $SharePoint = "Enabled" }

If ($_.ServicePlan.ServiceName -eq "MCOSTANDARD" –and $_.ProvisioningStatus -ne "Disabled") { $Lync = "Enabled" }

If ($_.ServicePlan.ServiceName -eq "OFFICESUBSCRIPTION" –and $_.ProvisioningStatus –ne "Disabled") { $Office = "Enabled" }

If ($_.ServicePlan.ServiceName -eq "SHAREPOINTWAC" -and $_.ProvisioningStatus -ne "Disabled") { $WebApps = "Enabled" } }



#create an array and populate the variable with the results from the license audit.  In this example, Office is not added as a disabled option since we will be enabling this service for all users.

$DisabledOptions = @()

If ($Exchange -eq "Disabled") { $DisabledOptions += "EXCHANGE_S_ENTERPRISE" }

If ($SharePoint -eq "Disabled") { $DisabledOptions += "SHAREPOINTENTERPRISE" }

#If ($Lync -eq "Disabled") { $DisabledOptions += "MCOSTANDARD" }

#If ($Office -eq "Disabled") { $DisabledOptions += "OFFICESUBSCRIPTION" }

If ($WebApps -eq "Disabled") { $DisabledOptions += "SHAREPOINTWAC" }

#Now we can create the license option variable which assigns all services except those that were not already enabled.

$LicenseOptions = New-MsolLicenseOptions –AccountSkuId "tenant:ENTERPRISEPACK" –DisabledPlans $DisabledOptions

#We apply the license to the user account.

Set-MsolUserLicense –User $Upn –LicenseOptions $LicenseOptions

Create GPO with Powershell to add app shortcuts on desktop

$
0
0

Hello,

I have a problem to create a group policy with Powershell to add a program shortcut on desktop. 

How can I use Powershell to create a GPO to set a Desktop Shortcut in the section "User Configuration\Settings\Windows-Settings\Shortcut"?

I can't find anything on registry, only the xml file in sysvol that created with the policy. Next possibility is to copy and edit the XML File, but that's no my target. I need this for several app deployment.

Thank you

Get MAC address of all connected, active network adapters?

$
0
0

Does anyone know how to filter down GetMac's results to only show connected network adapters?

GetMac seems to return two columns: Physical Address, Transport Name

So far I have:

$results = GetMac | Format-Table -AutoSize
$results

I'd like to apply the filter of:

IF "Transport Name" has the word "disconnected" (case insensitive) in it.

All my attempts have failed :(


New user script issues

$
0
0
Import-Module activeDirectory 
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null 
$Firstname = [Microsoft.VisualBasic.Interaction]::InputBox("Enter First Name", "Create New User")
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null 
$Lastname = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Lastname", "Create New User") | Out-Null
$title = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Job title ", "Create New User")| Out-Null
$email = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Job Email", "Create New User") | Out-Null
$department = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Job Department", "Create New User")| Out-Null
$street = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Street", "Create New User") | Out-Null
$city = [Microsoft.VisualBasic.Interaction]::InputBox("Enter City", "Create New User")| Out-Null
$postalcode = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Post Code", "Create New User")
$homephone = [Microsoft.VisualBasic.Interaction]::InputBox("Enter Phone Number", "Create New User")
$PWD=[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.VisualBasic') | Out-Null 
$PWD= [Microsoft.VisualBasic.Interaction]::InputBox("Enter Password ", "Create New User")
$dnsroot = '@' + (Get-ADDomain).dnsroot
$Dname="$firstName " + "$LastName"
$UPN = Get-adforest | select UPNSuffixes -ExpandProperty UPNSuffixes | Out-GridView -PassThru | Select-Object -ExpandProperty UPNSuffixes
$company = "Test Company"
$ou = Get-ADOrganizationalUnit -Filter * | Select-Object -Property DistinguishedName | Out-GridView -PassThru | Select-Object -ExpandProperty DistinguishedName
New-ADUser -Name "$firstName $lastName" -Displayname $Dname -AccountPassword (ConvertTo-SecureString “$pwd” -AsPlainText -force) -GivenName $FirstName  -title $title -EmailAddress $email -Department $department -Company $Company -StreetAddress $street -city $city -PostalCode $postalcode -HomePhone $homephone -SamAccountName "$firstName.$lastName" -Surname $LastName  -UserPrincipalName "$firstName.$lastName@$UPN" -Path $OU -Enabled $TRUE
for ($i = 1; $i -le 100; $i++ )
{
    Write-Progress -Activity "User creation in Progress" -Status "$i% Complete:" -PercentComplete $i;
}
Write-Output "User $Firstname $lastName has been created"


Exchange script issues

$
0
0

Good morning folks.

I am "newish" to Powershell scripting so I am hoping someone can assist me.

Basically, I am using EMS to pull the last 30 days of emails to a specific address from my mail server each month.

Here is what I have so far for dates:

$startDate=Get-Date; 
$endDate=Get-Date; 

$startDateFormatted=$startDate.AddDays(-1).ToShortDateString(); 
$endDateFormatted=$endDate.AddDays(-30).ToShortDateString(); 

From my understanding, This should use today as the start, and 30 days ago as the end.

When I run the command in a normal Powershell, it displays the date 30 days ago so I am assuming it is correct.

When I run it in EMS, it ends up only pulling like 14 days of information. I then changed the number to endDateFormatted=$endDate.AddDays(-60)and it pulled the same 14 days of information. 

Is there something I am missing? Let me know if you need me to include the other half of the script of what information I am pulling.

ANY help is MUCH appreciated. 

How to Split values by delimiters?

$
0
0

I have a script that has a switch, -Add, allowing the addition of 1 role and 1 member (into that role) in a database at a time.

PS> script1.ps1 -Add Database1 role1 member1
PS> script1.ps1 -Add Database1 role1 member2
PS> script1.ps1 -Add Database1 role2 memberx
PS> script1.ps1 -Add Database1 role3
PS> script1.ps1 -Add Database1 role4 membery

It wont be practical to have to run that script everytime if there are more than 1 member or 1 roles/members to add a time. hence, i'd like to update my script with bulk addition of roles/members at once, which would be helpful especially for a TFS use case, in which the user wont have to create multiple releases just to add a couple roles/members for the same database.

i am thinking of implementing a delimiter split, in which for every semicolon, that indicates the start of a new role, and any comma delimited members, all belong to one role unless a semicolon follows (not necessary if its the end of the input, unless it would be hard to achieve something like that with regex?)

pseudocode:

$RoleInput.Split(";") | ForEach { 

    $role = "$_";

    $MemberInput.Split(",") | ForEach { 

        $member = "$_";

        #-Add $DBName $role $member

    }
}

ultimately, i would like to achieve similar to the following:

PS> script1.ps1 -Add Database1 role1;role2;role3;role4 member1,member2;memberx;;membery

this means that for role1, member1 and member2 would be added for role2, memberx is addedfor role3, no member is added, and for role 4, membery is added

how would i achieve this correctly with regex to account for whitespaces, and end of input?

-----

I asked this elsewhere, but havent received compelling suggestions within the limits of the requirement/use case i am bound by as I had hoped. 

https://stackoverflow.com/questions/57261910/how-to-combine-and-split-values-by-delimiter



Get-Group members are truncated on screen

$
0
0

get-group servermanagement | select members

The above script does not display all members it displays the first four members however after the fourth it proceeds with ...}

how do i display all members of the group?

Set-ADUser Multiple Attributes

$
0
0

I am attempting to set multiple attributes against a list of users.  The attributes are coming from a CSV file.

I can import the CSV file, created the ForEach and write-host all of the attributes, so I know this part is working.

The problem I am having is how to use Set-ADUser -Identity $SamAccountName and my group of attributes

(I did not create the custom attributes Company-xxxxx, that was a gift from the previous Administrators)

I have tried using -Replace and -Add and a feeble attempt at an array, arrays and I just dont get along.  Without any luck.

If someone could point me in a direction that would be awesome.  My code is somewhat ugly, as I have been editing, adding, deleting....

#Create Log File
$date = (get-date).ToString('MMddyyy')
$file = New-Item -type file F:\temp\"$date"UserLog.csv -Force

$Attributes = Import-CSV "F:\temp\UserAttrbutes.csv"

ForEach ($Attribute in $Attributes)
{
	$SamAccountName = $null
	$SamAccountName = $Attribute.SamAccountName
	$UserTrue = Get-ADUser $SamAccountName -ErrorAction Stop
	IF($UserTrue -ne $null)
	{
		#$SamAccountName = $Attribute.SamAccountName
		#$UserTrue = Get-ADUser $SamAccountName -ErrorAction Stop
		Write-Host $Attribute.SamAccountName -ForegroundColor Yellow
		
		Write-Host "UPN:" $Attribute.UPN
		Write-Host "Company-CompanyID:" $Attribute.CompanyCompanyID
		Write-Host "Company-EmployeeType:" $Attribute.CompanyemployeeType
		Write-Host "Company-Generic00008:" $Attribute.CompanyGeneric0008
		Write-Host "Company-Generic00009:" $Attribute.CompanyGeneric0009
		Write-Host "Company-Generic0010:" $Attribute.CompanyGeneric0010
		Write-Host "Company-HireDate:" $Attribute.CompanyHireDate
		Write-Host "Company-HREmployeeID:" $Attribute.CompanyHREmployeeID
		Write-Host "Company-JObID:" $Attribute.CompanyJObID
		Write-Host "Company-PositionID:" $Attribute.CompanypositionID
		Write-Host "Company-StoreID:" $Attribute.CompanystoreID
		Write-Host "Company-TerminationDate:" $Attribute.CompanyTerminationDate
		Write-Host "City:" $Attribute.City
		Write-Host "Company:" $Attribute.Company
		Write-Host "Department:" $Attribute.Department
		Write-Host "State:" $Attribute.State
		Write-Host "Street Address:" $Attribute.StreetAddress
		Write-Host "*********************************************************" -ForegroundColor Green
		#$SamAccountName = $Attribute.SamAccountName
		$UPN = $Attribute.UserPrincipalName
		$CompanyCompanyID = $Attribute."Company-CompanyID"
		$CompanyEmployeeType =  $Attribute."Company-employeeType"
		$CompanyGeneric0008 = $Attribute."Company-Generic0008"
		$CompanyGeneric0009 = $Attribute."Company-Generic0009"
		$CompanyGeneric0010 = $Attribute."Company-Generic0010"
		$CGMHireDate = $Attribute."Company-HireDate"
		$CompanyHREmployeeID = $Attribute."Company-HREmployeeID"
		$CompanyJobID = $Attribute."Company-JObID"
		$CompanyPositionID = $Attribute."Company-positionID"
		$CompanyStoreID = $Attribute."Company-storeID"
		$CompanyTerminationDate = $Attribute."Company-TerminationDate"
		$City = $Attribute.City
		$Company = $Attribute.Company
		$Department = $Attribute.Department
		$State = $Attribute.State
		$StreetAddress = $Attribute.StreetAddres
		#Set-ADUser -Identity $SamAccountName -Add -UserPrincipalName $($UPN), -"Company-CompanyID" $($CompanyCompanyID);"Company-employeeType"=$CompanyEmployeeType;"Company-Generic0008"=$CompanyGeneric0008;"Company-Generic0009"=$CompanyGeneric0009;"Company-Generic0010"=$CompanyGeneric0010;"Company-HireDate"=$CompanyHireDate;"Company-HREmployeeID"=$CompanyHREmployeeID;"Company-JobID"=$CompanyJobID;"Company-positionID"=$CompanyPositionID;"Company-storeID"=$CompanyStoreID;"Company-TerminationDate"=$CompanyTerminationDate;City=$City;Company=$Company;Department=$Department;State=$State;StreetAddress=$StreetAddress}
		Set-ADUser -Identity $SamAccountName  -UserPrincipalName $UPN
		add-content $file -Value "$SAMAccountName, was successfully updated" -encoding ascii
	}
	Else
	{
		Write-Warning -Message "User $SAMAccountName Does Not Exist"
		Write-Host "*********************************************************" -ForegroundColor Green
		add-content $file -Value "$SAMAccountName, was does not exist" -encoding ascii
	}
}


Viewing all 21975 articles
Browse latest View live


Latest Images

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