Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

System.Object[] when trying to export PowerShell output in CSV file.

$
0
0

Hello, Could you please  help in correcting the output of below script?

In the CSV file, output for Location field is shown as System.Object[].

$Result=@() 
$users = Get-MsolUser -All
$Rcpt = $users | ForEach-Object{ Get-Mailbox $_.liveid | Select customattribute10}
$users | ForEach-Object {
$user = $_
if ($user.StrongAuthenticationRequirements.State -ne $null){
$mfaStatus = $user.StrongAuthenticationRequirements.State
}else{
$mfaStatus = "Disabled" }

   
$Result += New-Object PSObject -property @{ 
UserName = $user.DisplayName
UserPrincipalName = $user.UserPrincipalName
Location = $Rcpt
MFAStatus = $mfaStatus
}
}
$Result | Export-Csv Newfile.csv


PowerShell Copy the output from a.csv file and paste it in b.csv file column two.

$
0
0

Hi All,

I am new to power-shell.

Question: I have two files. File1 which his a.csv contains the list of IP-ADDRESS and their status with header as IP/HOST-STATUS. File-b which his b.csv contains the list of FQDN with header as IP/HOST-FQDN. I would like to copy the b.csv file to a.csv file in second column NOT IN FIRST column.

desired result should be as follows

IP/HOST-STATUS              IP/HOST-FQDN

10.26.36.7                        x.y.com

10.44.55.66                       g.b.com

PowerShell to connect to an OpenLDAP server over SSL

$
0
0

Hi, scripting guys !

I try to connect to an OpenLDAP server (Linux) using LDAPS (LDAP over SSL) from a Windows-Server 2012r2 using Powershell. It seems a simple thing, but I cannot make it work. I searched the Internet for clues, but the answers given are not working (most of the post are about connecting to an AD server with LDAPS). It would be just great if someone could help me out in here !

My final goal is to connect using a user/password with LDAPS. But as a first step, I am trying to connect anonymously. Of course, I have tested with an LDAP browser that anonymous LDAPS connections are allowed on this server, just to be sure... Here is my code

$ServerName = "xxx" $Port = 636 $dn = "$ServerName"+":"+"$Port"  $c = New-Object System.DirectoryServices.Protocols.LdapConnection $dn $c.SessionOptions.SecureSocketLayer = $True $c.SessionOptions.ProtocolVersion = 3 $c.AuthType = [System.DirectoryServices.Protocols.AuthType]::Anonymous 

$c.Bind()

It does not work. I have a message "LDAP server unavailable".

If I use port 389 and set SecureSocketLayer to $False, the same code works (the server accepts both LDAP and LDAPS connection, for anonymous user).



Powershell script to get local user accounts and disable stale (over 90 day)

$
0
0

I have a script that will output the local users who have not logged in 90+ days. 

Can I pipe the results to the Disable-LocalUser?

Could I just add code to the script to take username results and run the Disable-LocalUser function?

Here is my get info code:

$Today = (Get-Date).Date $MaxDaysOld = 90 $Results = Get-LocalUser -Name * | Where-Object { $_.Enabled } | ForEach-Object { if ($_.LastLogon) { $LastLogon = $_.LastLogon $DaysOld = ($Today - $_.LastLogon).Days } else { $LastLogon = $DaysOld = '_Never_' } if ($DaysOld -eq '_Never_' -or $DaysOld -gt $MaxDaysOld) { [PSCustomObject]@{ Name = $_.Name LastLogon = $LastLogon DaysAgo = $DaysOld } } } $Results

Thanks 

Setting Edge start page

$
0
0

I know there probably is a way, but am having trouble finding it.

I need to set the start page in EDGE using a PS script. It appears that it need to be done via local GPO as changing it in the registry is don't available.

Any help would be appreciated.

Eugene

 

Registering a scheduled job via Powershell Remoting does not work if using local User

$
0
0

Hey helpful people!

I have an issue and I don't understand it:

I want to register a scheduled job on a remote machine, using Credentials of a Local User on the remote Machine.

$PSsession = New-PSSession -Computername "CompName" -Credentials (Get-Credentials)

Invoke-Command -ScriptBlock {Register-ScheduledJob -ScriptBlock {"DoThings"} -Name "myName"} -Session $PSsession

The Session gets established and I can use it with "Enter-PSSession".

But when I try to register the ScheduledJob I get the following Error:


An access denied error occurred when registering scheduled job definition nameme.  Try running Windows PowerShell with
elevated user rights; that is, Run As Administrator.+ CategoryInfo          : PermissionDenied: (Microsoft.Power...edJobDefinition:ScheduledJobDefinition) [Register-S
   cheduledJob], RuntimeException+ FullyQualifiedErrorId : UnauthorizedAccessToRegisterScheduledJobDefinition,Microsoft.PowerShell.ScheduledJob.Reg
   isterScheduledJobCommand+ PSComputerName        : CompName

Some facts about the environment:

- OS of Client and Server are both "Windows Server 2016" (same issue with 2012R2 on the Server side)
- Same issue if the (target-) server is either a Domain or in a Workgroup
- PowershellRemoting enabled, Executionpolicy="unrestriced"
- local User on Server side is in the local Administrators Group and the "Remote Management Group"
- User Account Control is DISABLED
- I logged on locally once with the user I try to use, to create the Profile in the Filesystem
- Windows Firewall is OFF

It WORKS IF I use a Domain User instead of a local user... but I need it to work on Workgroup Servers! 

The problem is reproduceable and I don't get why this does not work. 

Has anybody any idea what causes this problem? I appriciate any helpful advice from you.



www.netlogix.de



Powershell GUI for workstation restart reminder - how to postpone reminder

$
0
0

Hello - fairly new to Powershell and working on a solution for a small subset of our users.  We have mandatory periodic reboots of our workstations, performed at night.  We have folks in an operations monitoring area whose work can be disrupted when we kick off the reboots (via config manager).  So the idea is to give them reminders to reboot when practicable but to not force them.  They choose a postpone notification time in hours from a pulldown.  I have cobbled together code from different scripts I've found and have something that is halfway to working but am having trouble with a couple things.

First, my while statement - when I select a number value in hours to postpone and then click postpone, I want the form to hide or close until the hour interval happens and then it will bring up the form again.  I'm trying to write a null output while the time on click is less than the time plus the number of hours chosen, but I end up immediately running the script again, which I only want to do after the interval. I also tried an if/then but same results.  What it seems I really need to do is be able to sleep for the interval instead of close the script.

Second I wanted to add a description in the form and didn't know how to build it from scratch so I made a blank form in primalforms and then grabbed the label code and inserted but no matter how I adjust the x and y I can't get it to appear in the form.

Note if you run it name it timed_reboot so the variable $scriptpath works.  Thanks for any advice you can offer!

[void][System.Reflection.Assembly]::LoadWithPartialName( “System.Windows.Forms”)
[void][System.Reflection.Assembly]::LoadWithPartialName( “Microsoft.VisualBasic”)

$form = New-Object “System.Windows.Forms.Form”;
$form.Width = 425;
$form.Height = 150;
$form.Text = "Computer Reboot Notification";
$form.StartPosition = [System.Windows.Forms.FormStartPosition]::CenterScreen;
$DropDownArray = @("1", "2", "3", "4")
$DDL = New-Object System.Windows.Forms.ComboBox
$DDL.Location = New-Object System.Drawing.Size(170,30)
$DDL.Size = New-Object System.Drawing.Size(80,40)

# sets path to script to current directory
$executingScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
$scriptPath = Join-Path $executingScriptDirectory "timed_reboot.ps1"

$form1 = New-Object System.Windows.Forms.Form
$label1 = New-Object System.Windows.Forms.Label
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 130
$System_Drawing_Point.Y = 10
$label1.Location = $System_Drawing_Point
$label1.Name = "label1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 21
$System_Drawing_Size.Width = 272
$label1.Size = $System_Drawing_Size
$label1.TabIndex = 0
$label1.Text = "Please select the number of hours to delay notification"

ForEach ($Item in $DropDownArray) {

    $DDL.Items.Add($Item) | Out-Null

}
$DDL.SelectedIndex  = 0

$button1 = New-Object “System.Windows.Forms.button”;
$button1.Left = 30;
$button1.Top = 85;
$button1.Width = 100;
$button1.Text = “Reboot Now”;
$button1.Add_Click($button1_OnClick)
$button1_OnClick = {Restart-Computer -Force -ComputerName localhost}

$button2 = New-Object “System.Windows.Forms.button”;
$button2.Left = 155;
$button2.Top = 85;
$button2.Width = 100;
$button2.Text = “Postpone”;
$button2.Add_Click($button2_OnClick)
$button2_OnClick = {
   $Time_On_Click = (Get-Date -Format g)
   $AddHours = (Get-Date -Format g).AddHours($textBox_Sender.text)  
  
    while ($Time_On_Click -lt $AddHours)
    
    {
        
        Write-Output = $Null
        $form.close()
        
    }
        
        invoke-expression "$scriptPath"
    }
$button3 = New-Object “System.Windows.Forms.button”;
$button3.Left = 290;
$button3.Top = 85;
$button3.Width = 100;
$button3.Text = “Abort Shutdown”;
$button3.Add_Click($button3_OnClick)
$button3_OnClick = {$form.Close()}

$form.Controls.Add($button1);
$form.Controls.Add($button2);
$form.Controls.Add($button3);
$form.Controls.Add($DDL);
$form.Controls.Add($textLabel1)
$ret = $form.ShowDialog();
$form.Controls.Add($label1)

$form.KeyPreview = $True
$form.Add_KeyDown({if ($_.KeyCode -eq "Enter") 
    {$x=$textBox1.Text;$form.Close()}})
$form.Add_KeyDown({if ($_.KeyCode -eq "Escape") 
    {$form.Close()}})

Use WMI to find office version while differentiating between Office 2016 and 2019

$
0
0

Title says it all!

Set objWord = CreateObject("Word.Application")

wscript.echo objWord.Name

wscript.echo objWord.Caption

wscript.echo objWord.Version

wscript.echo objWord.Build

objWord.Quit

So far I've got the above script to display:

Microsoft Word

Word

16.0

16.0.11901

However, I'm running Word 2019 and need to be able to differentiate between whether Office16 is relating to 2016 or 2019 using anything that can be rolled out using GPO but preferably WMI.

Any help is appreciated!


Removing a SID from the local administrator's group

$
0
0

Good morning, I have recently built a tool which removes domain users from the local administrators group using a text file for input of the machine name and user name.  Yesterday, I was asked to remove a dead account that only shows up as a SID in the local administrators group of ~1400 machines.  I tried using my program with a couple of minor modifications (my current tool uses SCCM to run net localgroups .... /delete, but I noticed none of the 15 test machines I used to create my initial collection had the account removed.

Some caveats, I can not use PSExec, it's frowned upon in our network environment. 

My VB and powershell skills are minimal (we use wise scripting for almost everything).

Please help

Thanks, Rick 

Get-MessageTrace cmdlet not available in Powershell

$
0
0

Hello All, 

I am new to Powershell and I have many questions, however for now just one :)

After experiencing a long wait for O365 to return info for a message trace, I read that PS can perform the same task exceptionally quickly.

I have installed the AzureAd module, Installed MSOnline module and connected to AzureAD from PS.

I can run cmdlets, however the Get-MessageTrace cmdlet does not seem to exist.

This is what returns;

PS C:\Users\Jim.Beam> Get-MessageTrace
Get-MessageTrace : The term 'Get-MessageTrace' is not recognized as the name of a cmdlet, function, script file, or
operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:1
+ Get-MessageTrace
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (Get-MessageTrace:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

A noob question for you guru's out there, however any help is appreciated!

Thank you!

Sozo.

Azure App Gateway alert

$
0
0

Hi,

I need a PowerShell script to trigger an alert whenever azure application gateway backend health turn to red. I have 2 subscriptions, under this, we have around 150+ Application Gateway provisioned. so the script should be reusable across all the subscription. it would be great, if any sample script available for the reference.

Thanks

Suri

Powershell script scan folders and subfolders and list details about files

$
0
0

I am trying to find a way to record all the details about my files on my server, as I have discovered that when I run my media files through Handbrake, they are losing they creation date, last used etc.

so I have hunted around and found this script that records the information I would like, but I am having issues working out how to get it to go deeper into the folder structure and record each file. cos at the moment all it does is list the root folders.

my folder structure looks like this

media \ year \ locations \ Files

I hope that someone can help me with this little problem.

# OldTime.ps1 - Start

. .\OldTime-record.ps1

for($i = 0; $i -lt $file.count; $i++) {

    write-output "$($file[$i])"

    write-output "$($time[$i])"   

Set-ItemProperty -Path $($file[$i]) -Name CreationTimeUTC -Value $($time[$i])   

Set-ItemProperty -Path $($file[$i]) -Name LastWriteTime -Value $($time[$i]) }

# OldTime.ps1 - End


    


Not given enough time to run batch

$
0
0

Hello all,

    I am trying to run:

pause
FOR /F "delims=" %i IN ('systeminfo ^| findstr /B /C:"OS Name"') DO set test=%i
pause
SET test=%test:~27%

echo|set/p=%test%%ComputerName%|clip

but it seems like the for loop is not given enough time to run.  The first pause works fine for my testing purposes, but then I get nothing in the clipboard.  I am running a .bat file and not powershell file.  Any ideas in how to make this thing run correctly?

Powershell GUI to Restart after 1 hour deferment

$
0
0

Hey Folks!

Trying to do the following, but haven't found anything that's quite what I need, and am relatively new to powershell.  I've been cobbling together and pouring over at least 10 different scripts and trying to find a resolution.

I've been tasked with creating a script (with gui) to restart workstations that haven't been rebooted in at least 7 days, and when the prompt comes up, it gives them two options, Reboot, or Defer - 1 Hour.  Then after that hour is up, it comes backup, but only with the Reboot option.

I borrowed the script from here, which GUI-wise looks great, but I'm having difficulty figuring out the logic for what I need it to do.  I understand the logic, but not sure how to get it done (am taking some powershell courses and have been down many a rabbit hole over the past few weeks on this).  

I wouldn't be using the schtasks option, just need to set a timer that brings the gui back up after 60 minutes, and only has the reboot option (which I can tie to shutdown /r /t 0).

I wasn't sure about posting code from the gallery on here, but can do so if it's ok.

arrary values into read-host and output is array values

$
0
0

First of all thank you guys for taking the time to answer my question, I am actually curious to know whether this is possible in PowerShell and how doable this project is.

so lets say I provide a custom value to each letter of the alphabet (a-z) , the value of each letter is 3 characters for each letter (lowercase and uppercase) 

$a = m3Q

$A = xeR

$b = ToH

then I put this on an array 

$array = @("$a", "$A", "$b")

how would I go about using this for text substation? what I'm trying to achieve is to create a form of a cipher with PowerShell by hard coding the values into each letter of the alphabet and able to encrypt the text so is unreadable. in my case I have all letters and numbers with each character with a random value however I still cannot think of a way to use this array as input and output. if using input substitution is not possible I think I can look into python for something like this however I think PowerShell can do this.

I am also aware of using different types of encryption in PowerShell like AES, but what if I want to disregard that and create my own?

if anybody can point me in the right direction so I can break my head with this task I'll gladly appreciate it. 


IF Vmware doesn't have snapshot. Send email "No snapshots found"

$
0
0

Hello,

Could you please help me modify the script below? The script below will check snapshots in Vsphere and will send a report in an email. I wanted to edit the script below like if it doesn't find any snapshots it will send an email with the body/contents that says "No snapshots found". 

Add-PSSnapin VMware.VimAutomation.Core

Connect-VIServer -Server 'vcenter' -User 'login' -Password 'password'

$Snapshots = Get-VM | Get-Snapshot | select Description,Created,VM,Name,SizeMB,SizeGB

function Get-SnapshotSize ($Snapshot)
{
    if ($snapshot.SizeGB -ge "1")
    {
        $Snapshotsize = [string]([math]::Round($snapshot.SizeGB,3)) + " GB"
        }
        else {
        $Snapshotsize = [string]([math]::Round($snapshot.SizeMB,3)) + " MB"
        }
   Return $Snapshotsize
}

function set-SnapshotDate ($snapshot)
{
    $greenValue = (get-date).AddDays(-7)
    $RedValue = (get-date).AddDays(-14)
    
    if ($snapshot.created -gt $greenValue)
        {
            $backgroundcolor = "green"
        }
    elseif ($snapshot.Created -lt $greenValue -and $snapshot.Created -gt $RedValue)
        {
            $backgroundcolor = "yellow"
        }
    else 
        {
        $backgroundcolor = "red"
        }
    return $backgroundcolor
}

function Format-HTMLBody ($body)
{
    $newbody = @()
    foreach ($line in $body)
    {
        ## Remove the Format Header
        if ($line -like "*<th>Format</th>*")
            {
                $line = $line -replace '<th>Format</th>',''
            }
        ## Format all the Red rows
        if ($line -like "*<td>red</td>*")
            {
                $line = $line -replace '<td>red</td>','' 
                $line = $line -replace '<tr>','<tr style="background-color:Tomato;">'
            }
        ## Formating all the Yellow Rows
        elseif ($line -like "*<td>yellow</td>*")
            {
                $line = $line -replace '<td>yellow</td>','' 
                $line = $line -replace '<tr>','<tr style="background-color:Orange;">'
            }
        ## Formating all the Green Rows
        elseif ($line -like "*<td>green</td>*")
            {
                $line = $line -replace '<td>green</td>','' 
                $line = $line -replace '<tr>','<tr style="background-color:MediumSeaGreen;">'
            }
        ## Building the new HTML file
            $newbody += $line
    }
    return $newbody
}

$date = (get-date -Format d/M/yyyy)
$header =@"
 <Title>Snapshot Report - $date</Title>
<style>
body {   font-family: 'Helvetica Neue', Helvetica, Arial;
         font-size: 14px;
         line-height: 20px;
         font-weight: 400;
         color: black;
    }
table{
  margin: auto;
  width: 100%;
  box-shadow: 0 1px 3px rgba(0,0,0,0.2);
  display: table;
  border-collapse: collapse;
  border: 1px solid black;
  text-align: center;

}
th {
    font-weight: 900;
    color: #ffffff;
    background: black;
    text-align: center;
    vertical-align: middle;
    border-style: ridge;
   }
td {
    border-bottom: 1px solid black
    }
</style>
"@

$PreContent = "<H1> VM Snapshots Report for " + $date + ".</H1>"
$Footer = "<h3> Please check and investigate accordingly </h3>"
$html = $Snapshots | select VM,Name,@{Label="Size";Expression={Get-SnapshotSize($_)}},Created,@{Label="Format";Expression={Get-SnapshotDateStyle($_)}}| sort Created -Descending | ConvertTo-Html -Head $header -PreContent $PreContent

$Report = Format-HTMLBody ($html)


$MailParam = @{ 
 To = "recepient" 
 From = "sender"
 SmtpServer = "smtpserver"
 Subject = "Daily Snapshot Report"
 body = ([string]$Report) 

}

Send-MailMessage @MailParam -BodyAsHtml
Disconnect-VIServer -Confirm:$false

Help with text comparison from a couple sources

$
0
0

Hi all, 

So I have been working on this for some time and just can't seem to get my head around the right solution.

Essentially what I trying to do is automate the updating of a list of users for a migration effort. 

The data I have is as follows:

One list comes in a spread sheet with names in the form Last, First 

Another list is a spreadsheet that contains all staff but is in a form of UNCPath, URL

Basically my end goal here is to take the first list and remove the people it contains from the second. 

I found the UNCPath is in the form \\servername\folder1\folder2\folder3 where folder3 turns out to be the samaccount name.

I was thinking of the following logic:

  1. Import csv files
  2. get samaccount name from either Name or combo of Givenname and Surname attributes
  3. get samaccount name from UNC path
  4. Compare names
  5. If a name matches, remove that entry from second csv file

I have the following scripted but keep running into issues with compare

$dirs = import-csv srclist.csv | select -ExpandProperty DIRECTORY
$names = import-csv names2.csv -Header last,first

foreach ($dir in $dirs)
{
    foreach( $name in $names)
    {

        $sam1 = $dir | Split-Path -Leaf
        $firstfilter = $user.first
        $secondfilter = $user.last
        $sam2 = Get-ADUser -Filter {GivenName -like $firstfilter -and Surname -like $secondfilter} | select-object samaccountname

        if ($sam1 -eq $sam2)
        {
            $sam1
            $sam2
        }
    }
}

I am stuck here...the if statement was just me testing to see if I could actually get antything relevant with nested foreachs like that.

Any help would be greatly appreciated!

Creating a script for lockout statistics over a period of ~30 days

$
0
0

Greetings,

I have created a simple piece of code to make an account lockout checker and unlock tool on powershell, im very new to it and just getting the hang of it, im trying to implement this into my work environment (IT ServiceDesk) and was hoping to try and get a script that can provide the statistics against lockouts over a period of say, 30 days. I have pasted my code below and if there is any advice that would be great.

 
Import-Module ActiveDirectory
cls
write-host "------------------------------------------------------------------------------------" -ForeGroundColor Magenta
write-host "|--Please note that this script is subject to change and is not the final version--|" -ForegroundColor Green 
write-host "| Welcome to the pre-release of the AD Account unlocker and Lockout checker script |" -ForegroundColor Yellow
write-host "| ------------------------------This is version 1.40------------------------------ |" -ForegroundColor Green
write-host "| -------Please can any suggestions or errors be reported to Ben Cotterell!------- |" -ForegroundColor Yellow
write-host "------------------------------------------------------------------------------------" -ForegroundColor Magenta

DO {
write-host "Please select one of the below scripts to run using the appropriate key assigned beforehand"
write-host "[O] Lockout Checker Tool"
write-host "[P] Account unlocker"
$answer = Read-Host "Option"
write-host " "
IF ($answer -eq "o"){
    #LockoutChecker
    Search-ADAccount -LockedOut | Select-Object -Property SamAccountName,PasswordExpired,LastLogonDate
    }

ELSEIF ($answer -eq "p"){
    #AccountUnlocker
    Search-ADAccount -LockedOut | Unlock-ADAccount -Confirm
    }
}UNTIL($answer -eq "End")

   


When running this it works fine other than the fact when it opens if I select the 'O' option, nothing happens and it just asks me to input another option, when I then input 'O' again it pastes out the information regarding lockouts twice. When I then press it 1 more time it gives me the data without any duplications but it removes the information bar at the top (SamAccountName,PasswordExpired,LastLogonDate).

Any help is greatly appreciated, cheers


Removing an item from the ribbon in Word

$
0
0

Hello all,

I need help adding a new entry in my Word.OfficeUI file to remove an add-in from the ribbon.  The file currently reads

<mso:customUI xmlns:x2="Mindjet.Mm18Word.AddIn.12" xmlns:mso="http://schemas.microsoft.com/office/2009/07/customui">
<mso:ribbon>
<mso:qat/>
<mso:tabs>
<mso:tab idQ="mso:TabHome">
<mso:group idQ="x2:MindjetGroup" visible="false"/>
</mso:tab>
</mso:tabs>
</mso:ribbon>
</mso:customUI>

I need to add in the PDFMakerOfficeAddin entry and set visibility to false.  Resulting file should look like this

<mso:customUI xmlns:x2="Mindjet.Mm18Word.AddIn.12" xmlns:x1="PDFMaker.OfficeAddin" xmlns:mso="http://schemas.microsoft.com/office/2009/07/customui">
<mso:ribbon>
<mso:qat/>
<mso:tabs>
<mso:tab idQ="mso:TabHome">
<mso:group idQ="x1:ACROBAT_SHARE" visible="false"/>
<mso:group idQ="x2:MindjetGroup" visible="false"/>
</mso:tab>
<mso:tab idQ="x1:ACROBAT_RIBBON"/>
</mso:tabs>
</mso:ribbon>
</mso:customUI>

I'm banging my head against a wall here. Any help would be appreciated!

Office 365 Bulk UPN Update

$
0
0

Hello,

I have a list of users in a CSV, has current UPN of "ID@domain.com", and ObjectID of each user. Each user has been added to Office 365 with their numeric ID as their logon and UPN name, but we are wanting to change that to Firstname.Lastname@subdomain.domain.com. As you can see, the UPN has to be changed to subdomain.domain.com, rather than domain.com.

The Firstname.Lastname@subdomain.domain.com has to be their primary email address (SMTP, not smtp), and it also has to become their Office 365 login/username.

So far I have this:

Import-Module -Name MSOnline
$Cred = Get-Credential
Connect-MsOnline -Credential $Cred
$O365Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://ps.outlook.com/powershell -Credential $MyCredential -Authentication Basic -AllowRedirection 
Import-PSSession $O365Session -AllowClobber 

#CSV from export which has been filtered to only contain student accounts. This will add the value of accounts to their department value.
Import-Csv "c:\users\user\data.csv" | foreach { Set-MsolUser -Department Test}

#This is receiving all the user objects via Azure AD, and filtering by the department value. The new UPN is then applied to users based on that filter
Get-Msoluser -Department "Test" | foreach { Set-MsolUserPrincipalName -UserPrincipalName $_.UserPrincipalName -NewUserPrincipalName ($_.firstname + "." + $_.lastname + '@subdomain.domain.com')
}

However this is the error that is returned:

Set-MsolUserPrincipalName : Input exceeded the maximum allowable length for the field.  Parameter Name: Mail.
At line:1 char:26+ ... | foreach { Set-MsolUserPrincipalName -UserPrincipalName $_.UserPrinc ...+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : OperationStopped: (:) [Set-MsolUserPrincipalName], MicrosoftOnlineException+ FullyQualifiedErrorId : Microsoft.Online.Administration.Automation.StringLengthValidationException,Microsoft.Online.Administration.Automation.SetUserPrincipalName

I can confirm the domain is verified, and that this is not a ADSync / On-Prem implementation, it's purely a cloud based approach.

Thank You



Viewing all 15028 articles
Browse latest View live


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