powershell – NTP Time – Get time of remote NTP server in DOS

I’ve been looking at many forums and google results and can’t find what I’m looking for.

Essentially I want to get an accurate time from a public NTP server, in DOS or powershell.
I know there’s the w32tm which can query a remote ntp server, but the result it gives is how much out my computer time is, not the actual time of the remote ntp server.

I’ve found various windows apps that work exactly as I want, but i can’t get the output to a variable to do anything with. I’m dead surprised there’s no .exe that just gets the time from a source, or that it wasn’t written into w32tm.

Something like ntpquery.exe pool.ntp.org (followed maybe like a timezone or something) with an output of the date / time is all I’m after.

Perhaps one of you knowledgeable folk know of a way I can do this?

Many thanks in advance.

Deleting all document versions but the current from a SharePoint document library using PowerShell

I have a SharePoint document library with a large number of documents and versions. My task is to create a PowerShell script to delete all versions but the current for each document.

When I tried to delete the versions within my iteration, I got an error saying that the “collection was modified”. Fair enough, I can’t change the collection I’m looping through.

So instead I added the versions to be deleted in an array to be processed later outside the loop. But that didn’t work eighter, I get “Exception calling Delete with 0 argument(s): Object reference not set to an instance of an object.”

I have reviewed all similar Q&As for this issue on this site, but no answer is spot on. Can anyone give a hint on what is going on here? Thanks so much for any help.

asnp *sh*
$site = new-object Microsoft.SharePoint.SPSite("http://somesite")
$web = $site.RootWeb
$list = $web.Lists("Dokument")
cls
$versionsToDelete = @()

foreach ($listItem in $list.Items)
{
    foreach ($ver in $listItem.Versions)  
    {
        if (!$ver.IsCurrentVersion)
        {
            $versionsToDelete += $listItem.Versions.GetVersionFromLabel($ver.VersionLabel)
        }
    }
}

for($i=0;$i -lt $versionsToDelete.Count;$i++)
{
    write-host "Trying to delete" $versionsToDelete.VersionLabel($i)
    $versionsToDelete($i).Delete()
}

$web.Dispose()
$site.Dispose()

Unable to query SharePoint list by date using CAML and PowerShell

I am trying to use a CAML query through PnP powershell to get a list of items. My code looks like this:

        $today = get-date -Format "yyyy-dd-MM"
        $today = $today + "T00:00:00"
        write-host $today
        $items=  Get-PnPListItem -List "Users" -Query "<View><Query><Where><Eq><FieldRef Name='DueDate'/ ><Value IncludeTimeValue='FALSE' Type='DateTime'>$($today)</Value></Eq></Where></Query></View>"
          

However, when executing this in PowerShell am getting “Cannot complete this action”.

Any idea how it can be solved?

Get username from full name – PowerShell function

I would like your opinion of my PowerShell function. Does it follow conventions, and what could can I do to improve it. It is made to create LDAP friendly username in Serbian language.

function Get-UsernameFromFullName
{
    (CmdletBinding())
    param
    (
        (Parameter(Position = 0, Mandatory = $true, ValueFromPipelineByPropertyName = $true))
        (string)
        $FullName,

        (Parameter(Position = 1, Mandatory = $false, ValueFromPipelineByPropertyName = $true))
        (ValidateSet('First', 'Last'))
        (string)
        $LastNamePosition = 'First'
    )
    
    $usernameComponents = $FullName.ToLower().Split(" ")

    switch ($LastNamePosition)
    {
        'First' { $firstName = $usernameComponents.Length -1; $lastName = 0 }
        'Last'  { $firstName = 0; $lastName = $usernameComponents.Length -1 }
        Default { $firstName = $usernameComponents.Length -1; $lastName = 0 }
    }

    $chars = ($usernameComponents.Get($firstName) + "." + $usernameComponents.Get($lastName)).ToCharArray()

    foreach($char in $chars)
    {
        switch($char)
        {
            'ć' { $segment = "c" }
            'č' { $segment = "c" }
            'đ' { $segment = "dj" }
            'š' { $segment = "s" }
            'ž' { $segment = "z" }
            default { $segment = $char }
        }
        $Username += $segment
    }
    return $Username
}

Here is a link to GitHub page of the actual .psm1 file.

This is an example of the function usage:

enter image description here

Add empty line in an array in PowerShell

I’m a novice in PowerShell and just started to learn this stuff. I have been following this link

https://docs.microsoft.com/en-us/azure/virtual-machines/scripts/virtual-machines-powershell-sample-collect-vm-details#code-try-0

to get a list of all VM’s. It’s working fine. I want to insert a ‘line break’ or a blank line whenever the resource group name changes.

How do I do this?

Thanks

file conversion – Am I able to specify the filepath when using .SaveAs method for documents with Powershell?

I’ve got a script for converting PDFs to .docx format and in its current state it saves the word documents in the same location, I was wondering if it’s possible to specify the file-path when using the Document.SaveAs method? I’m using a function that allows manual selection of an export folder and stores that in a variable, but haven’t managed to utilise it. Is there some way I can tell powershell to use this variable as the export path for the word documents?

This is what I have so far:

$documents_path = $PSScriptRoot

Function Get-Folder($initialDirectory) {
    (System.Reflection.Assembly)::LoadWithPartialName("System.windows.forms") | Out-Null
    $foldername = New-Object System.Windows.Forms.FolderBrowserDialog
    $foldername.Description = "Select an export folder"
    $foldername.rootfolder = "MyComputer"
    if($foldername.ShowDialog() -eq "OK"){
        $folder += $foldername.SelectedPath
    }
    return $folder
}

$folder = Get-Folder
$word_app = New-Object -ComObject Word.Application

Get-ChildItem -Path $documents_path -Filter *.pdf | ForEach-Object {
    $document = $word_app.Documents.Open($_.FullName)
    $pdf_filename = "$($_.DirectoryName)$($_.BaseName).docx"
    $document.SaveAs((ref) $pdf_filename, (ref) 16)
    $document.Close()
}

$word_app.Quit()

I’ve looked at the syntax when using the .SaveAs method and it didn’t look like there was a way to specify the file-path, I was hoping to be able to use $folder but couldn’t get it to work without errors. It’s by no means integral, just some QOL I’d like to include. I’m not sure if there’s a better way of converting/saving the files, I’m not very experienced with powershell so this is the best I’ve been able to come up with so far.

powershell – how to list bit depth and bit rate of all files in a set of nested folders?

I have a large collection of music and would like to know the bit rate and bit depth of the individual files.

I am using Windows 10 and it does not show properties of all the files in folders (there is no way to ‘expand’ a folder as on a mac when in detail view). I know how to add the bit depth label and bit rate label to a window when I open the folder to view the files in it. But I need to find all files for example that have a bit depth of 24 bits in a set of nested folders that contain many music files : some 16 bit and some 24 bit. The goal of this exercise is to segregate all files> 16 bits to another directory.

I tried using mp3 tag, an application that lists these properties for all files in a directory (even those deeply nested) but it is agonizingly slow on my laptop (30000 files would take 5 hours just to list). I tried using mediainfo (from mediaarea.net) but it only works on individual files. I tried mapping the network folder (where the files exist) and using the ‘tree’ command but it does not work either. A google search for ‘recursively list bit rate of all files in windows’ gave a few links one of which was 11 years old here. I modified it for flac like so

function Get-FLACs( (string)$directory = "$pwd", (int)$minimumBitrate = 32 ) {
  $shellObject = New-Object -ComObject Shell.Application
  $bitrateAttribute = 0

  # Find all flac files under the given directory
  $flacFiles = Get-ChildItem $directory -recurse -filter '*.flac'
  foreach( $file in $flacFiles ) {
    # Get a shell object to retrieve file metadata.
    $directoryObject = $shellObject.NameSpace( $file.Directory.FullName )
    $fileObject = $directoryObject.ParseName( $file.Name )
    Write-Output ("filename",$fileObject)

      # Find the index of the bit depth attribute, if necessary.
      for( $index = 5; -not $bitdepthAttribute; ++$index ) {
        $name = $directoryObject.GetDetailsOf( $directoryObject.Items, $index )
        if( $name -eq 'Bit depth' ) { 
          $bitdepthAttribute = $index 
          Write-Output ("bit depth index",$bitdepthAttribute)
          $bitdepthString = $directoryObject.GetDetailsOf( $fileObject, $bitdepthAttribute )
          Write-Output ("bit depth",$bitdepthString)
          }
      }
    }

I tried to test the above script on a folder with 2 flac files both of which are 24 bit depth and 96 khz sample rate.

The output of the script above was

 PS C:UsersStefanDownloadsCompare formats> Get-FLACs
filename


Application  : System.__ComObject
Parent       : System.__ComObject
Name         : BATIK - The Old Man FLAC
Path         : C:UsersStefanDownloadsCompare formatsBATIK - The Old Man FLAC.flac
GetLink      :
GetFolder    :
IsLink       : False
IsFolder     : False
IsFileSystem : True
IsBrowsable  : False
ModifyDate   : 6/15/2014 11:27:46 PM
Size         : 66131611
Type         : FLAC File

bit depth index
174
bit depth

filename
Application  : System.__ComObject
Parent       : System.__ComObject
Name         : Carmen Gomes Inc - A 1000 Shades of Blue FLAC
Path         : C:UsersStefanDownloadsCompare formatsCarmen Gomes Inc - A 1000 Shades of Blue FLAC.flac
GetLink      :
GetFolder    :
IsLink       : False
IsFolder     : False
IsFileSystem : True
IsBrowsable  : False
ModifyDate   : 4/26/2014 8:41:08 PM
Size         : 34188974
Type         : FLAC File

For the first file it found the attribute ‘bit-depth’ and its index (174) but did not find the attribute for the second file. In neither case did the script actually find the correct bit depth but just left the value blank.

script – Powershell get-eventlog fails after KB4565503

On a home network, a desktop has read the eventlog of a laptop up to 2020-06-30. The first time since then I ran the script I got

get-eventlog : Attempted to perform an unauthorized operation

This behavior also occurs in administrator mode.

Both the desktop & the laptop were updated with KB4565503. That update says it included a bunch of security updates. Okay, but what do I need to do to get the script to run?

get-errors.ps1:

Param((parameter(Mandatory=$true))
(string)$startDate
)

$after = Get-Date -Date $startDate

Write-Host "Getting power data"
$power = get-eventlog -computername geolaptop -log System -instanceid (1,42) -after $after | where-object {$_.Source -eq "Microsoft-Windows-Kernel-Power" -or $_.Source -eq "Microsoft-Windows-Power-Troubleshooter"}

Write-Host "Create power CSV file"
$power | select-object "eventid", "timegenerated" |export-csv power.csv

Write-Host "Getting error data"
$errors = get-eventlog -computername geolaptop -log System -instanceid (17) -after $after

Write-Host "Create errors CSV file"
$errors | select-object "timegenerated" |export-csv errors.csv

Write-Host "Populate MySQL tables"
.sessions

Frequently getting 429 error on using the PnP powershell script, this script is calling OneDrive content. How can we fix this issue?

We have configured 5-6 window schedulers to call powerShell scripts to fetch the OneDrive content. but PnP powershell script throwing below errors on the VM event viewer:

  1. Faulting application name: dwm.exe, version: 10.0.19041.1, time
    stamp: 0x9a82ecd.
  2. The storage optimizer couldn’t complete slab
    consolidation on Temporary Storage.
  3. Faulting application name:
    PowerShell.EXE, version: 10.0.19041.1, time stamp: 0xc37343ae
    Faulting module name: KERNELBASE.dll,