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

You cannot call a mthod on a null-valued expression. Outlook Attachment Script

$
0
0

I have an export of a list of a bunch of file locations, usernames (n the format of domain/username) and other data i. I am pulling out just the file location and username exporting these to csv files for each unique username and I want to send an email message to each user with their csv as an attachment. I define emailattach as the full file path and use that in the message.attachments.add but I get this error message.

You cannot call a method on a null-valued expression.
At C:\Users\smith\Desktop\data\parse-incident.ps1:18 char:1
+ $message.Attachments.Add($emailattach)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

I cannot use send-mailmessage due to our architecture. Any suggestions?

$data = import-csv .\file.csv|select Location, "File Owner"|Sort-Object "File Owner"
$dataowner = import-csv .\file.csv|select "File Owner"|Sort-Object "File Owner" -Unique
foreach($ownername in $dataowner)
{
$owner = $ownername.'File Owner'
$emailowner = $ownername.'File Owner'+"@test.com" -creplace '^[^\\]*\\', ''
$pathname = $ownername.'File Owner'+".csv" -creplace '^[^\\]*\\', ''

$emailattach = ("c:\users\smith\desktop\data\" + $pathname)

$data|Where {$_."File Owner" -eq "$owner"}|export-csv -Path "$pathname" -NoTypeInformation -Append
}
$o = New-Object -com Outlook.Application
$mail = $o.CreateItem(0)
#2 = high importance email header
$mail.importance = 2
$mail.subject = “Enterprise Security - Data Needs Reviewed“
$mail.body = "Test of DLP Incident Data"
$mail.To = “$emailowner"
$message.Attachments.Add("c:\users\smith\documents\" + $pathname)
sleep 3
$mail.Send()

# $o.Quit()


Bulk setting -BookingWindowInDays on O365

$
0
0

I would like to change the -BookingWindowInDays setting from the default (180 to 365 for our meeting rooms in O365.

I thought that this would work:

Get-MailBox | Where {$_.ResourceType -eq "Room"} | Set-CalendarProcessing -BookingWindowInDays 365

but all it does is return:

WARNING: By default, only the first 1000 items are returned. Use the ResultSize parameter to specify the number of
items returned. To return all items, specify "-ResultSize Unlimited". Be aware that, depending on the actual number of
items, returning all items can take a long time and consume a large amount of memory. Also, we don't recommend storing
the results in a variable. Instead, pipe the results to another task or script to perform batch changes.

I am a novice at this and am not sure how to fix command or if it is even possible to do in the fashion I am attempting.

Any help would be appreciated.

Thank you,

Peter

Dynamic Distribution List - exclude disabled accounts

$
0
0

Hi,

 

I've used the script below to create a dynamic distribution list. Although when one of my users sends to this list, it includes disabled accounts. All my disabled accounts are in their own OU "domain.local/users/disabled". I thought UserAccountControl -ne '2' would exlude disabled accounts but it isn't exluding all of them, my user got a failed delivery receipt for about 7 users. I checked all of these and they are disabled and in the disabled OU. An easy work around would be to exclude that OU, is this possible without moving the OU out of the Users OU? Or is there anything else I can check?

 

New-DynamicDistributionGroup -name "New List" -OrganizationalUnit "domain.local/users" -RecipientContainer "domain.local/lists" -RecipientFilter {((RecipientType -eq 'UserMailbox') -and (Office -eq " 4th floor PLL") -and (UserAccountControl -ne '2'))}

Get-Process to find PID, pipe to executable and run command

$
0
0

Good morning everyone :-)  I am new to using powershell and was wondering if someone could help me find a solution to my problem.

At my company we use a program called "Universe" and we use 2008 R2 task scheduler to kick off a .bat file that starts a few phantoms within the program every night. The problem with this is when run as a task scheduler, memory priority is only set to a 4 which is below normal(5).  My idea was to run a powershell script after the phantoms started, to set memory priority to normal with a small executable I have called "processpriority.exe". I am able to do this manually every day with processpriority.exe, however would like to automate the process.

I was able to use "Get-Process uvsh | format-list id"  and it returns the PIDs of all the processes running under "uvsh", but from there I don't know the best way to execute the program "processpriority.exe" under the system32 folder, and then execute the command to set each PID to a normal priority.  The command for that would be "processpriority set "PID" normal".

I apologize in advance if I didn't give complete information, and appreciate any feedback you can give.  Thanks!!

Use powershell to read Environment tab checkbox from ADUC

$
0
0

Hello all,

In ADUC, when you pull up a user, you can see an "Environment" tab, which contains a checkbox for "Start the following program at logon:". Here's a picture:

What I would like to do is use PowerShell to see if this checkbox is checked for a user. In my Google searches however, I have found that this checkbox is contained in the infamous "UserParameters" attribute.

My question is, what is the best way to see if this checkbox is checked for a user using PowerShell? Is this checkbox contained in any other attribute that PowerShell can read, or will I need to parse the UserParameters attribute to see if it's checked?

AD mapping, the deep dive

$
0
0

Good day.

I'd like to do an inventory of the plethora of active directory groups we've created in our company in so many years. I'd like to find redundant groups and delete them, groups that I can harmlessly merge together and so on.
So i am looking for a tool (preferably a PS script) that would do the following.

Run through all the servers belonging to a domain.
For each server run through the shares of that server.
For each share create a list of groups and users that have access rights to that share.

Regards

Kamil

Trim after and INCLUDING decimal

$
0
0

I have a series of numbers generated in the format of 12345.6789 or something similar. The decimal isn't fixed so I can't trim the number of characters, but I need to remove everything after and including the decimal point. I can't round it up either because everything before the decimal is an accurate value.

Any ideas?

Thanks in advance
Adam

Powershell Auto-Elevate (RunAs Administrator) and Pass Parameters

$
0
0

This is not a question but a comment about passing parameters to an auto-elevated script.  There are many examples out there about how to auto-elevate a script so it is running as Administrator but I could not find any examples about passing the parameters from the normal script to the auto-elevated script. 

I finally figured it out through some trial and error so for those that have been searching for a similar solution, here you go...

(If this has been posted elsewhere, please let me know because I have not been able to find it anywhere)

# Check if script is running as Adminstrator and if not use RunAs
Write-Host "Checking if the script is running as Administrator"
$IsAdmin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]"Administrator")
if (-not $IsAdmin){
    Write-Host "The script is NOT running as Administrator, restarting PowerShell as Administrator..."
    $cmd = $MyInvocation.MyCommand.Path + " -Parameter1 $Parameter1 -Parameter2 $Parameter2 -Parameter3 $Parameter3"
    $arguments = "-NoProfile -NoExit -Command ""& {$cmd} """
    Start-Process "$psHome\powershell.exe" -Verb Runas -ArgumentList $arguments -WorkingDirectory $localpath -ErrorAction 'stop'
    Break
}
else{
    Write-Host "The script is already running as Administrator"
}


Regexp replace to get two lines as one

$
0
0

I have a log file that I'm using replace on to basically convert it into a CSV.  I'm sort of hung on one part that has info generated from a different program.

There are two lines like this

SerialNumber

blahblah

Which I need to convert to

Serial,blahblah

I had assumed it would be a matter of

type file.log |  %{$_ -replace "SerialNumber'n'r","Serial,"} > newfile.log

But that doesn't seem to work.  I've tried 'n'r, 'r'n, \n\r, \r\n, \n, \r, 'n, 'r

Basically trying to remove the newline and cr from that line with the assumption it will pull the next line up. I've googled this and all the examples I could find of bringing two lines together don't work.  It just doesn't seem to get a pattern match.  Removing the line and inserting Serial, in front of the serial number won't work because I don't really have a way to pattern match that that I can think of. (If it helps it is a 7 digit alpha numeric Dell Service Tag) I know I could possibly do a pattern match on a 7 digit string of a-z 1-9 but don't want to risk an accidental pattern match elsewhere in the log.

Maybe I'm under the false assumption that powershell knows about carriage return and newline at the end of the text?

Would an alternate method be to replace it with Serial,[some code for a delete key] ?

PowerShell runnig in Admin Mode by default

$
0
0
How should I remove Windows Powershell from running in Admin Mode by default?

Powershell IE get html in frame

$
0
0

Hello.

 

Show HTML-code in IE (right button click)

 

 

<html>

<head>

</head>

<frameset id='frameset_main' rows="0px,81px,*,0px">

  <frame name="audio" src="copyright.html" scrolling="no" frameborder="no" noresize="noresize">

  <frame name="main_menu" src="menu_reccall.jsp" scrolling="no" noresize="noresize" frameborder="no">

  <frameset id='frameset_middle_row' cols="*,0px">

    <frame name="main" src="filteroperation?view_type=couple" frameborder="no" scrolling="yes" noresize="noresize">

                #document

                <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">

                <html>

                               ...

                               <div id="hovory"> ... </div>     

                               ...

                <html>

    <frame name="search" src="filters.jsp" frameborder="no" scrolling="yes" noresize="noresize">

  </frameset>

  <frame name="copyright" src="copyright.html" scrolling="no" noresize="noresize" frameborder="no">

</frameset>

 

</html>

 

 

 

I want get html-code in frame name="main" by powershell:

 

 

$link = "http://localhost"

$ie = New-Object -com InternetExplorer.Application

$ie.visible = $true

$ie.navigate($link)

 

while ($ie.Busy -eq $true)

{ Start-Sleep -Milliseconds 2000; }

 

$html = $ie.Document.getElementByID("main").document.body.innerHTML

 

 

But this code doesn't return right HTML:

 

Powershell:

<FRAME noResize src="copyright.html" frameBorder=no name=audio scrolling=no><FRAME noResize src="menu_reccall.jsp" frameBorder=no name=main_menu scrolling=no><FRAMESET id=frameset_middle_row cols=*,0px><FRAME noResize src="filteroperation?view_type=couple" fr

ameBorder=no name=main scrolling=yes><FRAME noResize src="filters.jsp" frameBorder=no name=search scrolling=yes></FRAMESET><FRAME noResize src="copyright.html" frameBorder=no name=copyright scrolling=no>

 

Thank you.

Looking for a way to install Windows Intune via powershell

$
0
0

I'm very new to Powershell and completely lost on how to do this.

Looking for a way to install Windows Intune via powershell from a self extracting zip file I will send to remote users. This will also need to run Corp admin level privileges to install.

Thank you in advance for your help.

Query Servers for a specific certificate

$
0
0

Hello,

We have a wildcard certificate on our domain.  Our CA is not longer supporting the SHA-1 algorithim and I need to re-key my certs to SHA2.  The problem I have is my previous network admin did not document the servers the wildcard cert was installed on.  I was wondering if there was a powershell script that would check the Personal Store and tell me if*.domain.com is installed.  Otherwise I have about a week to check around 100 servers manually.  

Please help,

Cheston

question on syntax

$
0
0

Can someone kindly tell me how i can fix this syntax issue?

$var = '\\'+$_.name;write-host $var

Works, but is sloppy

Write-host '\\'$_.name
Puts a space that i cant have.


Getting invalid namespace for Root\MicrosoftDNS

$
0
0

Am I supposed to have DNS tools installed or something to be able to utilize Root\MicrosoftDNS name space? Command below fails both on Windows 2008 and Windows 2012

PS C:\WINDOWS\system32>  Get-WmiObject -Class MicrosoftDNS_AType -NameSpace Root\MicrosoftDNS
Get-WmiObject : Invalid namespace "Root\MicrosoftDNS"
At line:1 char:2+  Get-WmiObject -Class MicrosoftDNS_AType -NameSpace Root\MicrosoftDNS+  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (:) [Get-WmiObject], ManagementException+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand



Sendkeys("A"), sends the Key "A" to active command, instead to Scheduled Task screen.

$
0
0
A PowerShell script runs from Scheduled Task every day. The script invoke a command which required to confirm from user to press "A" to accept. My script has SendKeys function, but the Key "A" prints into active Command Line instead in the  Scheduled Task command line. Thus script pausing until the user press a key

$wshell = New-Object -com WScript.Shell
 $wshell.sendkeys("{A}")

Help me to better understand powershell code/snippet.

$
0
0

Hello,

Could someone help me to better understand following highlighted in the provided code snippet,

1) From the code there is a variable with '  $HTMLHeader = @" '  what exactly this means ?

2) Another variable with '  $ServicesReport = @() ' what exactly this means ?

3)And finally what the below statement does ?

$row = New-Object -Type PSObject -Property @{  ....  }

Appreciate if someone could suggest some books with advanced powershell programming.

CODE:

$HTMLHeader = @"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"><html><head><title>My Systems Report</title><style type="text/css"><!--
body {
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
}

    #report { width: 835px; }

    table{
	border-collapse: collapse;
	border: none;
	font: 10pt Verdana, Geneva, Arial, Helvetica, sans-serif;
	color: black;
	margin-bottom: 10px;
}
</style></head><body>"@$ServicesReport = @()
	$Services = Get-WmiObject -Class Win32_Service -ComputerName $computer | Where {($_.StartMode -eq "Auto") -and ($_.State -eq "Stopped")}

	foreach ($Service in $Services) {
		$row = New-Object -Type PSObject -Property @{
	   		Name = $Service.Name
			Status = $Service.State
			StartMode = $Service.StartMode
		}

	$ServicesReport += $row

	}

Thanks


Copy-Item using Windows PowerShell Multithreading?

$
0
0

Hello all,

I need to figure out a way to copy a 500MB .zip file to about 400 servers in parallel.
Until now, I have been using the ForEach () method. But, I'd like to use a parallel method so that I can copy 500MB to multiple servers at once, to lower the total copy time.
I have been reading that I can do this using PowerShell Jobs. What is the best way to do this?

Here is my code using ForEach:

$servers = Get-Content C:\servers.txt

ForEach ($server in $servers)
{
Copy-Item -Path C:\500MB.zip -Destination "\\$server\c$\" -Verbose
}
Any help very much appreciated.

how to create multiple copies of a file with renamed filenames

$
0
0

hi,

 I want to create multiple copes of a  file [ say abc.docx] which has 3.5 MB of size  and want to rename it through power shell.

so, in the end, i want to get abc_1.docx,abc_2.docx, abc_3.docx ....abc_10.docx in the same folder with the same size. i mean, after running the ps script i should get the foldwer size set to 35 MB .

can anyone help, how to achieve this?

I am newbie in powershell. 

i tried the below :

$File = Get-ChildItem -Path "D:\ABCFolder\" -Filter Copying.bat -Recurse

for($i = 0; $i -lt $File.Count; $i++)
{
   Copy-Item $File[$i].FullName ("D:\ABCFolder\" + $File[$i].BaseName + $i +".doc")
}

help is appreciated!





Duplicate Records in Output

$
0
0

I have a script which works fine however what I cant seem to work out is why I get duplicate records in the output. If anyone knows why it would be a great help/

My code is below:

Connect-QADService "domain.com"

Function CheckUserExistance {
if(Get-QADUser -Identity $Global:Sam) {
Write-Host "User Found: $Global:Sam"
$Example = $Global:Sam + "2"
$prompt = "This User Already Exists, Please Choose Another Name. (e.g. $Example)"
$Title = "Error"
Add-Type  -AssemblyName microsoft.visualbasic
$popup = [Microsoft.VisualBasic.interaction]::MsgBox($prompt,"OkOnly,Critical", $title)
if ($popup -eq "Ok"){

$prompt = "Please Enter The Name To Create (All Lowercase e.g john.smith):"
$Title = "User To Create"

Add-Type  -AssemblyName microsoft.visualbasic
$Global:Sam = [Microsoft.VisualBasic.interaction]::inputbox($prompt,$title)
if ($Global:Sam -eq ""){exit}
}
}
}
# The following Function is used to randomly generate complex passwords.

function New-Password
{
    param
    (
        [int]$length,
        [switch]$lowerCase,
        [switch]$upperCase,
        [switch]$numbers,
        [switch]$specialChars
    )

    BEGIN
    {
        # Usage Instructions
        function Usage()
        {
            Write-Host ''
            Write-Host 'FUNCTION NAME: New-Password' -ForegroundColor White
            Write-Host ''
            Write-Host 'USAGE'
            Write-Host '    New-Password -length 10 -upperCase -lowerCase -numbers'
            Write-Host '    New-Password -length 10 -specialChars'
            Write-Host '    New-Password -le 10 -lo -u -n -s'
            Write-Host '    New-Password'
            Write-Host ''
            Write-Host 'DESCRIPTION:'
            Write-Host ' Generates a random password of a given length (-length parameter)'
            Write-Host ' comprised of at least one character from each subset provided'
            Write-Host ' as a switch parameter.'
            Write-Host ''
            Write-Host 'AVAILABLE SWITCHES:'
            Write-Host ' -lowerCase    : include all lower case letters'
            Write-Host ' -upperCase    : include all upper case letters'
            Write-Host ' -numbers      : include 0-9'
            Write-Host ' -specialChars : include the following- !@#$%^&*()_+-={}[]<>'
            Write-Host ''
            Write-Host 'REQUIREMENTS:'
            Write-Host ' You must provide the -length (four or greater) and at least one character switch'
            Write-Host ''
        }

        function generate_password
        {
            if ($lowerCase)
            {
                $charsToUse += $lCase
                $regexExp += "(?=.*[$lCase])"
            }
            if ($upperCase)
            {
                $charsToUse += $uCase
                $regexExp += "(?=.*[$uCase])"
            }
            if ($numbers)
            {
                $charsToUse += $nums
                $regexExp += "(?=.*[$nums])"
            }
            if ($specialChars)
            {
                $charsToUse += $specChars
                $regexExp += "(?=.*[\W])"
            }

            $test = [regex]$regexExp
            $rnd = New-Object System.Random

            do
            {
                $pw = $null
                for ($i = 0 ; $i -lt $length ; $i++)
                {
                    $pw += $charsToUse[($rnd.Next(0,$charsToUse.Length))]
                    Start-Sleep -milliseconds 20
                }
            }
            until ($pw -match $test)

            return $pw
        }

        # Displays help
        if (($Args[0] -eq "-?") -or ($Args[0] -eq "-help"))
        {
            Usage
            break
        }
        else
        {
            $lCase = 'abcdefghijklmnopqrstuvwxyz'
            $uCase = $lCase.ToUpper()
            $nums = '1234567890'
            $specChars = '!@#$%^&*()_+-={}[]<>'
        }
    }

    PROCESS
    {
        if (($length -ge 4) -and ($lowerCase -or $upperCase -or $numbers -or $specialChars))
        {
            $newPassword = generate_password
        }
        else
        {
            Usage
            break
        }

        $newPassword
    }

    END
    {
    }
}

Import-Csv "C:\ExternalADAccounts.csv" |
ForEach-Object {

$First = $_.Forename
$Last = $_.Surname
$Password = New-Password -length 8 -upperCase -lowerCase -numbers -specialChars
$stuff = $_.stuff
$OU = "domain.com/ou"
$UPN = "$First.$Last@$stuff.domain.com"
$Global:Sam = "$First.$Last"
$Display = "$First $Last"

$Global:Sam = $Global:Sam -Replace " ", ""
$Global:Sam = $Global:Sam -Replace "'",""
$Count = $Global:Sam.Length

If($Count -gt "19"){

$Global:Sam = $First[0] + "." + $Last

}

Do{CheckUserExistance}
While(Get-QADUser -Identity $Global:Sam)

Write-Host "Creating User: $Global:Sam"

New-QADUser -FirstName $First `
			-LastName $Last `
			-DisplayName $Display `
			-Name $Global:Sam `
			-SamAccountName $Global:Sam.ToLower() `
			-UserPassword $Password `
			-UserPrincipalName $UPN.ToLower() `
			-ParentContainer $OU

do{
$Test = Get-QADUser -Identity $Global:Sam
} until(Get-QADUser -Identity $Global:Sam)

Set-QADUser $Global:Sam -Title 'Non-Managed'

} | Select-Object @{label="DisplayName";expression={$Display}},@{label="SamAccountName";expression={$Global:Sam}}, @{label="Password";expression={$Password}}, @{label="Stuff";expression={$Stuff}} |
Sort-Object $Stuff |
Export-Csv "C:\NonManagedCreated.csv" -NoTypeInformation

Any help is greatly appreciated.

James

Viewing all 21975 articles
Browse latest View live


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