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

inventory of all ADDS resources in a hybrid organization

$
0
0

Hello MS team,

Can someone please provide me with a nice PowerShell script to collect all information regarding ADDS in a hybrid organization [on premises- Azure]?

Any information that you can share would be really appreciated

Cheers


Franki


Need help with my first powershell script

$
0
0

Hi all, so I am trying to teach myself some powershell basics and create a script. I have a bunch of ebooks in a directoty with the same filename structure, "author - title.mobi". So from scratch I created this script, but am having trouble getting it to run. The script should make an array of filenames in a given directory, split it by the dash into author and title, create an author folder within the directory, rename the old mobi file to title.mobi, and move it to the new author folder. I cant get it to go past creating a new directory. Any hints? Heres the code:

Write-Host "enter full book folder path:"
$folder = read-host

$listofbooks = split-path $folder"\*.mobi" -leaf -resolve

$count = $listofbooks.count
$n = 0

if($n -lt $count)
{
    $author,$title = $listofbooks[$n].split(' - ',2)    $title -replace ".txt", ""    #MKDIR $folder"\"$author    if(!(test-path $folder"\"$author)) # If the Artist folder doesn't exist                {                    MKDIR $folder"\"$author                }    rename-item $folder\$listofbooks($n)".txt" $title".mobi"    move-item -path $folder\$author".mobi" -destination $folder"\"$author"\"$title".mobi"    $n = $n + 1    write-host "done"
}




Ad Health checkup monitor

$
0
0

Hi All,

i had query in ad health checkup  script , how to add our  e-mail recipients in that script such as from and to

$smtphost = "SMTP.labtest.com"  $from = "DoNotReply@labtest.com"  $to = "Sukhija@labtest.com" $timeout = "60"

Please delete

Deleting a folder in all users profiles

$
0
0
Hi All,

I have a VBScript that recursively searches all user profiles and deletes a folder that I specify, for the sake of it lets call it Example. The script works fine in XP but won't work in Windows 7.

In XP, it will go to C:\Documents and Settings\ and scan through all user profiles and delete the Example folder which is exactly what I want.

In Windows 7, it goes to C:\Users and checks C:\Users\Administrator and then exits without scanning any other profile. The strange this is, if I change the script to scan c:\temp and add profiles then it scans through them and deletes Example as required.

Is there a trick to recursively scanning through c:\users? Below is the script that I am using (not my work, I am not capable of scripting such things) with the rootFolder set for Windows 7 C:\Users

Cheers,
Harry

**********************************************************************************************

on error resume next

dim folderSpec, count

Set ws = WScript.CreateObject("WScript.Shell")

Set fs = wscript.createobject("Scripting.FileSystemObject")


rootFolder = "C:\Users\"

folderSpec = "Example"

wscript.echo "Start"
count = 0

deleteAllFolders (rootFolder)

wscript.echo "Finished. Deleted " & count & " folders called " & folderSpec & " from " & rootFolder

'Deletes all folders in 'rootFolder' that are called 'folderSpec'
Sub deleteAllFolders(rootFolder)
set folderCollection = fs.GetFolder(rootFolder)
wscript.echo "Starting at folder: " & rootFolder
for each subFolder in folderCollection.subFolders
wscript.echo "Checking folder: " & subfolder.path
RecursiveSearchAndDelete(subFolder.path)
next
end sub

sub RecursiveSearchAndDelete(path)
set folderCollection = fs.GetFolder(path)
For Each Subfolder in folderCollection.SubFolders
if subFolder.name = folderSpec then
subfolderPath = subfolder.path
wscript.echo "* Found: " & folderSpec & " at " & subfolderPath
wscript.echo "* Deleting: " & subfolderPath
set folderToDelete = fs.GetFolder(subfolderPath)
folderToDelete.delete(true)
if err.number <> 0 then
wscript.echo "* An error occured deleting: " & subfolderPath
else
wscript.echo "* Deleted: " & subfolderPath
count = count + 1
Exit For
end if
end if
RecursiveSearchAndDelete Subfolder
Next
end sub

PS script won't start in task scheduler

$
0
0

i though i have it pat down but the script i need to run won't start in task scheduler.

i have correctly (i think) specified what needs to be run:

C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe

and its argument:

C:\Users\myhome\OneDrive\scripts\passwordReminder.ps1

in the "Conditions" tab i have no checked tick boxes. i'm using my domain admin account to run it too (even if not logged in).

what else am i missing?

How to use PowerShell to detech a popup window which ask for credential

$
0
0

Hello,

I have a remote PowerShell script which I use to connect to Office 365 Exchange server and pull the mailbox information like user DisplayName and email address etc., this is a simple script but need to get the information for around 70k mailbox, so it will take quite a while - 2-3 hours. I have my password store in a secure txt file, and the script will read this file to get the password, so I don't need to key in the user name and password to connect to the remote Exchange server, it's all automatically.

However as the script runs for 2-3 hours, for some reason the remote PowerShell session will timeout from time to time (might be other reason I don't know) and popup a window ask for user name and credential again, and the script was stuck until I manually key in the credential.

So anyone know how to let the same PowerShell script to detech this popup window and automatically input the credential without manual intervention? I have been struggling on such issue for a long time but don't know how to fix it.

Thanks in advance!

Mark Liu


Foldersize problem with sort

$
0
0

Hi,

I  create a ps script to scan a specific folder on the server, it works well  but the only thing is the sort. It should sort by size descending but it doesn't work.  The strange thing is, if I scan other directories it works.

Anyone knows why ?

Thank you very much

$startfolder = "x:\profiles"

# Mail
$mailto = "admin@xx.xx"
$mailfrom = "size@xx.xx"
$mailserver = "xx.xx.xx.x"

# HTML
$html = "<style>"
$html = $html + "BODY{background-color:white;font-family: arial;}"
$html = $html + "TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse; font-family: arial; font-size: x-small;}"
$html = $html + "TH{border-width: 1px;padding: 4px;border-style: solid;border-color: black;background-color:#B9DCFF; font-family: arial; font-size: x-small;}"
$html = $html + "TD{border-width: 1px;padding: 4px;border-style: solid;border-color: black;background-color:#D9ECFF; font-family: arial; font-size: x-small;}"
$html = $html + "</style>"

# Date
$date = get-date -format "dd_MM_yyyy"

$profilefolder = Get-ChildItem $startfolder |where { $_.PSIsContainer }

$array = @()
foreach ($h in $profilefolder)
    {
	$profilesize = "{0:N2}" -f ((Get-ChildItem -path $h.Fullname -recurse | Measure-Object -property length -sum ).sum /1GB)
	$object = New-Object -TypeName PSObject
	$object | Add-Member -Name 'Login_Name' -MemberType Noteproperty -Value $h.Name
	$object | Add-Member -Name 'ProfileSize_in_GB' -MemberType Noteproperty -Value $profilesize
	$array = $array + $object
	}
$body = $array | sort-object ProfileSize_in_GB -Descending | ConvertTo-Html -head $html -body "<H3>Profile </H3>" | Out-String


			$messageParameters = @{
				Subject = $subject = " Userprofile - $datum"
				Body = $body
				From = $mailfrom
				To = $mailto
				SmtpServer = $mailserver
				}
		    Send-MailMessage @messageParameters -BodyAsHtml -Encoding ([System.Text.Encoding]::UTF8) 


Using Richcopy to sync folders

$
0
0

I have a few network folders which I would like to automatically make offline copies of in the event of a disaster (think disaster recovery information).

 

I can script richcopy to perform the copy, but I can't interpret the error codes that it returns.  Also, the log file richcopy creates seems to be in some weird format, making it difficult for me to parse it and look for any errors.

 

Any thoughts?

Distinguished Name AD User creation

$
0
0

Hi there, 

I'm creating a Gui interface to create AD users from some textbox fields. However I need the Userprincipalname to be populated with the "@domain.local" suffix. I have the following code: 

$HashArguments = 
       @{ Name = $WPFlogonName.Text;
          GivenName=$WPFfirstName.Text;
          SurName = $WPFlastName.Text;
     UserPrincipalName = $WPFlogonName + '@test.local'.Text; 
          AccountPassword=($WPFpassword.text | ConvertTo-SecureString -AsPlainText -Force);
          Path=$TargetOU;
          }

I try to get the UserPrincipalname from the $WPFLogonname.Text value and create the user with a Hash command: 

$WPFMakeUserbutton.Add_Click({
    #Resolve Form Settings
    $hash = Get-FormFields
    New-ADUser @hash -PassThru
    $Form.Close()})

However the script tells me there is no method in textboxts that accepts a Op Addition: 

Method invocation failed because [System.Windows.Controls.TextBox] doesn't contain a method named 'op_Addition'.

How can I do this without creating an extra textbox for putting in the UPN, because people will make mistakes filling this in manually, or how can I prepopulate a textbox with the @domain.local suffix to be a whole word without doing an Addition? 

Thanks!


2 Years old email count

$
0
0
I am looking for a possible solution to find number of emails which are 2 years old for each and every user mailbox at O365. Can you suggest some script which can help me here.

Running a VBS script with no prompt and elevated permissions

$
0
0

Need to run a vbs that silently opens a batch file - which stops a service in this case, however need a line or two allowing it to runas (Windows 2012) 

These are for training labs where the student should not see what the script is doing and cannot access the folder where the actual BAT file is. 

Here is the basic vbs: 

Set WshShell = CreateObject("WScript.Shell" ) 
WshShell.Run chr(34) & "D:\TrainingScripts\Script01.bat" & Chr(34), 0
Set WshShell = Nothing 

Please can someone put me out of my misery where to add something like:  &"""", , "runas", 1

Thank you

gMSA + Task Scheduler v.4

$
0
0

Long time Windows administrator but recently just got into powershell. We run our scheduled task using gMSA accounts in our environment because it meets STIG's. In doing so, I learned how to create Scheduled Task using powershell since it is the only way to use gMSA with task. I searched these forums and found one post about modifying the xml but I don't quite understand the how to. I use the same ps1 script to create all my task and just edit the variables as needed. This is also good in case I have to rebuild a server or I get hit by a bus and the new admin understands how to do my job. But the task which need to run on a specified monthly date is eluding me.

Here is my go to script for creating task schedules for creating gMSA task. I cannot seem to figure out how to get it to run on a monthly basis. For example, I have one task I would like to run on the 25th of every month.

        #Path to powershell script
        $F = "c:\SchTsk\File_Management.ps1"

        #The first command uses the New-ScheduledTaskAction cmdlet to assign the action variable $A to the executable file tskmgr.exe
        $A = New-ScheduledTaskAction -Execute "C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe" -Argument "-noexit -ExecutionPolicy Bypass -File $F"

        #The second command uses the New-ScheduledTaskTrigger cmdlet to assign the trigger variable $T to the value AtLogon
        $T = New-ScheduledTaskTrigger -weekly -DaysOfWeek Saturday -At 7am

        #The third command uses the New-ScheduledTaskSettingsSet cmdlet to assign the settings variable $S to a task settings object
        $S = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -DontStopOnIdleEnd -ExecutionTimeLimit 1:00:00 -MultipleInstances 2

        #The fourth command assigns the principal variable to the New-ScheduledTaskPrincipal of the scheduled task, domainname\gMSA_account$
        $P = New-ScheduledTaskPrincipal -UserId domainname\gMSA_account$ -LogonType Password -RunLevel Highest

        #The fifth command sets the description varible to $D for the task definition
        $D = "Edit C:\SchTsk\File_Management.ps1"

        #Register the scheduled task
        Register-ScheduledTask Monthly_File_Management -Action $A -Trigger $T -Settings $S -Principal $P -Description $D
Thank's

Why is my Invoke-expression statement not working?

$
0
0

I am using the below script to listen to a UNC path and then filter on a .tar file that's created. The script then copies the last created .tar file to another location where it is to be unzipped (untarred) as the next step in the process. However, the script breaks just after it performs the copy and seems to never reach the Invoke-expression statement. I can execute the expression itself in a powershell script alone and it performs well. Now it seems to go out to lunch without having ever processed the Invoke statement. Can somebody please tell me what I'm doing wrong? Thanks!

$folder = "\\catl0dv603\DouglasUNCTest"
$filter = "*.tar"                             # <-- set this according to your requirements
$dest = "C:\A_uxdesign\test"
$scriptPath = "C:\A_uxdesign\UnzipTarFile.ps1"

$fsw = New-Object System.IO.FileSystemWatcher $folder, $filter -Property @{
 IncludeSubdirectories = $true;           # <-- set this according to your requirements
 NotifyFilter = [System.IO.NotifyFilters]"FileName, LastWrite"

}

#register ObjectEvent
$onCreated = Register-ObjectEvent $fsw Created -SourceIdentifier FileCreated -Action {
 $path = $Event.SourceEventArgs.FullPath
 $name = $Event.SourceEventArgs.Name
 $changeType = $Event.SourceEventArgs.ChangeType
 $timeStamp = $Event.TimeGenerated
 Write-Host "The file $name was $changeType at $timeStamp" -ForegroundColor Yellow
 Write-Host "Waiting for copy job to finish ..." -ForegroundColor Cyan

Copy-Item "\\catl0dv603\DouglasUNCTest\*" $dest -Force -Verbose -Recurse
Invoke-expression ".\UnzipTarFile.ps1"
}

WMI - Querying StatusInfo (enabled/disabled) property on all devices shown in device manager.

$
0
0

hi, ive tried a number of ways to get the current state of a device (pretty much the same as is displayed in Device Manager)

When i run: 

gwmi cim_logicaldevice|select name,statusinfo

gwmi win32_networkadapter|select name,statusinfo,netenabled

it returns me some statuses but most of them are null. Even when i try disable a device in device manager and re-run it, the corresponding name returned within the query still shows as null StatusInfo. 

As an example also, when using win32_networkaddapter and i query the "netenabled" property if the device (in my case a wireless addapter) isnt connected to a network it shows false even through the device is enabled in device manager.

I've tried querying the separate classes eg. win32_networkadapter, win32_usbcontroller etc.. but i cant seem to get a consistant response.

any help appreciated.


why would this script give off an error?

$
0
0

i have this simple script to update user's phone extension using their samAccountName as the search key. it does the job but it also gives off  the error below for no apparent reason (to me):

Import-CSV 'd:\newphone.csv' | foreach-object {
    Set-ADuser -Identity $_.ID -Replace @{ipPhone=$_.extension; msExchExtensionAttribute16=$_.extension}
}

here is the error:

Get-ADUser : Cannot validate argument on parameter 'Identity'. The Identity property on the argument is null or empty.
At C:\Users\x\OneDrive\scripts\addPhone.ps1:2 char:18
+   if (Get-ADuser $_.ID) {
+                  ~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-ADUser], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.GetADUser

am i missing something?

Regards,

Rino


Powershell Handle errors to file in Workflow

$
0
0
Hello Every one!

I have Powershell Script with workflow and foreach -parallel

I set TimeoutSec inside workflow to InlineScript

When I set sleep command to 15 sec, I got error below:

Microsoft.PowerShell.Utility\Write-Error : The activity has exceeded the specified maximum running time of 10 seconds.
At create-new-vms:25 char:25
+
    + CategoryInfo          : NotSpecified: (:) [Write-Error], TimeoutException
    + FullyQualifiedErrorId : System.TimeoutException,Microsoft.PowerShell.Commands.WriteErrorCommand
    + PSComputerName        : [localhost]
 
Microsoft.PowerShell.Utility\Write-Error : The activity has exceeded the specified maximum running time of 10 seconds.
At create-new-vms:25 char:25
+
    + CategoryInfo          : NotSpecified: (:) [Write-Error], TimeoutException
    + FullyQualifiedErrorId : System.TimeoutException,Microsoft.PowerShell.Commands.WriteErrorCommand
    + PSComputerName        : [localhost]
    
    
I want write this error to Log files (one file to one error? for every foreach element )

How to do this?

What I must add to my script?



My script:

$newvmlist="test1","test2"

workflow create-new-vms {

param(
[string[]]$vms
)

foreach -parallel ($vm in $vms)
{

$run = InlineScript{


# Create New VM
echo " "
echo " "
echo "___"
echo "VM Name - $Using:vm "
echo "----"
echo " "
echo " "
sleep 15


} -PSActionRunningTimeoutSec 10


$run


}

}

create-new-vms -vms $newvmlist 



Thanks in advance!

Parsing CSV Data to another CSV based on Samaccountmatch

$
0
0

I have 2 csv's, 1 from exchange and 1 from AD. I am querying for samaccountname, emailaddress, enabled in AD. I am querying for samaccountname, primarysmtpaddress where recipienttype is 'usermailbox'.

After these are compared it spits out a 3rd csv based on the mismatches it finds.

I need to figure out how to take data from 1 csv ("Path\get_exusers.csv") "primarysmtpaddress" column. Then add it correlating to the mismatch file that is generated from a compare-object of ("Path\get_exusers.csv") and ("Path\get_adusers.csv"). The end result is the mismatch csv (Path\get_diff.csv). I need to take the "primarysmtpaddress" column from the ("Path\get_exusers.csv") and only add the addresses correlating to the "samaccountname" column in the mismatch csv.

Also, any other suggestions are welcome.

AD Script:

$ErrorActionPreference = 'Continue'
$SamAccountPath = "Path\get_adusers.csv"
$SamAccountPathE = "Path\get_adusers_edit.csv"
$Folder = "Path\mismatch_script"
$logfile = "Path\mismatch_script\get-user.txt"

Try{
if (Test-Path $Folder)
{}
else
{
    New-Item -Path "$Folder" -ItemType Directory -Force | Out-Null
}
} Catch {
Write-Output "Could not create log folder" | Out-File $logfile -Append

}
Try
{
   Import-Module ActiveDirectory

} Catch {
  Write-Output "Could not import ActiveDirectory module." | Out-File  $logfile -Append

}

Try{
Get-Aduser -filter * -properties Samaccountname, emailaddress, enabled | ? { $_.enabled -eq $true } | select samaccountname, emailaddress |`
?{$_.emailaddress -ne $null} | Sort-Object samaccountname |`
Export-Csv -Path $SamAccountPath -NoTypeInformation -Force | Out-Null
Get-Content $SamAccountPath | select -Skip 1 | ConvertFrom-Csv -Header 'Samaccountname','primarysmtpaddress' | Export-Csv -Path $SamAccountPathE -NoTypeInformation -Force |Out-Null
Remove-Item $SamAccountPath -Force

} Catch {

Write-Output "Could not get ad users" | Out-File  $logfile -Append
}

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -version 2.0 -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto; Path\get-exuser_information.ps1"

Exchange Script:

$AliasPath =  "Path\get_exusers.csv"
$SamAccountPath = "Path\get_adusers_edit.csv"
$MismatchPath = "Path\get_diff.csv"
$logfile = "Path\get-user.txt"

$mboxes = get-mailbox -Resultsize Unlimited -identity
$samobj.Samaccountname | Where-Object {$_.recipienttype -eq "UserMailbox"} | select samaccountname, primarysmtpaddress
$ExUserL = Import-Csv $AliasPath
$AdUserL = Import-Csv $SamAccountPath | Where-Object {$_.samaccountname}
$samobj = New-Object PSObject -Property @{ 'Samaccountname' = $_.samaccountname }
$Compare = Compare-Object -ReferenceObject $ExUserL -DifferenceObject $AdUserL -Property samaccountname, primarysmtpaddress



Try {
ForEach-Object{

Import-Csv $SamAccountPath | select samaccountname | Out-Null
}
$mboxes | Sort-Object samaccountname | Export-Csv $AliasPath -NoTypeInformation -Force | Out-Null

} Catch {
Write-Output "Could not get mailboxes" | Out-File  $logfile -Append
}

Try {

$compare | foreach {
if ($_.sideindicator -eq '<=')
{$_.sideindicator = ''
$_.samaccountname = ''
$_.primarysmtpaddress = ''
}

if ($_.sideindicator -eq '=>')
{$_.sideindicator = "Mismatch"}

}

$compare | Export-Csv $MismatchPath -NoTypeInformation -Force | Out-Null

} Catch {
Write-Output "Could not compare ex and ad csvs" | Out-File $logfile -Append
}

Send-MailMessage -SmtpServer "server" -Attachments $MismatchPath -From "email" -to "email" -Subject "Mismatch Report"


Set Advanced Permission on Folder

$
0
0

Hello My Name is Werner

i am a newbie with powershell. I need to set the special Permission (advanced Permission) on folders in my Project folder strukture.

folder-structure

i am google a bit but i found only some entries of the standard permission for a Folder.

My Target ist to set the advanced Permission for the spezial Group like the picture displays.

End-Permission

Thank you all

Werner

Sending an email using PowerShell from a scheduled task

$
0
0

Hi,

I have a scheduled task setup in the windows task schedlar that runs a powershell script. This script should send out an email on completion. I'm using the Send-MailMessage CmdLet

Send-MailMessage -SmtpServer "xxx" -From "MyServiceAccount@example.com" -To "me@example.com"  -Subject "Hello!" -Body "That's it"

This results in an error:
Send-MailMessage : Mailbox unavailable. The server response was: 5.7.1 Client does not have permissions to send as this sender

The task is set up to run as the service account behind MyServiceAccount@example.com. And is marked as "Run with highest privileges". The strange part is that it works if I use an Invoke-Command to localhost, like:

Invoke-Command -ComputerName localhost -ErrorAction Continue -ScriptBlock { 
   Send-MailMessage -SmtpServer "xxx" -From "MyServiceAccount@example.com" -To "me@example.com"  -Subject "Hello!" -Body "That's it"
}

Please note that there is no Credential on the Invoke-Command. As I understand it it the two Send-MailMessage should be running under the same account. If I check $env:USERNAME just before, it is also the same for both. I have a simple script with both variants:

Invoke-Command -ComputerName localhost -ErrorAction Continue -ScriptBlock { 
    Send-MailMessage -SmtpServer "xxx" -From "MyServiceAccount@example.com" -To "me@example.com"  -Subject "Hello 1!" -Body "That's it"
}
Send-MailMessage -SmtpServer "xxx" -From "MyServiceAccount@example.com" -To "me@example.com"  -Subject "Hello 2!" -Body "That's it"

I receive the email "Hello 1!" but the other command gives the error above. I can of cause go ahead an use the version with Invoke-Command. But as I don't understand it, it feels a bit obscure, and I don't like working with obscure... If anyone out there can explain this to me that would be much appreciated!

Thanks


Viewing all 15028 articles
Browse latest View live


Latest Images

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