Quantcast
Channel: PowerShell
Viewing all 15370 articles
Browse latest View live

How do I write -Verbose output to a logfile

$
0
0

Hello,

I'm writing a script to delete old backup files, but I want to be able to see what files were deleted.

I have tried using Start-Transcript /Stop-Transcript and it works but its not very presentable when viewing it.

I have also tried using | Add-Content $logfile but all that seems to do is added the files names to the logfile that are older than 30days

I just need this -Verbose output to be added to a Logfile 

"Remove-Item -Path C:\Users\User.name\Desktop\Testbackup\$($_.Name) -Force -Verbose "
If seeing more of the script would be helpful let me know I just did not want to add clutter.

Robocopy to array and dealing with spaces

$
0
0

Hello all, first time poster. I have a need to scan large data sets for 0 bytes files. I found a really interesting method for doing this via robocopy on this site

https://community.spiceworks.com/topic/1924583-quickly-scan-file-system-for-0-byte-files

It works after changing a few variables. I only added an additional column for folder as I need to report on the entire folder path. " Folder = $Matches.Folder"

$ZeroList = Invoke-Expression -Command "Robocopy $SharePath NULL /XD Snapshot /L /S /NJH /NJS /BYTES /FP /NC /NDL /XJ /TS /R:0 /W:0" | ForEach {
If ($_ -match "(?\d+)\s(?\S+\s\S+)\s+(?\S+)\\(?.*$)")
{
If ([int64]$Matches.Size -eq 0)
{
[PSCustomObject]@{
Folder = $Matches.Folder
Name = $Matches.Name
# Size = [int32]$Matches.Size
#LastWriteTime = [datetime]$Matches.Date
}
}
}
}

It...

EventLogs - trying to move them to central server

$
0
0

Hello, I have event logs setup to archive after a certain size and i'm trying to setup a sciprt that will run on the server that it going to house these.

The script is going to connect to the admin share (C$) on these servers and move the archive-*evtx files but i keep getting "UnauthorizedAccessException"

Is there a way to get around this w/out putting creds in plain text in a powershell file?

Powershell lastlogontimestamp

$
0
0

Hey all,

Just wondering if you could assist with my script. im not great with powershell, i kind of just throw it all together. The below works, i just need lastlogontimestamp to be displayed in the correct format.

Also i noticed lastlogontimestamp gets triggered when logging on to OWA only. I havent tested AD but im assuming this would also update the value. Is this a better value to use than lastlogontime?

Get-Mailbox -RecipientTypeDetails UserMailbox -resultsize unlimited | select-object displayname,primarysmtpaddress,@{n="ADusername";e={(Get-ADUser $_.SamAccountName -Properties samaccountname).samaccountname}},@{Name='LastLogonTime';Expression={((Get-MailboxStatistics $_.alias).lastlogontime)}},@{n="ADDescription";e={(Get-ADUser $_.SamAccountName -Properties description).description}},@{n="LastLogonTimestampAD";e={(Get-ADUser...

Parse a Text File and output to csv

$
0
0

Let me start by saying I am absolutely new to Powershell. I was tasked with taking output from a command and extract part of the output into a csv file. I did search the site and found some examples, but I am obviously doing something wrong or missing something. Any assistants in understanding this is greatly appreciated.

I run this command:

job run jobs:status::get -s "status=Ended*" c:\REPORT_OUTPUT\ENDED_OK.txt

The contents of the file looks like this:

{
"statuses": [
{
"jobId": "COMPANY:00020",
"folderId": "COMPANY:",
"numberOfRuns": 1,
"name": "dbopt",
"folder": "RUN_Daily",
"type": "Command",
"status": "Ended OK",
"held": false,
"deleted": false,
"startTime": "20181221070012",
"endTime": "20181221070015",
"orderDate": "181221",
"ctm": "COMPANY",
"description": "Calculates database statistics",
"host":...

Script for completing logins

$
0
0

I need to setup laptops for users after imaging the laptop for them. Basically logging into apps like Outlook,Skype for biz, and a few other apps. I was wondering how I would go about creating a script that asks for credentials and then uses those credentials to sign into apps for a no touch setup.

Monitoring powershell activity

$
0
0

Hi Team,

Kindly suggest what are the ways & tools to monitor the user activity done in powershell (Monitor powershell user activity) in Windows 7,8,8.1 & 10. Need to know where the powershell logs are stored in local machine and how we can get those logs in SIEM for monitoring purpose. 

Kindly reply me for my queries.

Send Email Notification on Error with WinSCP .NET Script

$
0
0

I have a script that will login to a remote SFTP and download all files from today to a folder. I need to send an email notification with the result to my team. This script will be set up as an unattended task and therefore I need to know what the result is. I am new to scripting and cannot figure this one out for the life of me. I appreciate the help!

Powershell
# Load WinSCP .NET assemblyAdd-Type-Path"C:\Program Files (x86)\WinSCP\WinSCPnet.dll"# Set up session options$sessionOptions=New-ObjectWinSCP.SessionOptions-Property@{Protocol=[WinSCP.Protocol]::SftpHostName="test.com"UserName="test"Password="test SshHostKeyFingerprint = "ssh-rsa1024test" Timeout = New-TimeSpan -Minutes 10}$session = New-Object WinSCP.Sessiontry{ # Connect $session.Open($sessionOptions) $sessionOptions.AddRawSettings("SendBuf",...

Powershell will not load modules

$
0
0

After a while of not using it I've returned to find an error I have never seen before. Windows 10, I have removed powershell and reinstalled it.

Whenever I attempt Import-Module I get the following error: Cannot get install directory from registry. This happens if I try to import one at a time of in bulk

Any thoughts?

Custom column not working with certain cmdlets

$
0
0

Hi,

I'm trying to add a custom column but it returns an empty value. i tested the same custom column on two cmdlets on one it worked and on one it didn't

Here is the cmdlet that it didn't work

Powershell
get-mailboxjohnDoe|selectname,@{name="size";expression={Get-MailboxStatistics$_.samaccountname|select-ExpandPropertyTotalItemSize}}

Even if i change the variable in the expression to a static one, it still doesn't work.

If i just change the first command to lets say get-command and give a static name in the expression it works beautifully.

Whats the catch here? why doesn't it work?

Thanks in advance.

Add hour to a date in a date variable

$
0
0

Hello,

actually, i use powershell in my company to create the transfer to another user when he is out of office. Another script is automatically created and a task is created to remove the automatic transfer to the specified date. 

To create the scheduled task, i use a date picker script i found on Microsoft Forum. The problem is when i put the date i cannot specify the time. I want to start the job end of the day (5pm). Is it a way to just add 5 pm to a specific date variable? Or do you have another idea? Thank you !

Install .msi silently based on operating system architecture

$
0
0

Hi All,

Any idea how i can fix below? its not installing the .msi :(

The msiexec.exe runs and i get a help pop up menu telling me which parameters i can use but install does not actually happen. I am stumped, please help!

Powershell
If((Get-CimInStanceWin32_OperatingSystem).OSArchitecture-eq"64-Bit"){$Root=Split-Path$MyInvocation.MyCommand.Path-ParentStart-Process-FilePath"msiexec.exe"-ArgumentList"/i $Root\nsepa64.msi /qn+"-Wait-Passthru}Else{$Root=Split-Path$MyInvocation.MyCommand.Path-ParentStart-Process-FilePath"msiexec.exe"-ArgumentList"/i $Root\nsepa32.msi /qn+"-Wait-Passthru}pause

PowerShell Find Filenames Based on Content

$
0
0

I can't seem to get Powershell to find any file that contains specific word. I've tried a few examples and getting mixed results. I need to search all files not just .TXT. I've created an .XLSX and .DOCX with the pattern, and when I perform the command to search this directory it returns no values.

Basically I am either getting no results, InputStream, or just Folder name that contains the -pattern when I remove the Group path | Select Name option.

Powershell
Get-ChildItem-path\\server\share\folder\folder-file-recurse-ErrorActionSilentlyContinue|Select-String-list-pattern"SpecialText"|grouppath|selectname

Other References:

https://blogs.technet.microsoft.com/heyscriptingguy/2016/06/27/use-windows-powershell-to-search-for-...

...

Script to stop services on a remote server when a reboot occurs.

$
0
0

I am looking for a script that I can use a shutdown script to stop services on a remote server.

I want to use this on a SQL server , the script needs to stop a few services on an remote application server and needs to confirm that the services are stopped before the reboot of the SQL server occurs.

Does anyone knows how to accomplish this?

Delete mail items older than "date" O365 EOL

$
0
0

Good morning,

I'm trying to respond to an user request of delete all his mail items older than 01/01/2016.
I've currently set a retention policy which delete items after 735 days but won't work, also forcing the execution with the Start-ManagedFolderAssistant cmdlet.

There's some powershell commands in order to to this?

Thanks


Adding muliple users (UserPrincipalName/email) to multiple groups

$
0
0

Hi.

I need to add Multiple users (100+) to multiple groups (100+) with powershell - and I cannot solve it with your script here due to my lack of skills.https://community.spiceworks.com/topic/459481-adding-users-to-multiple-security-groups-in-ad?started...as each group should contain different users.

Users in my csv are equal to email address and equal to UserPrincipalName and seperated by comma.

My csv-file looks like this:

Groups;Users

Group1;user1@domain.com,user2@domain.com,user3@domain.com

Group2;user1@domain.com,user5@domain.com

group3;user4@domain.com,user5@domain.com

I have tried with this script from another fora with Martin from Spiceworks commenting with an answer, but I cannot get it right how to add several users - split the comma between users - to add them into the group :

Hoping that you could help me.

Text
Import-Module...

Importing PSSession - Connecting to Exchange 365

$
0
0

So updating a tool to my utilities module that cleans up the process of connecting to exchange, now that we're on Office365 I'm trying to update it for connecting to Exchange365. I have the core functionality working but am left with a slightly irritating piece that I can't seem to get working.

When I import the PSSession in the function it acts like it is importing the sessions, gathering the commands etc. but it doesn't actually import the commands. I have to run Import-PSSession from the console against the session to get the commands imported. I've tried adding scopes to things and playing around with different ways of importing the session but nothing has worked. Googling hasn't had much luck either so I'm hoping someone here has a fix for this.

Here's the code I am using.

Powershell
$Global:ExchangeSession=New-PSSession...

Lync to Skype PowerShell

$
0
0

Hi All, working on this messy issue with a Lync to Skype migration.

Here's the situation, we've migrated our client off of Lync to Skype for Business 2016 via Office 365.

I'm working on cleaning up left over problems with the migration.

In particular, some of the computers have both Lync and Skype installed. This results in Skype not working.

I've found this script and am testing it out -

Powershell
# Remove Lync and Skype if installed.$programs=@(SkypeforBusiness,MicrosoftLync)foreach($programin$programs){$app=Get-WmiObject-ClassWin32_Product|Where-Object{$_.Name-match$program}if($app-ne$Null){$app.Uninstall()}}

We have an exe file in place on a NAS and I am wanting to run it in tandem with the above. Something to the tune of

Powershell
start-Process-Wait-FilePath"nas path"-ArgumentList"/S"...

Run IF 15 minutes or older password

$
0
0

There's an account I want to disable for administrative purposes if the last password reset is 15 minutes or older. I'm getting stuck because I think storing the Get-Date as a variable doesn't keep the same format when I try to add 15 minutes... example below

Powershell
$Time=Get-Date$lastpass=get-aduserAdminUSERHere-propertiespasswordlastset|select-PropertypasswordlastsetIF($Time=$Lastpass.AddMinutes(15)){"Lock It Up!"}
Powershell
butthenthishappens
Powershell
Methodinvocationfailedbecause[Selected.Microsoft.ActiveDirectory.Management.ADUser]doesnotcontainamethodnamed'AddMinutes'.Atline:1char:7+IF($Time=$Lastpass.AddMinutes(15)){+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+CategoryInfo:InvalidOperation:(AddMinutes:String)[],RuntimeException+FullyQualifiedErrorId:MethodNotFound
...

Will this PS script leave credientials in memory?

$
0
0

“$servers= get-content 'D:\script-xxxxx\remoteaccessforadmin\server.txt'
$output = 'D:\script-xxxxx\remoteaccessforadmin\test.csv'
$results = @()

foreach($server in $servers)
{
$admins = @()
$group =[ADSI]"WinNT://$server/Administrators"
$members = @($group.psbase.Invoke("Members"))
$members | foreach {
$obj = new-object psobject -Property @{
Server = $Server
Admin = $_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)
}
$admins += $obj
}
$results += $admins
}
$results| Export-csv $Output -NoTypeInformation”

Viewing all 15370 articles
Browse latest View live


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