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

Moving from DocTag to AIP

$
0
0

Hi.

I am moving from DocTag to Azure Information Protection. I found some script as a reference for reading Word document custom attributes. I was able to edit the scritpt to read the relevant attribute and based on its value set the correct AIP label. It works fine, it reads the attribute correctly and then set AIP attribute and refresh visual marking. But even though for every document I get this error

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)
At C:\script\DocTag2AIP.ps1:11 char:13+     foreach($property in $customProperties) {+             ~~~~~~~~~+ CategoryInfo          : OperationStopped: (:) [], COMException+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException

The script looks like this

$files = @(Get-ChildItem C:\Users\luberan\Desktop\*.docx -Recurse)

foreach ($file in $files) {
    $fileName = $file.Name
    $filePath = $file.DirectoryName
    $directory = $filePath + "\" + $fileName
    $word = New-Object -comobject Word.Application
    $document = $word.documents.open($directory)
    $binding = "System.Reflection.BindingFlags" -as [type]
    $customProperties = $document.CustomDocumentProperties
    foreach($property in $customProperties) {
        $vl = [System.__ComObject].InvokeMember("value",$binding::GetProperty,$null,$property,$null)
        if ($vl -eq "PU - For Personal Usage") {
            $word.Application.Quit()
            Set-AIPFileLabel -Path $directory -LabelId id1 -PreserveFileDetails
            $word = New-Object -comobject Word.Application
            $document = $word.documents.open($directory)
            $document.Save()
        }
        elseif ($vl -eq "C1") {
            $word.Application.Quit()
            Set-AIPFileLabel -Path $directory -LabelId id2 -PreserveFileDetails
            $word = New-Object -comobject Word.Application
            $document = $word.documents.open($directory)
            $document.Save()
        }
        elseif ($vl -eq "C2") {
            $word.Application.Quit()
            Set-AIPFileLabel -Path $directory -LabelId id3 -PreserveFileDetails
            $word = New-Object -comobject Word.Application
            $document = $word.documents.open($directory)
            $document.Save()
        }
        elseif ($vl -eq "C3") {
            $word.Application.Quit()
            Set-AIPFileLabel -Path $directory -LabelId id4 -PreserveFileDetails
            $word = New-Object -comobject Word.Application
            $document = $word.documents.open($directory)
            $document.Save()
        }
        elseif ($vl -eq "C4") {
            $word.Application.Quit()
            Set-AIPFileLabel -Path $directory -LabelId id5 -PreserveFileDetails
            $word = New-Object -comobject Word.Application
            $document = $word.documents.open($directory)
            $document.Save()
        }
    }
    $word.Application.Quit()
}

The provided script is exact copy of the real script, I just replaced AIP label IDs by id1 - id5.

How to fix the issue please? Or is the script completely wrong?


get-aduser from a csv file

$
0
0

Powershell newbie...

I was given a spreadsheet with email address from HR department. Was asked to provide full name and account name that went with the email address. Tried the follwing, but have not been able to get it to work.

Import-Module ActiveDirectory
$UserList=Import-Csv c:\employeelist.csv
FOREACH ($Person in $UserList) 
{
get-aduser -Filter {emailAddress -eq $Person} -SearchBase "dc=domainname"-Server prod-dc -Properties Name,emailAddress,samAccountName |
Select Name,emailAddress,samAccountName |
Export-CSV c:\allinfo.csv -NoTypeInformation
}

I'm seeing:

CategoryInfo          : NotSpecified: (:) [Get-ADUser], ADException

FullyQualifiedErrorId : The search filter cannot be recognized,Microsoft.ActiveDirectory.Management.Commands.GetADUser

Remotely add Domain User to local group

$
0
0

I've been playing with this for some time, and I seem to be missing something.  I am trying to develop a script that reads and XML file containing a list of computers, local groups, and names of domain users (and computers) to be added to the local groups.  I would like to be able to run this from a management workstation. 

I've been working from these two posts.

http://blogs.technet.com/b/heyscriptingguy/archive/2010/08/19/use-powershell-to-add-domain-users-to-a-local-group.aspx

http://blogs.technet.com/b/heyscriptingguy/archive/2008/03/11/how-can-i-use-windows-powershell-to-add-a-domain-user-to-a-local-group.aspx

It appears that the command $objGroup = [ADSI]("WinNT://atl-fs-001/Administrators") only works locally.  I have not been able to figure out any format that allows me to get the information remotely.  So I figured I would use Invoke-Command to execute the two lines of code remotely. 

Invoke-Command -ComputerName RemoteServer {
$de = [ADSI]"WinNT://RemoteServer/Administrators,Group"
$de.psbase.invoke("Add",([ADSI]"WinNT://Domain/User").path)
}

(I am trying it first with fixed, valid values - change to variables when I get things figured out.)  That gave me the error:

Exception calling "Invoke" with "2" argument(s): "Number of parameters specified does not match the expected number."+CategoryInfo          :NotSpecified: (:) [], MethodInvocationException+FullyQualifiedErrorID :DotNetMethodTargetInvocation+PSComputerName        :RemoteServer

I need help on what to try next.

Thanks.


. : | : . : | : . tim

Powershell Script to monitor a file for specific string

$
0
0

Hi Everyone,

I am new to powershell scripting. Currenlty I am trying to do a script which will monitor a file for a specific string for particular time and continue to next step if the strings created in the file.

For example, I need a Powershell Script equivalent below Linux script.

starttime=$(date +%s)
counter=0
while [ $counter -le 0 ]
do
counter=`cat logs/custom.log | grep "The Agent is now enabled" | wc -l`
sleep 5
        runningtime=$(date +%s)
        if [ $runningtime == $[$starttime+50] ]; then #if running time = start time + 30 seconds
            echo "Agent is not started within 30 Seconds timeframe. Please check logs"
            break
        fi
done


Can someone please help me.

Need to get sessions disconnected 10 days ago

$
0
0

Hi Techies, 

I have a requirement where I need to fetch machines which got disconnected (CITRIX) 10 days ago. I am able to fetch all the disconnected sessions with SessionStateChangeTime. Something like this:

MachineName     SessionStateChangeTime

ABCDI051          9/4/2018 8:51:02 PM
ABCDJ010          10/31/2018 2:37:07 PM
ABCDJ011          10/29/2018 7:56:03 PM
ABCDJ015          10/29/2018 4:01:49 PM
ABCDJ016          10/31/2018 1:01:42 PM

I need to fetch machines that were disconnected longer than 10 days back from today (31st Oct 2018). 

I tried to do this:

$10DaysBack=(Get-date).addDays(-10).ToString('MM/dd/yyyy hh:mm:ss tt')

Get-BrokerDesktop -SessionState Disconnected -MaxRecordCount 6000 | where ('$_.SessionStateChangeTime' -le '$10DaysBack') | Select HostedMachineName,SessionStateChangeTime

This isnt working and gives me no output (as if there are no machines that were disconnected longer than 10 days back). 

Any help will be appreciated. 

Regards, 

AK


Thanks, Arun.

PowerShell: how to convert .msg (e-mail) files to .eml files

$
0
0

I would like to know if it's possible to convert .msg files into .eml files. I have a folder containing several .msg (mail) files but I need to convert them into .eml files. I would like to use PowerShell for this job, and I have taken a look at the System.Net.Mail.SMTPClient and System.Net.Mail.MailMessage objects, but so far i haven't found the solution for conversion .msg to .eml. Please help me out here.

Mark

Forcing windows 7 theme to change across the whole network

$
0
0

Hi,

I am working for an advertising company as the IT apprentice ive been tasking with changing the background off all the machines on our network.

This would usually be an easy task as i can just set a GPO to change the screen saver, the issue I have is they want to the background to rotate between 5 images and to my knowledge you can only change windows 7 theme through GPO to new users.

Is there a way I can push a script out over the network that changes the windows 7 theme??

Any help is greatly appreciated.

Thanks

Jack

String with spaces fails in start-process PowerShell.exe - what am i missing?

$
0
0

This is a very simplified version of a real world problem. (The real world script file is many thousands of lines (6800). I mention this is case someone is drawn to suggest that the code in script.ps1 in the problem below, is passed in as a scriptblock.)

I am starting a new process from PowerShell.exe. It is another PowerShell instance. I am starting it as a different user, but that is probably not significant to the question. Into that process I am passing a script file name with a SPACE in the path. This fails.

Here is the code content for the script.ps1 file.

Write-Host "Sleeping"

Start-Sleep -seconds 2

Here is the code for the parent which starts script.ps1

$PScred = get-credential 'domain\username'

$ScriptFile = "C:\test space\script.ps1"

Start-Process PowerShell.exe -Wait -Credential $PScred -WorkingDirectory 'C:\' -ArgumentList "-file $ScriptFile" -PassThru

Expected behaviour is that PowerShell starts and the word sleeping is printed for two seconds.

Actual behaviour is PowerShell starts and terminates with no output.

I also tried this command - with the same results.

Start-Process PowerShell -wait -credential $cred -ArgumentList "-file 'C:\test space\script.ps1'"

If I specify a path with no spaces, it works no problems.

I am wondering what I can do to overcome this behaviour, or if this is expected?

Thank you.

 


Get AD Computer Object Date last connected to domain

$
0
0

Before anyone pastes me a solution based on last logon please take a moment to tell me if there is another solution.  Last Logon is useless for a system that remains connected for extended periods without access.  As long as the host is connected and receiving patches I could care less if its inactive for a year.  I am trying to generate an AD Computer Object Aging report but I have found no other criteria I can use to validate if an AD object is offline for an extended period (which is a concern as patching would not occur).  I assumed there must be an AD Object characteristic that captured the date an object was seen by AD but then I suppose that would be a continually changing value if it was connected.

Since I cannot rely on LastLogon as a valid aging source are there are any other options?  For now I have a flawed aging reporting solution.  I am making due but it seems hard to believe that there is not some daily value that is in a date format that I can query reflecting evidence that the host is online despite no local or remote logins to the host.  Any insight is appreciated.  Thank you.

Refresh current user profile

$
0
0

I found this vbscript that does something similar to what i want to do in powershell. I want to be able to refresh the current user profile to see the change without logging out and back in. So is there a way to write this script in powershell

Set oShell = CreateObject("WScript.Shell")
Set oSHApp = CreateObject("Shell.Application")
Set oFSO = CreateObject("Scripting.FileSystemObject")

'Set Wallpaper to Path Below
sWinDir = oFSO.GetSpecialFolder(0)
sWallPaper = "C:\WINDOWS\DOMXP.bmp"

' Update Wallpaper in registry
oShell.RegWrite "HKCU\Control Panel\Desktop\Wallpaper", sWallPaper
wscript.sleep 3000

'Refresh Screen
oSHApp.ControlPanelItem cstr("desk.cpl")
' alt. oShell.Run "control desk.cpl"

Do Until oShell.AppActivate ("Display Properties")
Loop
oShell.SendKeys "{DOWN}{UP}{TAB 3}~"

'Minimise all Windows.
oSHApp.MinimizeAll

Set-SPUser : The parameterless Read method can only be used when this instance was initialized with an SPUser object.

$
0
0

I'm new to scripting and have run into an issue.  What we are trying to accomplish is for all our of SharePoint sites listed in a file, we want to gather a list of Users, compare them to the Admin array, then if they do not exist in the array, clear their permissions and add them back as Read only.  

$ListofSites =  Get-Content -Path "C:\sites.txt" 
$AdminUserLogin = @("DOMAIN\USER", "DOMAIN\USER2", 
                        )
foreach ($item in $ListofSites) 
    {
    Write-Host $item
    $Users = Get-SPUser -Web $item -Limit ALL | Format-Table -AutoSize  
        foreach ($user in $Users)
            {
            Write-Host $user
            If ($user -ne $AdminUserLogin) {Set-SPUser -Identity $._UserLogin -ClearPermissions -AddPermissionLevel 'Read'}
            Else {"User is an admin"}
            }
     }

I am getting this error--seems to be a piping error but I'm not really sure!  Help please!

Set-SPUser : The parameterless Read method can only be used when this instance was initialized with an SPUser object.
At C:\Scripts\SPReadOnly2.ps1:30 char:55
+             If ($user -ne $AdminUserLogin) {Set-SPUser <<<<  -Identity $._UserLogin -ClearPermissions -AddPermissionLevel 'Read'}
    + CategoryInfo          : InvalidData: (Microsoft.Share...SPCmdletSetUser:SPCmdletSetUser) [Set-SPUser], InvalidOperationException
    + FullyQualifiedErrorId : Microsoft.SharePoint.PowerShell.SPCmdletSetUser

Powershell: change default datetime format in script?

$
0
0
Hi,

I have an html report in which I include dates.
Now these dates appear in month/day/year. I want to prevent to need to change every date to format dd/mm/yyyy.
Practical example in SCCM:(Get-CMDeployment -CollectionName $CollectionX).deploymenttime gives 11/15/2017 09:15:33
whereas it should be 15/11/...

Is there a way to set it in beginning of script so dates are in correct format?
Tried
Set-Culture -CultureInfo de-de but that does not work.

Please advise.
J.

Jan Hoedt

mysqldump in powershell

$
0
0

Hi,

Need to put this in powershell, help please?

mysqldump -u remote -pr3m0t3@hs hs_db > c:\backup\hs_backup \hs_db_%date:/=%_%time:~0,2%-%time:~3,2%-%time:~6,2%.sql

SelfSignedCertificateEx

$
0
0

I use the script SelfSignedCertificateEx with no problem on windows 2016 server

The same command

New-SelfSignedCertificateEx -Subject "CN=WKS002" -EnhancedKeyUsage "Server Authentication" -Exportable -FriendlyName "Test_2 tls sql" -KeySpec Exchange -KeyUsage "KeyEncipherment","DataEncipherment" -NotAfter $([datetime]::now.AddYears(5)) -SignatureAlgorithm SHA256 -SubjectAlternativeName "WKS002"

executed on my windows 10 pro ends with the following error

ForEach-Object : CertEnroll::CObjectId::InitializeFromValue: Paramètre incorrect. 0x80070057 (WIN32: 87 ERROR_INVALID_PARAMETER)

Au caractère C:\utils\bin\New-SelfSignedCertificateEx.ps1:242 : 23
+         $EnhancedKeyUsage | ForEach-Object {
+                             ~~~~~~~~~~~~~~~~
    + CategoryInfo          : OperationStopped: (:) [ForEach-Object], ArgumentException
    + FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.Commands.ForEachObjectCommand

Any help welcome


thierry

Import-Csv with a column that needs to be multivalued

$
0
0

I am trying to import for Exchange having ResourceDelegates as a column in my CSV file.  When I import I get a [string]"Resource1,Resource2,Resource3" instead of @("Resource1","Resource2","Resource3").  I can use "-split ',' " but I don't want to mess up when I am running the commands straight from the command line parameter "-ResourceDelegates 'Resource1', 'Resource2', 'Resource3' " it is works beautifully. 

The issue with using "-split" is that I am trying to keep all capabilities of accepted data in the "Set-CalendarProcessing <Identity> -ResourceDelegates <delegates[]>" alive and well which includes being able to use our DistinguishedName's CN:  "LastName, FirstName".  "-split" would mess this up. 

CSV File sample data:

"Name","ResourceDelegates""GroupA","Resource1,Resource2,Resource3""GroupB","Resource1, Resource2, Resource3"

Function Test-CsvImportArray 
{
	Param(
		[Parameter(ValueFromPipelineByPropertyName = $true)]
		[string[]]$ResourceDelegates
	)"ResourceDelegates Count: $($ResourceDelegates.Count)""ResourceDelegates Value: $($ResourceDelegates)"
}

Then I check the variable using Import-Csv (only showing one Row of CSV import)::

PS D:\PowerShell> Import-Csv .\CSV\Resource_List.csv | Test-CsvImportArray
ResourceDelegates Count: 1
ResourceDelegates Value: Resource1, Resource2, Resource3
PS D:\PowerShell>

Now if I did it via the parameters on command line (only showing one Row of CSV import):

PS D:\PowerShell> Test-CsvImportArray -ResourceDelegates Resource1, Resource2, Resource3
ResourceDelegates Count: 3
ResourceDelegates Value: Resource1
ResourceDelegates Value: Resource2
ResourceDelegates Value: Resource3
PS D:\PowerShell>
What can I do to make this all happen by ONLY changing code in the function?  I don't want to typecast anything before piping to the import.


Find this post helpful? Does this post answer your question? Be sure to mark it appropriately to help others find answers to their searches.




Powershell and the robocopy /xd switch

$
0
0

Hello,

I am trying to assemble a robocopy command in a powershell script. If the list of excluded directories is sent to robocopy as an array, it does not work:

$reactIgnores = @( $reactjs + "\.git",$reactjs + "\node_modules",  $reactjs + "\build")

Robocopy /l $reactjs $synReactjs /mir /xd $reactIgnores


Yields an Exc Dirs line of:

Exc Dirs : C:\Users\me\Projects\prj\reactjs\.git C:\Users\me\Projects\prj\reactjs\node_modules C:\Users\me\Projects\prj\reactjs\build


And it doesn't work (descends into the .git directory immediately).

If I specify the excluded directories on the command line explicitly, it yields a different Exc Dirs line:

Robocopy /l /mir $reactjs $synReactjs /xd C:\Users\me\Projects\prj\reactjs\.git C:\Users\me\Projects\prj\reactjs\node_modules 

Exc Dirs : C:\Users\me\Projects\prj\reactjs\.git            C:\Users\me\Projects\prj\\reactjs\node_modules


And it works fine. What am I missing in the powershell array assembly? Does't work if I assemble the excluded directories as a string either - what is /xd looking for?


PS: it is impossible to setup code and output blocks correctly in this forum interface - this question is asked more clearly here:

https://stackoverflow.com/questions/53087761/robocopy-xd-ignores-a-list-of-directories

Erroneous Results from Get-ADUser

$
0
0

The below AD query gives me thousands of results, including four named: 7-Jan, 7-Mar, 1-Apr, 8-Mar.

Get-ADUser -Filter * -SearchBase "OU=Departments,DC=dom,DC=for" | Select-Object samaccountname | export-csv -Path c:\users\me\desktop\wtf.csv -NoTypeInformation

However, when I use Powershell to ask AD to show me users with the samaccountname of any from the above list I get nothing:

Get-ADUser -filter * -SearchBase "OU=Departments,DC=dom,DC=for" | Select-Object samaccountname | Where-Object {$_.samaccountname -eq "7-Jan"}

Does anyone have any idea or explanation for this?

Check if Automatic Updates are idle/running? Check if reboot needed?

$
0
0

Is there a way to find out if scheduled Automatic Updates are idle or in progress (checking, downloading, installing)?

Is there a way to find out, if scheduled Automatic Updates are done, if a reboot is needed to finish updating?

,

I am looking for a low-maintenance and free way to set up overnight scheduled automatic updates, that can ONLY run at night and never during the day when people are using the machines. If a machine misses the overnight scheduled Window, that absolutely does not mean the updates should install the next morning when an employee logs on to the machine and is trying to get their work done.

In general I already know what needs to be done, though it's the finer points of saving energy that are a problem. I don't want to leave machines on all night. I want the machines to turn on, and do their automatic updates from Microsoft as scheduled (no need for WSUS). If a reboot is needed, then do that, and resume updating after the restart if needed. If all done and no restart needed, do some other maintenance tasks like defragging, and shut down the system.

The general plan goes like this:

  1. AD GPO, Computer policy: Set Windows Update service to Manual start so it cannot run during the daytime, ever. Stop the service if it is running.
  2. AD GPO, Computer policy: Set Windows Update to automatic updates, automatic install, at 2:00 am
  3. Power up machines overnight on a schedule (via Wake on LAN scheduler or BIOS timer), at 1:50 am
  4. AD GPO, Computer policy: Scheduled task to run script every day with Local System user account at 1:55 am
  5. Script starts Windows Update service (net start wuauserv)
  6. Script waits about ten minutes for Windows Automatic Updates to start. (2:05 am)
  7. Poll Windows Update to check status. If busy with checking, downloading or installing, then wait another five minutes and repeat polling task.
  8. If Windows Update is found to be idle, check if Restart required. If yes, schedule a one-time startup task to restart this script, and reboot the system. On system restart, this script is run again, Windows Update service starts, and updates may continue to install if required.
  9. If Windows Update is found to be idle, and no restart is needed, defrag all local hard drives, and then shut down the system.

,

It seems simple enough, but I don't see how to read the state of the Windows Update API when it is doing scheduled automatic updates.

It seems possible to try to grep the current status / progress out of the WindowsUpdate.log, but that looks like an extremely painful roll-your-own solution, and I've not found a script yet that's already capable of reading the logfile to get the current state of the Windows Update service.




ps script to get AD attribute by email

$
0
0

Hello!

I need some advice. I user this PS line

Get-ADUser -Filter "EmailAddress -eq 'x.y@xy.com'" -Properties extensionAttribute4

I would like to make a tool to be able to copy only the email address and it gives back the attribute. I just don know where to start.

Compilation Error

$
0
0

Hello All,

Please fix the compilation error of below script which was created to get the SystemSKUNumber , when we run the script it get stopped if any of the machine is not accessible.

Const wbemFlagReturnImmediately = &h10
Const wbemFlagForwardOnly = &h20
Const ForReading = 1, ForWriting = 2, ForAppending = 8

	Set ofs = CreateObject("Scripting.FileSystemObject")
	Set oF = oFs.opentextFile("c:\temp\surfaceinput.txt",forreading)
	Set oFout = oFs.createtextFile("c:\temp\surfaceoutput.csv",forwriting)
	oFout.writeline "Server,Manufacturer,Model,Name,SystemSKUNumber"
	strQuery = "SELECT * FROM Win32_ComputerSystem"
	Do While oF.AtEndOfStream <> True  
		strComputer = ucase(trim(oF.readline))
		Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
		Set checkshareresult = ofs.ExecQuery("Select * from Win32_Share where name ='" & sharename & "'")
 If checkshareresult.Count <> 0 Then
  For each vars in checkshareresult
   If not LCase(vars.Status) = "ok" Then
    oFout.writeline strComputer & "," & "Not accessible"
   Else
    oFout.writeline strComputer & "," & "Accessible"
	End if

		Set colItems = objWMIService.ExecQuery(strQuery, "WQL", wbemFlagReturnImmediately + wbemFlagForwardOnly)
		For Each objItem In colItems
			oFout.writeline strComputer & "," & objItem.Manufacturer & "," & objItem.Name & "," & objItem.SystemSKUNumber
			Next
 End If
		Set objWMIService = nothing  
	loop
	of.close
	oFout.close


THANKS SURESH M

Viewing all 15028 articles
Browse latest View live


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