Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x

Powershell

16K

Solutions

7K

Contributors

Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to the Component Object Model (COM) and Windows Management Instrumentation (WMI), enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and Common Information Model (CIM) enabling management of remote Linux systems and network devices.

Share tech news, updates, or what's on your mind.

Sign up to Post

Hello,

Does anyone know if it's possible to disable Integrated Apps for an Office365 Tenant via powershell?  If so, can you give me the command as I can't find a reference for it.

See that attachment for reference.  (Settings> Serives & Addins> Integrated Apps)

Thank you
Integrated-Apps.PNG
0
NEW Veeam Backup for Microsoft Office 365 1.5
LVL 1
NEW Veeam Backup for Microsoft Office 365 1.5

With Office 365, it’s your data and your responsibility to protect it. NEW Veeam Backup for Microsoft Office 365 eliminates the risk of losing access to your Office 365 data.

Hello,

I am trying to write script but I have no enough powershell experience to do that. I would like to have a loop until a condition is true.

For my project I need to check if a CD or dvd inserted is blank or not. I found I can check with "Get-Volume | select -property operationalStatus | Where-Object {$_.operationalStatus -eq "Unknown"} " When media is blank operationalstatus is alway Unknown.

I have started to write like that (see below) but it does not work. I am not surprised I do not know how to do that :-)


I would like to continue to show a warning until blank CD is inserted and then continue to action. I do not know how to build a loop until the condition is true.

Thank you in advance for your help and sorry for my bad english. I am a french who did not work during english lessons at school :-)

$OS = Get-Volume | select -property operationalStatus | Where-Object {$_.operationalStatus -eq "Unknown"} 

Do{

If ($OS.operationalStatus -eq  "Unknown")

{ 
 
Start-Process -Wait "C:\Program Files (x86)\softwarexxx"

 
}
Else {

[System.Windows.Forms.MessageBox]::Show("CD/DVD inserted is not blank")
Start-Process -Wait "C:\Program Files (x86)\CDBurnerXP\cdbxpcmd.exe" -ArgumentList "--eject [ -device:1 ]"
[System.Windows.Forms.MessageBox]::Show("Please insert a blank CD/DVD and click OK")
Start-Process -Wait "C:\Program Files (x86)\CDBurnerXP\cdbxpcmd.exe" -ArgumentList "--wait-for-disc [ -device:$Devicenumber ]"
}

}
Until ($OS -eq  "Unknown")

Open in new window

0
Looking for a script to generate a list of Computers and IP in the entire domain, preferably in a delimited format.
Thanks in advance.
0
Hi,

Please I need a script (vbscript or Powershell)  to export the following attribute from two "OU" in active directory,
After to run the script we obtein a output file .csv (encode in UTF-8 )

I want to display in the output file the following fields:
"Account","Disabled","First Name","Last Name","Mail"

*Disable = True or False
"""ou=Accounts,ou=Sales,ou=USA,dc=Dom,dc=local"",""DC1Serv.dom.local"""
"""ou=Accounts,ou=Marketing,ou=USA,dc=Dom,dc=local"",""DC1Serv.dom.local"""

Best regards,
0
Here's what I'm trying to do...

Get computer names from an OU using Get-ADComputer
Get logged on user with computer name obtained from Get-ADComputer, use error handling to determine which computers weren't reachable.
If possible, Nest the fields below
Get-Adcomputer - "Full Name, Department"
Get-WMIobject - "Computer, Model"

I've tried with the script below but can't figure out how to nest or get the try-catch error handling to work.

Clear-Host

$Computers = Get-ADComputer -Filter * -SearchBase "DC=domain,DC=com" | select -ExpandProperty Name
 
Foreach ($Computer in $Computers){

    try{
        Get-WmiObject -Class win32_computersystem -ComputerName $Computer  -ErrorAction stop  | Select Username, Caption, Model
    }
    Catch{
        $Exception = $_
        If ($Exception.Exception.Message -like "The RPC server is unavailable*")
            {
                Write-Host -BackgroundColor Red "$_ was not reachable"
            }
    }


}
0
Hi all

I've made a script in Powershell 2.0 for creating users in Microsoft SQL Server 2008.
Now, everything is fine. But I want to script 'user mapping' for new created logins.
So you know, if you choose properties of sql user and choose 'User Mapping' and select a database to map for the selected user.

I searched on Google, but doesn't find anything.. Can someone help me for powershell 2.0?

Kind Regards
0
Hey Experts!  Here's a script that will email a log file.  I'd like to include the log file into the body of the email as well as keep the log file as an attachment.

$ServerList = @'
	"Name",			"Path"
	servers
'@ | ConvertFrom-Csv
$LogFile = "\\w2k12FS01\PUBLIC\Tivoli_Master_Logs\Combined_{0}.log"

$Yesterday = (Get-Date).AddDays(-1)
$Pattern = (Get-Date).AddDays(-1).ToString('MM\/dd\/yyyy') + ' * --- SCHEDULEREC STATUS BEGIN*'
$Timestamp = $Yesterday.ToString('yyyyMMdd')
$in = $false
$ServerList | ForEach-Object {
	$Server = $_
	"========== $($Server.Name) ============================================================"
	Try {
		Switch -Wildcard (Get-Content -Path "\\$($Server.Name)\$($Server.Path.Replace(':', '$'))" -ErrorAction Stop) {
			$Pattern					{$in = $true}
			'*SCHEDULEREC STATUS END*'	{$in = $false}
			default						{If ($in) {$_}}
		}
	} Catch {
		"ERROR accessing '$($Server.Path)': $($_.Exception.Message)"
	}

} | Set-Content -Path $($LogFile -f $TimeStamp)

$EmailFrom = "me"
$EmailTo = "me"
$EmailSubject = "Backup results for $($yesterday)"  
$SMTPServer = "smtp"
$EmailAttachment = $LogFile -f $TimeStamp

Send-MailMessage -From $EmailFrom -To $EmailTo -Subject $EmailSubject -SmtpServer $SMTPServer -Attachments $EmailAttachment -Body $EmailSubject

Open in new window


I have this code from another script I have that works and am trying to use it but can't get it to work with this script.  Any help would be appreciated!

$mailmessage = New-Object system.net.mail.mailmessage 
$mailmessage.from = ($emailfrom) 
$mailmessage.To.add($emailto)
$mailmessage.Subject = $emailsubject
$attachment = New-Object System.Net.Mail.Attachment($emailattachment, 'text/plain')
  $mailmessage.Attachments.Add($attachment)
$mailmessage.Body = ("<br />$('*'*72)<br />" + ((Get-Content -Path $LogFile) -join '<br />') + "<br />$('*'*72)<br />")

$mailmessage.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)  
#$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("$SMTPAuthUsername", "$SMTPAuthPassword") 
$SMTPClient.Send($mailmessage)

Open in new window

0
Hey Experts.  I'd like to add the ability to email the log file once the script has finished running.  Below is the script I'd like to add the email functionality to:

$ServerList = @'
	"Name",			"Path"
	Servers
'@ | ConvertFrom-Csv
$LogFile = "\\w2k12FS01\PUBLIC\Tivoli_Master_Logs\Combined_{0}.log"

$Yesterday = (Get-Date).AddDays(-1)
$Pattern = (Get-Date).AddDays(-1).ToString('MM\/dd\/yyyy') + ' * --- SCHEDULEREC STATUS BEGIN*'
$Timestamp = $Yesterday.ToString('yyyyMMdd')
$in = $false
$ServerList | ForEach-Object {
	$Server = $_
	"========== $($Server.Name) ============================================================"
	Try {
		Switch -Wildcard (Get-Content -Path "\\$($Server.Name)\$($Server.Path.Replace(':', '$'))" -ErrorAction Stop) {
			$Pattern					{$in = $true}
			'*SCHEDULEREC STATUS END*'	{$in = $false}
			default						{If ($in) {$_}}
		}
	} Catch {
		"ERROR accessing '$($Server.Path)': $($_.Exception.Message)"
	}
} | Set-Content -Path $($LogFile -f $TimeStamp)

Open in new window


I tried adding this at the end of the script but it didn't work because of an error (Tivoli_Master_Logs\Combined_{0}.log value cannot be null).

$EmailFrom = "me"
$EmailTo = "me"
$EmailSubject = "Backup results for $($yesterday)"  
$SMTPServer = "smtp"

$emailattachment = $LogFile

$mailmessage = New-Object system.net.mail.mailmessage 
$mailmessage.from = ($emailfrom) 
$mailmessage.To.add($emailto)
$mailmessage.Subject = $emailsubject
$attachment = New-Object System.Net.Mail.Attachment($emailattachment, 'text/plain')
  $mailmessage.Attachments.Add($attachment)
$mailmessage.Body = ("<br />$('*'*72)<br />" + ((Get-Content -Path $LogFile) -join '<br />') + "<br />$('*'*72)<br />")

$mailmessage.IsBodyHTML = $true
$SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 25)  
#$SMTPClient.Credentials = New-Object System.Net.NetworkCredential("$SMTPAuthUsername", "$SMTPAuthPassword") 
$SMTPClient.Send($mailmessage)

Open in new window


Thanks experts for your help!
0
Experts, here is a script that outputs the info to a log file but I need the filename to include yesterday's date.  I've tried a few things in the attempt to learn on my own but haven't had much luck.  Looking for some help.

$ServerList = @'
	"Name",			"Path"
	servers
'@ | ConvertFrom-Csv

$Pattern = (Get-Date).AddDays(-1).ToString('MM\/dd\/yyyy') + ' * --- SCHEDULEREC STATUS BEGIN*'
$in = $false
$ServerList | ForEach-Object {
	$Server = $_
	"========== $($Server.Name) ============================================================"
	Try {
		Switch -Wildcard (Get-Content -Path "\\$($Server.Name)\$($Server.Path.Replace(':', '$'))" -ErrorAction Stop) {
			$Pattern					{$in = $true}
			'*SCHEDULEREC STATUS END*'	{$in = $false}
			default						{If ($in) {$_}}
		}
	} Catch {
		"ERROR accessing '$($Server.Path)': $($_.Exception.Message)"
	}
} | Set-Content -Path \\w2k12FS01\PUBLIC\Tivoli_Master_Logs\Combined[yesterdaysdate].log

Open in new window


format MMddYYYY

Thanks Experts!
0
Greetings Experts!  As I continue my path towards a script to monitor my backups, I need this script to pull the log files from servers that have the log files in different directories.  The standard hadn't been set yet.  I figured out how to pull the log files in from the other directories however how can I clean-up the $server name in log file?

$ServerList = 'w2k8sentry01\c$\path\to\file', 'w2k12share01\c$\path\to\file', 'mgt01\e$\path\to\file'

$Pattern = (Get-Date (Get-Date).AddDays(-1) -f 'MM\/dd\/yyyy') + ' * --- SCHEDULEREC STATUS BEGIN*'
$in = $false
$ServerList | ForEach-Object {
	$Server = $_
	"========== $($Server) ============================================================"
	Switch -Wildcard (Get-Content -Path "\\$($Server)") {
		$Pattern					{$in = $true}
		'*SCHEDULEREC STATUS END*'	{$in = $false}
		default						{If ($in) {$_}}
	}
} | Set-Content -Path C:\tools\logs\new_test3.log

Open in new window


[log file]
MGT01\long file name\
w2k8sentry01\long file name\
w2k12share01\long file name\

Thanks for your continued help with this script!
0
Problems using Powershell and Active Directory?
LVL 7
Problems using Powershell and Active Directory?

Managing Active Directory does not always have to be complicated.  If you are spending more time trying instead of doing, then it's time to look at something else. For nearly 20 years, AD admins around the world have used one tool for day-to-day AD management: Hyena. Discover why

I don't have admin rights & can't install dsquery/RSAT.

Is there a Windows command prompt command to list out member computers of an OU ?
Pls give exact syntax
0
Hey Experts.  As a continued evolution of this script, I need this script I to run on the two servers listed.  Since the results will be listed in the log file, I need the server name included in the results.

Script:
$in = $false
$pattern = (get-date (get-date).AddDays(-1) -f 'MM\/dd\/yyyy') + ' * --- SCHEDULEREC STATUS BEGIN*'
$(
  switch -wildcard -file C:\tools\logs\dsmsched.log
  {
    $pattern   { $in = $true }
    '*SCHEDULEREC STATUS END*'  { $in = $false }
    default { $_ | ? { $in } }
  }
)

Open in new window


Servers:
\\serverA
\\serverB
0
I would like to have the folder size of the following path "C:\ArchiveDocs\DocImageExports\Servicing" by excluding "C:\ArchiveDocs\DocImageExports\Servicing\Old"

This code gives me everything including "Old". I need to exclude the "Old" folder.
"{0:N2} GB" -f ((Get-ChildItem "C:\ArchiveDocs\DocImageExports\Servicing\" -Recurse |  Measure-Object -Property Length -Sum -ErrorAction Stop).Sum / 1GB)

Open in new window


Thanks for your help
0
Hey Experts!  Here is a script that I would like to modify to include the ability to write the output to a log file.

$in = $false
$pattern = (get-date (get-date).AddDays(-1) -f 'MM\/dd\/yyyy') + ' * --- SCHEDULEREC STATUS BEGIN*'
$(
  switch -wildcard -file C:\tools\logs\dsmsched.log
  {
    $pattern   { $in = $true }
    '*SCHEDULEREC STATUS END*'  { $in = $false }
    default { $_ | ? { $in } }
  }
)

Open in new window


Thanks Experts!
0
Hello, I have the following code but i am getting access denied.

I need to move everything from "C:\ArchiveDocs\DocImageExports\Servicing" into "C:\ArchiveDocs\DocImageExports\Servicing\Old"

Move-Item -Path "C:\ArchiveDocs\DocImageExports\Servicing" -Destination "C:\ArchiveDocs\DocImageExports\Servicin
g\Old"

Open in new window


Error:
Move-Item : Access to the path 'C:\ArchiveDocs\DocImageExports\Servicing' is denied.

Open in new window


Thanks for your help
0
Hi there,
Was wondering if someone could help me out here...in the past, we automated a ftp process to one of our customers, using a batch file and the ftpcmd.dat command. Now, they have switched to a https site, and as a result, broke our current process.

Doing some searching, I was able to find links using PowerShell as an alternative, particularly, the Invoke-WebRequest cmdlet. Going step-by-step, I was able to connect to the site; here's what I did:

# The first command uses the **Invoke-WebRequest** cmdlet to send a sign-in request. The command specifies a value of "FB" for the value of the *SessionVariable* parameter, and saves the result in the $R variable.When the command completes, the $R variable contains an **HtmlWebResponseObject** and the $FB variable contains a **WebRequestSession** object.

$R=Invoke-WebRequest https://website -SessionVariable fb

# The second command shows the **WebRequestSession** object in the $FB variable.
$FB

# The third command gets the first form in the **Forms** property of the HTTP response object in the $R variable, and saves it in the $Form variable.
$Form = $R.Forms[0]

# The fourth command pipes the properties of the form in the $Form variable into a list by using the Format-List cmdlet.
$Form | Format-List

# The fifth command displays the keys and values in the hash table (dictionary) object in the Fields property of the form.
$Form.fields

# The sixth and seventh commands populate the values of the email and pass 

Open in new window

0
hello experts
i need this powershell module, could you let me know where i can download it(the sshshell module)? i can't find it by myself.

thank you
0
Hi EE

so I need to pull some group member details but I need to use the get-QASUnixUser CMDLET to get some specific Unix account details .

can someone help me ?

so basically , how do I pull members of a group but also using get-QASUnixUser  to get those Unix account details.
0
Hi Expert

How to wirte a powershell scripting to check the users lockout status
0
Who's Defending Your Organization from Threats?
Who's Defending Your Organization from Threats?

Protecting against advanced threats requires an IT dream team – a well-oiled machine of people and solutions working together to defend your organization. Download our resource kit today to learn more about the tools you need to build you IT Dream Team!

Where i work has a large number of DHCP scopes. must be approx 40-50 its been left that way for a good few years apparently

I have just joined in past 6 months and just getting round to look at it now

Any DHCP scope clean up plans? Whats the worst thing that can happen if some are removed that have VLAN connections (one thing we're worried about) so i plan on taking an inventory first

I know i can use powershell to look for free addresses per scope can i use this to see addresses that are taken, then i could compare using HP IMC to see whats actually being used

Any ideas appreciated domain functionality is 2008
1
I have created a 2 node vsan cluster with a witness.  The two physical hosts are interconnected with 10gb links and the vsan vmkernel resides on that particular vswitch.  I leave the mgmt on the default vSwitch0 which uses vmk0.

I'm looking for a way to script in powercli/powershell adding a route to the esxi hosts so that it can communicate with the witness.

$HostNameFQDN = xyz.domain.com

This outputs nothing on my system currently but it seems like i'm really close.
$Host_Gateway = Get-VMHost -Name $HostNameFQDN | Get-VMHostNetworkAdapter | select VMKernelGatway

New-VMHostRoute -VMHost $HostNameFQDN -Destination 172.23.0.0 -Gateway $Host_Gateway -PrefixLength 20

Would somebody be able to assist with getting this to work, correctly?  I've also noticed that the Get-network commands do not work in Powershell ISE but they do in the regular powershell window.

Thanks in advance.
0
I was asked to take a look at the mailbox to inventory the size and dates of the mail to see what archiving policy would reduce the mailbox size by at least 50-70%. If this user has 45GB in the last 6 months, then a 1 year policy won’t be of much value and I think that the user won’t want anything less than a year. I need to find a report mailbox folder sizes with PowerShell within a date range. I think I should use the Get-MailboxFolderStatistics -identity cmdlet but not certain. Can you help?
0
I want to log into a website using a username and password, so I copied the following code and executed. In result the webpage is opening but its not logging into the webpage and getting the following error.

Any suggestions?

$ie = New-Object -com InternetExplorer.Application 
$ie.visible=$true
$ie.navigate("url") 
while($ie.ReadyState -ne 4) {start-sleep -m 500} 
$ie.Document.getElementById("ctl00_username").value = "abcdef" 
$ie.Document.getElementById("ctl00_password").value = "123456" 
$ie.Document.getElementById("ctl00_login").click()
start-sleep 20 
$ie.Document.body | Out-File -FilePath C:\Users\averm\Documents\adi\test\web123.txt 

Open in new window


Exception from HRESULT: 0x80020101
At line:7 char:1
+ $ie.Document.getElementById("ctl00_usernamerequiredvalidator").value  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
 
Exception from HRESULT: 0x80020101
At line:8 char:1
+ $ie.Document.getElementById("ctl00_passwordrequiredvalidator").value  ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
 
Exception from HRESULT: 0x80020101
At line:9 char:1
+ $ie.Document.getElementById("ctl00_login").click()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

Open in new window

0
I have a PowerShell script that I have used many times to add devices from a text file  to a device collection in SCCM.  I have a txt file with 29 computers but only 10 are showing in member count.  If I look at the direct connections and count them then there are 29 devices.  I have deployed to this collection but my reports are only listing the 10 devices.  I have updated the collection many times to no avail.  Is there something I can do to rectify the collection count?

Kind Regards,

Nigel
0
I am using Invoke-WebRequest in Powershell to authenticate against Forms authentication in a C# MVC site.

I have usually done it this way successfully;
$webServerUrl = 'http://localhost:54363'

$r = Invoke-WebRequest $webServerUrl -SessionVariable my_session
$form = $r.Forms[0]
$credentials = Get-Credential
$form.fields['Username'] = $credentials.GetNetworkCredential().UserName
$form.fields['Password'] = $credentials.GetNetworkCredential().Password
$form.fields['RembemberMe'] = $true;

$r = Invoke-WebRequest -Uri $($webServerUrl + $form.Action) -WebSession $my_session -Method GET -Body $form.Fields

Open in new window


As you can see, I retrieve a form, set username and password and log in.
But now in the recent version of the system, the first Invoke-WebRequest fails and the $r variable is never populated.

I get the html of the page outputted to the Powershell terminal window and at the end of that I receive:
+ $r = Invoke-WebRequest $webServerUrl -SessionVariable my_session
+      ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExc
   eption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

Open in new window


I have tried debugging the MVC application while sending a request with Powershell, and I cannot see anything out of the ordinary. The LoginController and its Index method returns 401 Not Authorized with the HTML for a login form. When I use that form in a web browser, I can log in. But my attempt  in Powershell still fails.

The error variable displays this:
$error[0].Exception
The remote server returned an error: (401) Unauthorized.

Open in new window

0

Powershell

16K

Solutions

7K

Contributors

Windows PowerShell is a task automation and configuration management framework from Microsoft, consisting of a command-line shell and associated scripting language built on the .NET Framework. PowerShell provides full access to the Component Object Model (COM) and Windows Management Instrumentation (WMI), enabling administrators to perform administrative tasks on both local and remote Windows systems as well as WS-Management and Common Information Model (CIM) enabling management of remote Linux systems and network devices.